Your location:Tech News>News>Script>Several ways to turn Java JSON string

Latest News

Several ways to turn Java JSON string

Author:fsadmin

Views:

  package com.doit8.test.jsontest;

  import java.util.ArrayList;

  import java.util.List;

  import com.alibaba.fastjson.JSON;

  import com.alibaba.fastjson.JSONArray;

  import com.alibaba.fastjson.JSONObject;

  import com.doit8.test.jsontest.pojo.Card;

  import com.doit8.test.jsontest.pojo.Person;

  public class App

  {

  public static void main (String [] args)

  {

  //1.JSON string generated by the object, the object contains an array of objects converted into a string JSON.

  Person person = new Person ();

  person.setUsername ( "xiejava");

  person.setSex ( "man");

  person.setAge (38);

  person.setEmail ( "xiejava @ ishareread.com ");

  Card card1 = new Card ();

  card1.setCardName ( "bankCard1");

  card1.setCardCode ( "888888888");

  card1.setCardValue (99999999);

  Card card2 = new Card ();

  card2.setCardName ( "bankCard1");

  card2.setCardCode ( "999999999");

  card2.setCardValue (222222222);

  // array of objects

  List cards = new ArrayList();

  cards.add (card1);

  cards.add (card2);

  person.setCardList (cards);

  String json = JSON.toJSON (person).toString ();

  System.out.println (json);

  //2.JSON string generated by JSON object

  JSONObject jObject = new JSONObject ();

  jObject.put ( "username", "xiejava");

  jObject.put ( "sex", "man");

  jObject.put ( "age", 38);

  jObject.put ( "email", "xiejava @ ishareread.com ");

  // array of objects packaged by JSONArray

  JSONArray jArray = new JSONArray ();

  jArray.addAll (cards);

  jObject.put ( "cardList", jArray);

  String json2 = jObject.toJSONString ();

  System.out.println (json2);

  // 3.JSON string generated by JSON object

  JSONObject jObject2 = new JSONObject ();

  jObject2.put ( "username", "xiejava");

  jObject2.put ( "sex", "man");

  jObject2.put ( "age", 38);

  jObject2.put ( "email", "xiejava @ ishareread.com ");

  // constructor JSON string

  String cardjsonStr1 = "{" cardName ":" bankCard1 "," cardCode ":" 888888888 "," cardValue ": 99999999}";

  String cardjsonStr2 = "{" cardName ":" bankCard2 "," cardCode ":" 999999999 "," cardValue ": 222222222}";

  JSON.parseObject (cardjsonStr1);

  JSONArray jArray2 = new JSONArray ();

  // JSON string converted to JSON object is added to the JSONArray, [note must use JSON.Converting the parseObject () method of the object as JSON, or otherwise the string, the string when transferred into JSON will double quotes.]

  jArray2.add (JSON.parseObject (cardjsonStr1));

  jArray2.add (JSON.parseObject (cardjsonStr2));

  jObject2.put ( "cardList", jArray2);

  String json3 = jObject2.toJSONString ();

  System.out.println (json3);

  }

  }

Recommend article

Relate article