JSON, the JavaScript Object natation, is a lightweight data interchange format that uses a completely language-independent text format to provide an ideal data interchange Format for Web application development.
JSON object:
Objects in JSON (object) begin with "{" and End With "}". Each item in the object is a Key-value pair, represented in the form of "Key:value", separated by commas between the key-value pairs. such as: {"name": "Coolxing", "Age" =24, "male": true, "address": {"Street": "Huilongguan", "City": "Beijing", "Country": "The" }}. The JSON object's key can only be of type string, and value can be string, number, false, True, null, object objects, or even array arrays, which means nested situations can exist.
JSON array:
The JSON array (array) ends with "[" and "]", and each element in the array can be string, number, false, True, null, object, or even array, and the elements between the arrays are separated by commas. such as ["coolxing", "," "Street": "Huilongguan", "City": "Beijing", "Country": "the".
In the last blog post, "Android Learning notes 44:json data parsing," We used the basic JSON API to create JSON data on the server side and parse the JSON data on the Android client.
In fact, to create and parse JSON data, you can also use Gson to do this. Gson is a Java class library that Google provides to map between Java objects and JSON data. With Gson, you can easily convert a string of JSON data to a Java object, or convert a Java object to the appropriate JSON data.
Two important methods of 1.GSON
In the Gson API, two important methods are provided: Tojson () and Fromjson () methods. where the Tojson () method is used to convert the Java object to the corresponding JSON data, the Fromjson () method is used to convert the JSON data to the corresponding Java object.
1.1 Tojson () method
The Tojson () method is used to convert Java objects to the corresponding JSON data, mainly in the following ways:
(1) String Tojson (jsonelement jsonelement);
(2) String Tojson (Object src);
(3) String Tojson (Object src, Type typeofsrc);
where method (1) is used to convert the Jsonelement object (which can be jsonobject, Jsonarray, etc.) into JSON data, and Method (2) is used to serialize the specified object object to the appropriate JSON data Method (3) is used to serialize the specified object object, which can include a generic type, into the appropriate JSON data.
1.2 Fromjson () method
The Fromjson () method is used to convert JSON data to the corresponding Java object, mainly in the following ways:
(1) <T> T Fromjson (jsonelement json, class<t> Classoft);
(2) <T> T Fromjson (jsonelement json, Type Typeoft);
(3) <T> T Fromjson (Jsonreader Reader, Type Typeoft);
(4) <T> T Fromjson (Reader Reader, class<t> Classoft);
(5) <T> T Fromjson (Reader Reader, Type Typeoft);
(6) <T> T Fromjson (String json, class<t> Classoft);
(7) <T> T Fromjson (String json, Type Typeoft);
The above method is used to parse different forms of JSON data into Java objects.
2. Generate JSON data on the server side
To generate JSON data on the server side using Gson technology, you first need to complete the following two preparations.
(1) A Web project was created using MyEclipse, where I named the project "Gsondemoproject" to simulate server-side Web services.
(2) Import Gson API packet Gson-2.2.1.jar to the project.
We can then create a Jsontools tool class in the project and implement a static method Createjsonstring (), in which JSON data is generated by using Gson technology. The specific implementation of the method is as follows.
public class Jsontools { /* * Function: Generates a JSON string * Param:value object objects that you want to convert to a JSON string
* Retuen:json string * Author: Blog Park-still indifferent * * Public
static string createjsonstring (OBJ ECT value) { Gson Gson = new Gson (); String string = Gson.tojson (value); return string;
}
}
As you can see, the exact implementation of this method is very simple, first creating a Gson object and then converting the incoming value (any Java object) into a JSON string by calling the Tojson () method of the Gson object.
By using this method, we can easily pass any Java object in and convert it into JSON data. As with the previous posting, we can implement a simple way to get a list of person objects in the Jsonservice class, as follows:
*
* Function: Get the Person object list
* Author: Blog Park-still
indifferent
/public list<person> Getlistperson () {
Lis t<person> list = new arraylist<person> ();
person person = new person (, "Jack");
person who = new person (, "Rose",);
person person = new person (, "Bob");
List.add (person);
List.add (person);
List.add (person);
return list;
In this method, we add 3 person objects to the list of lists, each with an ID (int), name (String), and age (int) three properties.
Finally, we need to create a jsonaction class that inherits from HttpServlet and implement the Dopost () method that responds to client requests to the server. Specifically as follows:
public void DoPost (HttpServletRequest request, httpservletresponse response)
throws Servletexception, IOException {
Response.setcontenttype ("text/html;charset=utf-");
Request.setcharacterencoding ("utf-");
Response.setcharacterencoding ("utf-");
PrintWriter out = Response.getwriter ();
list<person> Listperson = Jsonservice.getlistperson ();
String str = null;
String Action_flag = Request.getparameter ("Action_flag");
if (Action_flag.equals ("persons") {
str = jsontools.createjsonstring (Listperson);
}
Out.println (str);
Out.flush ();
Out.close ();
}
In this method, we get the Person object list Listperson by calling the Getlistperson () method in the Jsonservice class, and pass it into the Jsontools.createjsonstring () method. Generated JSON data for the Person object list. By publishing the project to Tomcat and using a browser to access the Web project, you can see the interface shown in Figure 1, where the Person object list has been successfully converted to JSON data.
Figure 1 The JSON data generated
3. Parsing JSON data on the client
In the Android project, we can access the URL shown in Figure 1 through the HttpURLConnection interface to get the JSON data on the server.
After you get the JSON data, you can restore the JSON data shown in Figure 1 to the corresponding Person object list by using the Fromjson () method mentioned earlier. Of course, because the Gson is used here, it is also necessary to import the Gson-2.2.1.jar package into the Android project. The specific implementation methods are as follows.
* * Function: Parse JSON data, revert to Person object list
* Param : jsonstring JSON data obtained from server
* Retuen:person Object list
* Author: Blog Park-Still indifferent
* * Public
static list<person> Getlistperson (String jsonstring) {
list< person> list = new arraylist<person> ();
Gson Gson = new Gson ();
List = Gson.fromjson (jsonstring, New typetoken<list<person>> () {}.gettype ());
return list;
}
As you can see, the code implementation that parses JSON data using Gson is also very simple. Among them, TypeToken is a data type converter provided by Gson, which supports a variety of data collection type conversion, and its reflection mechanism can map the parsed Java object to the corresponding data collection.
In this example, the same click the button button to send a request to the server to obtain the JSON data, after obtaining the JSON data from the server, using the above code to parse the JSON data, and then displaying the resolved person object in turn in the TextView control. The results of the program running are shown in Figure 2.
Figure 2 Running results
The above is a small compilation for you to share the Android learning Note 45 Gson parse the entire narrative of JSON, I hope you like.