Android Handy Note 44 JSON data parsing _android

Source: Internet
Author: User
Tags data structures object object

JSON (JavaScript Object notation) 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.

This article will focus on how to create JSON data on the server side and how to parse the JSON data on the Android client in the Android development.

1.JSON Data structure

There are two types of data structures in JSON: objects and arrays.

1.1 Objects

In JSON, an object begins with "{" (opening parenthesis), and "}" (closing parenthesis) ends. Each name is followed by a ":" (a colon), followed by a value of that name, separated by multiple "names: Values" (commas). Names need to be enclosed in double quotes, and values must be enclosed in double quotes if they are strings, and are not required if they are numeric. The schematic diagram of the structure is shown in Figure 1.


Figure 1 schematic diagram of the JSON object structure

The following code is an example of a simple JSON object:

 {
 "id":,
 "name": "Jack",
 "Age":
 }

1.2 Array

In JSON, an array is an ordered collection of values (value). An array begins with "[" (left bracket), and "]" (right bracket) ends. Values are separated from each other by using the "," (comma). The schematic diagram of the structure is shown in Figure 2.

Figure 2 schematic diagram of the JSON array structure

The following code is a simple example of a JSON array:

["Beijing", "Shanghai", "Guangzhou"]

1.3 Types of values

In JSON's object and array structure, value values can be not only simple data types such as numbers, strings, but also objects, arrays, and so on, as shown in Figure 3.


Figure 3 Type of value in JSON

Therefore, we can use the combination of object and array to form a complex data structure. The following code uses the object structure to define a "Students" object that contains a student array in the "Students" object, and the value in the student array is the JSON object.

   {'
     students ':
     [
     {' name ': ' Jack ', ' Age ':},
     {' name ': ' Rose ', ' Age ':}
     ]
   

2. Generate JSON data on the server side

Typically, when a client requests server data, the server can send the data to the client in the form of an XML document, JSON data, or HTML.

So how do you generate JSON data on the server side? First, you need to complete the following two preparatory work.

(1) We need to create a Web project using MyEclipse, where I name the project "Jsondemoproject" to simulate server-side Web services.

(2) We also need to import JSON API packet Json-lib-2.2.2-jdk15.jar in this project.

In the JSON API, the Jsonobject class is provided, and by invoking the put (object key, Object value) method of the Jsonobject class, an object object can be deposited as a key-value pair into the jsonobject. By calling the ToString () method of the Jsonobject class, you can convert the Jsonobject object to JSON data.

The following code creates a Jsontools class and implements the static method Createjsonstring (), which is used to generate the JSON data.

public class Jsontools {   /* * Function:   The key value of generating JSON data * Param:key    JSON data
 
   
    *       Object   to generate the content of the JSON data   * Retuen:  JSON data   * Author:  Blog Park-still indifferent   *  /public static string createjsonstring (String key, Object value) {    jsonobject jsonobject = new JS Onobject ();  Create a Jsonobject object    jsonobject.put (key, value);         Fill in the contents of the Jsonobject object return    jsonobject.tostring ();        Generate JSON data and return  }                         
 
   

By using this method, we can easily pass in all kinds of data and transform it into JSON data. For example, 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 ( ) {
     list<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;
   

Where the person object has three properties, id (int), name (String), and age (int).

Finally, we can create a jsonaction class that inherits from HttpServlet and implement the Dopost () method in response 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");  Gets the URL parameter
     if (action_flag.equals ("persons")) {
       str = jsontools.createjsonstring ("Persons", Listperson);
     }
     out.println (str);
     Out.flush ();
     Out.close ();
   }

As you can see, in the Dopost () method, we get the Person object list Listperson by calling the Getlistperson () method, and pass it into the Jsontools.createjsonstring () method. Thus a string of JSON data is obtained.

By publishing the project to Tomcat and using a browser to access the Web project, you can see the interface shown in Figure 4, where the Person object list has been successfully converted to JSON data.

Figure 4 The JSON data generated

3. Parsing JSON data on the client

With the above steps, we have generated JSON data on the server. It's easy to get this JSON data in our Android project, just use Android to access the URL shown in Figure 4 for the HttpURLConnection interface we provide.

So, after you get the JSON data on the server, how do you parse the JSON data in the Android project?

Look at the JSON data shown in Figure 4 to see that:

(1) The outermost layer of the JSON data is the Jsonobject,jsonobject key is "persons" and the value is a jsonarray.

(2) also contains 3 Jsonobject objects in the Jsonarray.

(3) in each of the embedded Jsonobject objects, there is a combination of 3 key-value pairs.

After analyzing the form of JSON data, you can begin to parse it. In Android, we can create a Jsontools class and implement the Getlistperson () class method to resolve the JSON data obtained from the server and revert to the list of person objects. Specific

The code looks like this:

  * * Function: Parse JSON data, revert to Person object list * Param:key JSON Data Key value * jsonstring JSON data obtained from server * Retuen:person Object list * Author: Blog Park-Still indifferent * * public static list<person> Getlistperson (String key
     , String jsonstring) {list<person> List = new arraylist<person> ();     try {jsonobject jsonobject = new Jsonobject (jsonstring);    Create Jsonobject object Jsonarray Personarray = Jsonobject.getjsonarray (key);  Gets the value of the Jsonobject object, which is a JSON array for (int i =; I < personarray.length (); i++) {Jsonobject Personobject = Personarray.getjsonobject (i);
         Gets each of the Jsonobject objects in the JSON array person = new man ();           int id = personobject.getint ("id");
         Gets the value of the key in each Jsonobject object String name = personobject.getstring ("name");
         int age = Personobject.getint (' age ');    Person.setid (ID);
         The parsed attribute value is stored in the Person object Person.setname (name); Person.setage (age);
         List.add (person);
     Adds each resolved person object to the list} catch (Jsonexception e) {e.printstacktrace ();
   } return list;  }

In this example, click the button button to send a request to the server to obtain the JSON data, and after obtaining the JSON data from the server, you can use the above code to parse the JSON data and then display the resolved person object in turn in the TextView control. The results of the program running are shown in Figure 5.

Figure 5 Running results

The above content is small to share the Android handy Note 44 of the JSON data analysis of all the narrative, I hope you like.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.