Android JSON data parsing (Gson mode)

Source: Internet
Author: User
Tags tojson

To create and parse JSON data, you can also use Gson to do so. Gson is a Java class library provided by Google for mapping between Java objects and JSON data. With Gson, you can easily convert a string of JSON data into 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 available: the ToJson () and the Fromjson () methods. where the ToJson () method is used to convert the Java object to the appropriate JSON data, the Fromjson () method is used to implement the conversion of the JSON data to the appropriate Java object.

1.1 ToJson () method

The ToJson () method is used to convert a Java object to the appropriate JSON data, mainly in the following ways:

(1) String ToJson (jsonelement jsonelement);

(2) String ToJson (Object src);

(3) String ToJson (Object src, Type typeofsrc);

Wherein, method (1) is used to convert the Jsonelement object (can be jsonobject, Jsonarray, etc.) into JSON data; method (2) is used to serialize the specified object object into the corresponding JSON data Method (3) is used to serialize the specified object object (which can include a generic type) into the corresponding JSON data.

1.2 Fromjson () method

The Fromjson () method is used to convert JSON data to the appropriate 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 methods above are used to parse different forms of JSON data into Java objects.

2. Generating JSON data on the server side

To use Gson technology to generate JSON data on the server side, you first need to complete the following two preparations.

(1) created a Web project using MyEclipse, where I named the project "Gsondemoproject" to emulate the server-side Web service.

(2) Import the Gson API packet Gson-2.2.1.jar into the project.

We can then create a Jsontools tool class in the project and implement the static Method Createjsonstring (), in which the JSON data is generated by using the Gson technique. The specific implementation of this method is as follows.

 public  class   Jsontools { /*   * Function: Generate a JSON String * Param:value object objects that you want to convert to a JSON string * Retuen:json String * A Uthor: Blog Park-still indifferent  */ public  static   String createjsonstring (Object value) {Gson Gson  = new   Gson ();          String  string  = Gson.tojson (value);  return  string  ; }}  

As you can see, the 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 invoking the Tojson () method of the Gson object.

By using this method, we can easily pass in any Java object and convert it into JSON data. As in the previous blog post, we can implement a simple way to get a list of person objects in the Jsonservice class, as follows:

/** Function: Get list of person objects * Author: Blog Park-still indifferent*/     PublicList<person>Getlistperson () {List<Person> list =NewArraylist<person>(); Person Person1=NewPerson (001,"Jack", -); Person Person2=NewPerson (002,"Rose", -); Person Person3=NewPerson (003,"Bob", -);        List.add (Person1);        List.add (Person2);        List.add (Person3); returnlist; }

In this method, we add 3 person objects to the list, each with an ID (int), a name (String), and an age (int) of three properties.

Finally, we need to create a jsonaction class that inherits from HttpServlet and implements the Dopost () method in it to respond to client requests to the server. Specific as follows:

 Public voidDoPost (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("Text/html;charset=utf-8"); Request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding ("Utf-8"); 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 to the Jsontools.createjsonstring () method, The JSON data for the list of person objects is generated. Publishing the project to Tomcat, using a browser to access the Web project, you can see the interface shown in 1, and the list of person objects has been successfully converted into JSON data.

Figure 1 The resulting JSON data

3. Parsing JSON data on the client

In Android engineering, we can access the URL shown in Figure 1 through the HttpURLConnection interface to get JSON data on the server.

Once you have the JSON data, you can restore the JSON data shown in Figure 1 to the corresponding Person object list by using the previously mentioned Fromjson () method. Of course, because Gson is used here, you also need to import the Gson-2.2.1.jar package into the Android project. The specific implementation method is as follows.

 /*   
    
     */
     public  static  List<person > Getlistperson (String jsonstring) {list  <Person> list = new  arraylist<person> ();        Gson Gson  =  Gson (); List  = Gson.fromjson (jsonstring, new  typetoken<list<person>        > () {}.gettype ());     return   list; }

As you can see, code implementations that parse JSON data using Gson are also very simple. Among them, TypeToken is the data type converter provided by Gson, which supports a variety of data collection type conversions, and its reflection mechanism can be implemented to map the parsed Java objects to the corresponding data collection.

In this example, the same click button to send a request to the server to get the JSON data, after the server obtains the JSON data, using the above code to complete the parsing of the JSON data, and finally the resolved person object is displayed in the TextView control in turn. The program runs as shown in result 2.

Figure 2 Running results

Android JSON data parsing (Gson mode)

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.