What is json? A lightweight data exchange format with good readability and ease of writing.
Differences between json and xml
1. The data readability of JSON and XML is basically the same.
2. JSON and XML have the same rich parsing Methods
3. JSON is smaller than XML.
4. easier interaction between JSON and JavaScript
5. JSON is less descriptive than XML.
6. JSON is much faster than XML.
JSON parsing can be divided into the following categories:
JSONObject: it can be viewed as a json object, which is the basic unit of the JSON definition in the system. It contains a pair of Key/Value values. Its response to an External call (External: Applying the value output by the toString () method) is a standard string (for example, {"JSON": "Hello, World "}, the outmost is enclosed by braces, and the Key and Value are separated by the colon ). The operation format for Internal (Internal) behaviors is slightly. For example, to initialize a JSONObject instance, reference the Internal put () method to add a value: new JSONObject (). put ("JSON", "Hello, World! "), Separated by commas (,) between keys and values. Value types include: Boolean, JSONArray, JSONObject, Number, String, or the default Value JSONObject. NULL object.
JSONStringer: json text Build class. According to official explanations, this class can help you quickly and conveniently create JSON text. Its biggest advantage is that it can reduce program exceptions caused by format errors. referencing this class can automatically create JSON text in strict accordance with the JSON syntax rules (syntax rules. Each JSONStringer object can only create one JSON text .. Its biggest advantage is that it can reduce program exceptions caused by format errors. referencing this class can automatically create JSON text in strict accordance with the JSON syntax rules (syntax rules. Each JSONStringer object can only create one JSON text.
JSONArray: it represents a group of ordered values. The format of toString output is enclosed in square brackets. Values are separated by commas (,) ([value1, value2, value3], you can use the short code to learn more about the format ). This class has the same internal query behavior. The get () and opt () methods can both return the specified value through the index, and the put () method is used to add or replace the value. The value Type of this class can also include: Boolean, JSONArray, JSONObject, Number, String, or the default value JSONObject. NULL object.
JSONTokener: json parsing class
JSONException: Exceptions in json
1. Construct json
First, we will build a simple json
// Generate json
Public String createJson (){
Try {
JSONObject jsonObject = new JSONObject ();
JsonObject. put ("id", "1 ");
JsonObject. put ("name", "Li Lei ");
JsonObject. put ("age", "30 ");
Return jsonObject. toString ();
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
Return "";
}
The resulting json data is: {"id": "1", "name": "Li Lei", "age": "30 "}
This is the simplest json data.
The process is to create a jsonobject object and add the property to the json
Next we will create a json data with an Array
// Generate json
Public String createJson (){
List Persons = getTestValues ();
Try {
JSONObject jsonObject = new JSONObject ();
JSONArray array = new JSONArray ();
For (int I = 0; I <persons. size (); I ++ ){
JSONObject person = new JSONObject ();
Person p = persons. get (I );
Person. put ("id", p. getId ());
Person. put ("name", p. getName ());
Person. put ("age", p. getAge ());
Array. put (person );
}
JsonObject. put ("persons", array );
System. out. println (jsonObject. toString ());
Return jsonObject. toString ();
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
Return "";
}
What we get from the above Code is this data.
{"Persons": [{"id": "1", "age": "30", "name": "Li Lei" },{ "id ": "2", "age": "25", "name": "Han Meimei"}]}
Code Analysis:
1. Create the outermost {} object jsonObject
2. Create an array object to save the information of two people
3. Create a jsonObject object in the loop to save everyone's information. Do not forget to add the object to the array after adding the attribute.
4. Add the array to the outermost layer object
In addition to using jsonObject and jsonArray to create json, we can also use JSONStringer
// Generate json
Public String createJson (){
JSONStringer jsonStringer = new JSONStringer ();
Try {
JsonStringer. object ();
JsonStringer. key ("id"). value ("1 ");
JsonStringer. key ("name"). value ("Li Lei ");
JsonStringer. key ("age"). value ("30 ");
JsonStringer. endObject ();
System. out. println (jsonStringer. toString ());
} Catch (Exception e ){
E. printStackTrace ();
}
Return jsonStringer. toString ();
}
In the above Code, we get the data {"id": "1", "name": "Li Lei", "age": "30 "}
Next, let's talk about
1. Create a JSONStringer object
2. Call the object () method to start creating and adding a header {(of course, it should appear in pairs with endobject)
3. added an attribute using key ("name"). added the attribute value through value ("value ").
4. After adding all the content, call the endobject () method to notify the json creation process.
Next we will use JSONStringer to create a json data with an Array
// Generate json
Public String createJson (){
List Persons = getTestValues ();
JSONStringer jsonStringer = new JSONStringer ();
Try {
JsonStringer. object ();
JsonStringer. key ("persons ");
JsonStringer. array ();
For (int I = 0; I <persons. size (); I ++ ){
Person person = persons. get (I );
JsonStringer. object ();
JsonStringer. key ("id"). value (person. getId ());
JsonStringer. key ("name"). value (person. getName ());
JsonStringer. key ("age"). value (person. getAge ());
JsonStringer. endObject ();
}
JsonStringer. endArray ();
JsonStringer. endObject ();
System. out. println (jsonStringer. toString ());
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
Return jsonStringer. toString ();
}
View the generated string
{"Persons": [{"id": "1", "name": "Li Lei", "age": "30" },{ "id ": "2", "name": "Han Meimei", "age": "25"}]}
Is the data we need
1. Create a New JSONStringer object to store the generated json data.
2. Call key ("persons") to add the key value of the array.
3. Call array () to notify the system. Next, an array appears with endarray)
4. Create a pair of {} using the object () method in the loop and add the attribute to the braces.
The above code shows how to generate json data.
Ii. parse JSON
Next we will parse the simplest json data as {"id": "1", "name": "Li Lei", "age": "30 "}
Let's take a look at the parsed code.
// Parse json
Public Person parserJson (){
String json = "{\" id \ ": \" 1 \ ", \" name \ ": \" Li Lei \ ", \" age \": \ "30 \"}";
Person person = new Person ();
Try {
JSONTokener jsonTokener = new JSONTokener (json );
// At this time, no json text has been read. Direct Reading is a JSONObject object.
// If the read position is "name":, nextValue is "Li Lei" (String)
JSONObject jsonObject = (JSONObject) jsonTokener. nextValue ();
Person. setId (jsonObject. getString ("id "));
Person. setName (jsonObject. getString ("name "));
Person. setAge (jsonObject. getString ("age "));
} Catch (Exception e ){
E. printStackTrace ();
}
Return person;
}
Resolution steps
1. convert a json string to a jsonTokener object
2. Call the nextValue () method of jsonTokener to convert json data to a jsonObject object.
3. Get the required value through getString (keyname)
Of course, nextValue () does not necessarily obtain a jsonObject object. For more information, see the code comments.
Next, parse the data with an array ~
{"Persons": [{"id": "1", "name": "Li Lei", "age": "30" },{ "id ": "2", "name": "Han Meimei", "age": "25"}]}
Public List ParserJson (){
String json = "{\" persons \ ": [{\" id \ ": \" 1 \ ", \" name \ ": \" Li Lei \", \ "age \": \ "30 \" },{ \ "id \": \ "2 \", \ "name \": \ "Han Meimei \", \ "age \": \ "25 \"}]} ";
List Persons = new ArrayList ();
Try {
JSONTokener jsonTokener = new JSONTokener (json );
// At this time, no json text has been read. Direct Reading is a JSONObject object.
// If the read position is "name":, nextValue is "Li Lei" (String)
JSONObject jsonObject = (JSONObject) jsonTokener. nextValue ();
JSONArray array = jsonObject. getJSONArray ("persons ");
For (int I = 0; I <array. length (); I ++ ){
JSONObject object = array. getJSONObject (I );
Person person = new Person ();
Person. setId (object. getString ("id "));
Person. setName (object. getString ("name "));
Person. setAge (object. getString ("age "));
Persons. add (person );
}
} Catch (Exception e ){
E. printStackTrace ();
}
Return persons;
}
1. Create a list to store the parsed information.
2. Convert the json string to a jsonTokener object and then convert it to a jsonObject object.
3. Get the json array through getJSONArray ("persons ")
4. parse the json array through loops. The parsed content is not explained.