Android study notes 44: JSON data parsing

Source: Internet
Author: User
Tags array example json array example package json

JSON (JavaScript Object Notation) is a lightweight data exchange format. It uses a language-independent text format and provides an ideal data exchange format for Web application development.

This article describes how to create JSON data on the server and parse JSON data on the android client.

 

1. JSON Data Structure

JSON has two data structures: objects and arrays.

1.1 objects

In JSON, an object starts with "{" (left parenthesis) and ends with "}" (right Parenthesis. Each "name" is followed by a ":" (colon), followed by the value of this name. Multiple "names: Values" are separated by commas. The name must be enclosed in double quotation marks. If the value is a string, it must be enclosed in double quotation marks. If it is a numeric value, it is not required. Its structure 1 is shown in.

Figure 1 JSON object structure

The followingCodeIs a simple JSON object example:

 
1 {2"ID": 001,3"Name": "Jack",4"Age": 255}

Array 1.2

In JSON, an array is an ordered set of values. An array starts with "[" (left square brackets) and ends with "]" (right square brackets. Values are separated by commas. Its structure 2 is shown in.

Figure 2 JSON Array Structure

The following code is a simple JSON array example:

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

Type of 1.3 Value

In the JSON object and array structure, the value can not only be a simple data type such as a number or string, but also an object or an array, as shown in 3.

Figure 3 JSON Value Type

Therefore, we can use a combination of objects and arrays to form a complex data structure. The following code defines a "Students" Object using the object structure. The "Students" object contains a student array, and the value in the student array is a JSON object.

1 {2"Students":3 [4{"Name": "Jack", "Age": 23},5{"Name": "Rose", "Age": 24}6 ]7}

 

2. Generate JSON data on the server

Generally, when a client requests server data, the server can send the data to the client in XML, JSON, or HTML format.

So how to generate JSON data on the server? First, you need to complete the following preparations.

(1) We need to create a web project using myeclipse. Here I name this project as "jsondemoproject" to simulate the Web service on the server.

(2) We also need to import the json api package json-lib-2.2.2-jdk15.jar in this project.

The json api provides the jsonobject class. by calling the put (Object key, object Value) method of the jsonobject class, you can store an object as a key-value pair to a jsonobject object. By calling the tostring () method of the jsonobject class, the jsonobject object can be converted to JSON data.

The following code creates a jsontools class and implements the static method createjsonstring () to generate JSON data.

 1  Public   Class  Jsontools {  2  3  /*  4   * Function: Generate JSON data.  5   * Param: key value of the key JSON data  6   * Content of JSON data to be generated for an object  7   * Retuen: JSON data  8   * Author: blog Park-still indifferent  9  */  10  Public   Static  String createjsonstring (string key, object Value ){  11 Jsonobject = New Jsonobject (); //  Create a jsonobject  12 Jsonobject. Put (Key, value ); //  Add content to the jsonobject  13  Return Jsonobject. tostring ();//  Generate JSON data and return  14   }  15  16 }

By using this method, we can easily transfer various data and convert it into JSON data. For example, we can implement a simple method to obtain the list of person objects in the jsonservice class, as shown below:

 1       /*  2   * Function: gets the list of person objects.  3   * Author: blog Park-still indifferent  4       */  5       Public List <person> Getlistperson (){  6 List <person> List = New Arraylist <person> ();  7 Person person1 = New Person (001, "Jack", 25 );  8 Person person2 = New Person (002, "Rose", 24 ); 9 Person person3 = New Person (003, "Bob", 26 );  10   List. Add (person1 );  11   List. Add (person2 );  12   List. Add (person3 );  13           Return  List;  14 }

The person object has three attributes: ID (INT), name (string), and age (INT.

Finally, we can create a jsonaction class inherited from httpservlet and implement the dopost () method to respond to client requests to the server. The details are as follows:

 1  Public   Void  Dopost (httpservletrequest request, httpservletresponse response)  2               Throws  Servletexception, ioexception {  3   4 Response. setcontenttype ("text/html; charset = UTF-8" );  5 Request. setcharacterencoding ("UTF-8");  6 Response. setcharacterencoding ("UTF-8" );  7 Printwriter out = Response. getwriter ();  8           9 List <person> listperson = Jsonservice. getlistperson ();  10           11 String STR = Null  ;  12 String action_flag = request. getparameter ("action_flag "); //  Obtain URL parameters  13           If (Action_flag.equals ("persons" )){  14 STR = jsontools. createjsonstring ("persons" , Listperson );  15   }  16   Out. println (STR );  17   Out. Flush (); 18   Out. Close ();  19 }

We can see that in the dopost () method, the listperson Object List is obtained by calling the getlistperson () method, and it is passed into jsontools. createjsonstring () method to obtain a string of JSON data.

Publish the project to Tomcat and access the Web project using a browser. The page shown in Figure 4 is displayed. The person Object List is successfully converted into JSON data.

Figure 4 JSON data generated

 

3. parse JSON data on the client

Through the above steps, we have generated JSON data on the server. It is easy to obtain the JSON data in our android project. You only need to use the httpurlconnection interface provided by Android to access the URL shown in Figure 4.

After obtaining the JSON data on the server, how does one parse the JSON data in the android project?

Observe the JSON data shown in Figure 4 and you can see:

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

(2) jsonarray contains three more jsonobject objects.

(3) Each embedded jsonobject has a combination of three key-value pairs.

After analyzing the JSON data structure, you can start to parse it. In the android project, we can create a jsontools class and implement the getlistperson () Class Method to parse the JSON data obtained from the server and restore it to the person Object List. The Code is as follows:

 1       /*  2   * Function: parses JSON data and restores it to the person Object List.  3  * Param: key value of the key JSON data  4   * JSON data obtained by jsonstring from the server  5   * Retuen: List of person objects  6   * Author: blog Park-still indifferent  7        */  8       Public   Static List <person> Getlistperson (string key, string jsonstring ){  9 List <person> List = New Arraylist <person> ();  10           Try  {  11 Jsonobject = New Jsonobject (jsonstring ); //  Create a jsonobject  12 Jsonarray personarray = jsonobject. getjsonarray (key ); //  Obtains the value of a jsonobject, which is a JSON array. 13               For ( Int I = 0; I <personarray. Length (); I ++ ){  14 Jsonobject personobject = personarray. getjsonobject (I ); //  Obtains every jsonobject in the json array.  15 Person = New  Person ();  16                   Int Id = personobject. getint ("ID "); // Obtains the value corresponding to the key in each jsonobject.  17 String name = personobject. getstring ("name" );  18                   Int Age = personobject. getint ("Age" );  19 Person. setid (ID ); //  Saves parsed property values to the person object.  20   Person. setname (name );  21   Person. setage (AGE ); 22 List. Add (person ); //  Add the parsed person object to the list.  23   }  24 } Catch  (Jsonexception e ){  25   E. printstacktrace ();  26   }  27           Return  List; 28 }

In this example, click the button to send a request to the server for obtaining JSON data. After obtaining JSON data from the server, you can use the above Code to parse JSON data, finally, the parsed person object is displayed in the textview control in sequence.ProgramThe result 5 is displayed.


Figure 5 running result

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.