Android study note 45: JSON data parsing (GSON Mode)

Source: Internet
Author: User
Tags tojson

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.

In the previous blog titled Android study note 44: JSON data parsing, we used basic JSON APIs to create JSON data on the server side and parse JSON data on the Android client.

You can also use GSON to create and parse JSON data. GSON is a Java class library provided by Google for ing between Java objects and JSON data. Using GSON, you can easily convert a string of JSON data into a Java object, or convert a Java object to the corresponding JSON data.

 

1. Two important GSON Methods

GSON APIs provide two important methods: toJson () and fromJson. Here, the toJson () method is used to convert Java objects into corresponding JSON data, and the fromJson () method is used to convert JSON data into corresponding Java objects.

1.1 toJson () method

The toJson () method is used to convert a Java object to a corresponding JSON data, mainly in the following forms:

(1) String toJson (JsonElement jsonElement );

(2) String toJson (Object src );

(3) String toJson (Object src, Type typeOfSrc );

Method (1) is used to convert a JsonElement Object (such as JsonObject and JsonArray) to JSON data. Method (2) is used to serialize a specified Object to JSON data; method (3) is used to serialize the specified Object (including the generic type) to the corresponding JSON data.

1.2 fromJson () method

The fromJson () method is used to convert JSON data into corresponding Java objects in the following forms:

(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 preceding method is used to parse JSON data of different forms into Java objects.

 

2. Generate JSON data on the server

To use GSON technology to generate JSON data on the server, you must first complete the following two preparations.

(1) create a Web Project using MyEclipse. Here I name this Project as "GsonDemoProject" to simulate the Web service on the server.

(2) import the gson api packet gson-2.2.1.jar to the project.

Then, we can create a JsonTools tool class in this project and implement the static method createJsonString (). In this method, GSON technology is used to generate JSON data. The specific implementation of this method is as follows.

1 public class JsonTools {2 3/* 4 * Function: generate the JSON string 5 * Param: value Object 6 * Retuen: JSON string 7 * Author: blog garden-still indifferent 8 */9 public static String createJsonString (Object value) {10 Gson gson Gson = new gson (); 11 String string = Gson. toJson (value); 12 return string; 13} 14 15}

We can see that the specific implementation of this method is very simple. First, create a Gson object, and then call the toJson () method of the Gson object to transfer the passed value (any Java object) convert to a JSON string.

By using this method, we can easily pass in any Java object and convert it into JSON data. Like in the previous blog, we can implement a simple method to get the list of Person objects in the JsonService class, as shown below:

1/* 2 * Function: Get the Person Object List 3 * Author: blog garden-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}

In this method, three Person objects are added to the List. Each Person object has three attributes: id (int), name (String), and age (int.

Finally, we need to 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");13         if(action_flag.equals("persons") {14             str = JsonTools.createJsonString(listPerson);15         }16         out.println(str);17         out.flush();18         out.close();19     }

In this method, we obtain the listPerson Object List by calling the getListPerson () method in the JsonService class and pass it to JsonTools. the createJsonString () method generates the JSON data of the Person Object List. Publish the project to Tomcat and access the Web project using a browser. The page shown in 1 is displayed. The Person Object List is successfully converted into JSON data.

Figure 1 JSON data generated

 

3. parse JSON data on the client

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

After obtaining the JSON data, you can use the fromJson () method mentioned above to restore the JSON data shown in figure 1 to the corresponding Person Object List. Of course, because GSON is used here, you also need to import the gson-2.2.1.jar package to the Android project. The specific implementation method is as follows.

1/* 2 * Function: parses JSON data and restores it to the Person Object List. 3 * Param: jsonString Json data obtained from the server. 4 * Retuen: Person Object List. 5 * Author: blog garden-still quiet 6 */7 public static List <Person> getListPerson (String jsonString) {8 List <Person> list = new ArrayList <Person> (); 9 Gson gson = new Gson (); 10 list = gson. fromJson (jsonString, new TypeToken <List <Person> (){}. getType (); 11 return list; 12}

As you can see, the code for parsing JSON data using GSON is also very simple. TypeToken is a data type converter provided by GSON. It supports conversion of multiple data sets. Its reflection mechanism can map parsed Java objects to corresponding datasets.

In this example, you also 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 preceding code to parse JSON data, finally, the parsed Person object is displayed in the TextView control in sequence. The result 2 is displayed.

Figure 2 running result

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.