/** * 1. The data and data objects contained in the string are parsed based on the JSON string received */System.out.println ("1. According to the received JSO n string to parse the data and data objects contained in the string "); The JSON string received by string result = "[{\" username\ ": \" Your name\ ", \" user_json\ ": {\" username\ ": \" Your name\ ", \ "nickname\": \ "Your Nickname\"}}] "; Generates a JSON object based on a string jsonarray json = new Jsonarray (result); Jsonobject jsonobject = json.optjsonobject (0); Gets the data item String username = jsonobject.getstring ("username"); Gets the data object Jsonobject user = Jsonobject.getjsonobject ("User_json"); String nickname = user.getstring ("nickname"); SYSTEM.OUT.PRINTLN (username); System.out.println (nickname); /** * 2.JSON Object converted to string String */System.out.println ("2.JSON object converted to string string"); Create Jsonobject Object JSONObject jsonobj = new Jsonobject (); Add Data jsonobj.put ("username", "Wanglihong") to the JSON; Jsonobj.put ("height", 12.5); Jsonobj.put ("Age", 24); Create a Jsonarray array and add the JSON to the array jsonarray = new Jsonarray (); Array.put (Jsonobj); Convert to String jsonstr = Array.tostring (); System.out.println (JSONSTR); /** * 3. The collection is converted to the Jsonarray object */System.out.println ("3. Set to Jsonarray object "); Initializes the ArrayList collection and adds the data list<string> List = new arraylist<string> (); List.add ("username"); List.add ("Age"); List.add ("Sex"); Initializes the HashMap collection and adds an array of map<string,string> Map = new hashmap<string,string> (); Map.put ("BookName", "CSS3 Combat"); Map.put ("PRIce "," 69.0 "); Initializes the Jsonarray object and adds the data jsonarray Jsonarray = new Jsonarray (); Jsonarray.put (list); Jsonarray.put (map); System.out.println (Jsonarray.tostring ());
Imported Package Name:
Import Org.json.JSONArray;
Import Org.json.JSONObject;
Dependencies for import:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
Output Result:
1. Parse the data and data objects contained in the string based on the JSON string received
Your name
Your nickname
2.JSON object converted to string string
[{"Age": "username": "Wanglihong", "Height": 12.5}]
3. Set conversion to Jsonarray object
[["Username", "age", "Sex"],{"price": "69.0", "BookName": "CSS3 Combat"}]
Java Foundation-json