Json-lib uses "2", json-lib "2"
The previous article mainly focused on the use of json-lib to implement conversion between JSON strings and objects in java, ignoring the functions of json-lib itself. Two Classes in json-lib are important: JSONObject and JSONArray, because of their different names, implement different functions. JSONObject processes object format ({}), JSONArray processes the array format ([]). The following describes how to use JSONArray.
JSONObject
I. Source Code
The JSONObject class contains multiple overloaded elements (). This method stores data to the JSONObject class. by viewing the source code, it is found that JSONObject implements data storage through Map, see the following source code,
private Map properties; /** * Construct an empty JSONObject. */ public JSONObject() { this.properties = new ListOrderedMap(); }
The JSONObject has the Map attribute, which is a ListOrderMap object. The element () method adds data to properties because properties is map, you can use the Map Operation Method to operate the properties attribute. JSONObject encapsulates the properties operation method. From the source code, you can find that there are many overloaded get () methods, such,
public Object get( String key ) { verifyIsNull(); return this.properties.get( key ); }
From the get method, we can see that the get method of Map is used.
After the above source code analysis, we can know that the operation on JSONObject is the operation on Map.
Ii. Use
Public static void TestJSONObject () {// create a JSONObject jsonObject = new JSONObject (); jsonObject. element ("my", "this is my first"); String str = jsonObject. toString (); String keyValue = jsonObject. getString ("my"); System. out. println ("str:" + str); System. out. println ("keyValue:" + keyValue );}
Print the result,
str:{"my":"this is my first"}keyValue:this is my first
With the JSONObject instance, you can use the element () method to add the values corresponding to the key and key. print out the strings and you can see that they are in the JSON object format, it can be seen that this form is the same as converting a class into a string in JSON format. You can regard "my" as a Class Attribute and "this is my first" as the attribute value.
With this understanding, you can convert a JSON string into a JSONObjec object and then obtain the values in the object, as shown below,
public static void getValue(){ String str="{\"my\":\"this is my first\",\"second\":\"this is second!\"}"; JSONObject jsonObject=JSONObject.fromObject(str); String my=jsonObject.getString("my"); String second=jsonObject.getString("second"); System.out.println("my:"+my); System.out.println("secode:"+second); }
The output is as follows,
my:this is my firstsecode:this is second!
It can be seen that we can get the desired value without converting the JSON string into the corresponding class. to convert it to the corresponding class, we must have the following class,
package com.cn.study.day3;public class TestAndMy { private String my; private String second; public String getMy() { return my; } public void setMy(String my) { this.my = my; } public String getSecond() { return second; } public void setSecond(String second) { this.second = second; } }
The code for generating a class is as follows,
Public static void getValue () {String str = "{\" my \ ": \" this is my first \ ", \" second \ ": \" this is second! \ "}"; JSONObject jsonObject = JSONObject. fromObject (str); String my = jsonObject. getString ("my"); String second = jsonObject. getString ("second"); System. out. println ("my:" + my); System. out. println ("secode:" + second); System. out. println ("-------------------------------"); // generate the class TestAndMy test = (TestAndMy) jsonObject. toBean (jsonObject, TestAndMy. class); System. out. println ("my:" + test. getMy () + ", second:" + test. getSecond ());}
In some cases, it may not be such a simple string, but rather complicated. How should we obtain the desired value? Let's look at the example below,
public static void complex(){ String str="{\"data\":{\"my\":\"this is my first\",\"second\":\"this is second!\"}}"; JSONObject jsonObject=JSONObject.fromObject(str); JSONObject dataObject=jsonObject.getJSONObject("data"); System.out.println("dd:"+dataObject.toString()); }
Print the result,
dd:{"my":"this is my first","second":"this is second!"}
In the above example, it is no longer a JSON object, but data corresponds to a JSON object. After obtaining the JSONObject instance, we know that the underlying storage of a JSONObject instance is Map, you can use the get method to obtain the value corresponding to the key. You can use the get (String key) method. This method returns an Object, which cannot be processed after the Object is returned, this method does not work. You can use getString (String key). This method returns the String form of the value corresponding to the key. For the above example, we should return {"my ": "this is my first", "second": "this is second! "}, Still cannot reach the goal of final parsing. Finally, we can use the getJSONObject (String key) method and return the JSONObject object. Then we can use this object for full parsing.
JSONArray
I. Source Code
View the source code of JSONArray. We can find that the bottom layer of JSONArray is implemented by List, that is, the JSONArray object is used to store data in List,
/** * The List where the JSONArray's properties are kept. */ private List elements;/** * Construct an empty JSONArray. */
public JSONArray() { this.elements = new ArrayList(); }
All values in JSONArray are placed in elements, and elements is an instance of ArrayList. The underlying layer of ArrayList is implemented through arrays. Therefore, JSONArray operations are based on arrays.
JSONArray provides an overloaded element () method to add data and an overloaded get () method to retrieve data.
Ii. Use
The following is an example of using JSONArray,
Public static void testJSONArray () {String array = "[\" 123 \ ", \" this is my test \ ", {\" address \": \ "Chaoyang District, Beijing \", \ "age \": \ "23 \", \ "name \": \ "JSON \"}] "; JSONArray jsonArray = JSONArray. fromObject (array); // because the bottom layer of JSONArray is an array, the following method is used to access the element String str1 = jsonArray. getString (0); String str2 = jsonArray. getString (1); String str3 = jsonArray. getString (2); System. out. println ("str1:" + str1 + ", str2:" + str2 + ", str3:" + str3 ); // because the third element is a JSON string in the form of an object, you can obtain the third element JSONObject o3 = jsonArray. getJSONObject (2); // obtain the JSONObject System. out. println ("address:" + o3.getString ("address") + ", age:" + o3.getString ("age "));}
The printed result is,
Str1: 123, str2: this is my test, str3: {"address": "Chaoyang District, Beijing", "age": "23", "name ": "JSON"} address: Chaoyang district, Beijing, age: 23
Because JOSNArray is implemented by ArrayList, The getString () method is used here to obtain the string at each index, but it cannot be completely parsed, therefore, you can use the getJSONObject () method to obtain the object at the third position and parse the object.
From the above description, both JSONArray and JOSNObject classes can store data, but they are used in different ways. This is precisely the difference that leads to different parsing methods.
If anything is incorrect, please point it out. Thank you!