Application of JSON data parsing tool Gson

Source: Internet
Author: User
Tags json tojson

In our actual development, data such as JSON and XML are the most common, and it is often necessary to write additional parsing tool classes to parse the data. Of course you can write yourself, but write your own shortcomings:

It's not as perfect as it was written by yourself.
The second is to write their own analytical tools very time-consuming, is a thankless thing
Since there are so many open source tools available on the Web, why do we have to build our own wheels?

Today, the blogger will introduce a JSON parsing tool Gson, I believe many small partners have heard it, I will briefly introduce its use.


one, introduce Gson to your project

If you're using Eclipse, you can go to Gson's github to download its jar file and import it into your project. The GitHub address of Gson is attached here: Https://github.com/google/gson

If you're using Android studio and using Gradle, it's easier to add the following statement to your Build.gradle file:


dependencies {

Compile ' com.google.code.gson:gson:2.4 '
}

So you can bring Gson into your project.

Second, the use of Gson

Converts a string array into a Json string:


Gson Gson = new Gson ();
String[] Date {"Sun", "Mon", "Tus", "Wes", "Thes", "Fri", "Sat"};
String Datejson = Gson.tojson (date);
System.out.println (Datejson);

Output results:

["Sun", "Mon", "Tus", "Wes", "Thes", "Fri", "Sat"]

Converts a list collection to a Json string:


Gson Gson = new Gson ();
list<students> Students = new arraylist<> ();
Students a = new Students ("Xiaoming", "Anhui", 18);
Students B = new Students ("Ahan", NULL, 19);
Students C = new Students ("Qianfeng", "Chaohu", 20);
Students d = new Students ("Heshang", "Changchun", 21);
Students.add (a);
Students.add (b);
Students.add (c);
Students.add (d);
String Stujson = Gson.tojson (students);
System.out.println (Stujson);

Where students class:
public class students{
Public Students (string name, string address, int age) {
THIS.name = name;
this.address = address;
This.age = age;
}
}

Output results:

[
{' name ': ' Xiaoming ', ' address ': ' Anhui ', ' age ': 18},
{' name ': ' Ahan ', ' age ': 19},
{' name ': ' Qianfeng ', ' address ': ' Chaohu ', ' Age ': 20},
{' name ': ' Heshang ', ' address ': ' Changchun ', ' Age ': 21}
]

Converts a map collection into a Json string

Gson Gson = new Gson ();
hashmap<string, string> colors = new hashmap<> ();
Colors.put ("Black", "#000000");
Colors.put ("BLUE", "#0234ff");
Colors.put ("RED", "#2addbf");
Colors.put ("Yellow", "#123456");
String Colorjson = Gson.tojson (colors);
System.out.println (Colorjson);

Output results:


{"RED": "#2addbf", "BLUE": "#0234ff", "Black": "#000000", "Yellow": "#123456"}

Converts a Json string into a Java object

String Sjson = "{' name ': ' Little Monk ', ' address ': ' Chaohu ', ' age ': 22}";
Students s = Gson.fromjson (Sjson, Students.class);
String name = S.getname ();
String addr = s.getaddress ();
int age = S.getage ();
SYSTEM.OUT.PRINTLN (name + "" + addr + "" + age);

Output results:

Little Monk Chaohu 22
Converts a Json string into a collection

Gson Gson = new Gson ();
Type type = new typetokenmap<string, string> map = Gson.fromjson (Colorjson, type);
For (String Key:map.keySet ()) {
SYSTEM.OUT.PRINTLN (key + ":" + map.get (key));
}

Output results:

RED: #2addbf
BLUE: #0234ff
Black: #000000
Yellow: #123456

A careful friend can find that this code introduces a type object to represent the types of the map collection, and note that the type class imported here is Java.lang.reflect.Type in the type Oh. Why do you use TypeToken? The reason is that because of the generic implementation mechanism of Java, the type of Java code that uses generics is erased, we cannot get the type of generics, and if it is passed directly into Xxx.class, Gson may not be able to parse the actual object correctly. So here's how it's written, and it's OK to pay attention to it later.

These are some of the basic uses of Gson. Gson can not only parse JSON data into the corresponding class object of JSON, but also parse the JSON data into class objects encapsulated in other classes. For example, there is a class as follows:

public class jsonresponse{
Private list<student> student_list;
Private list<teacher> teacher_list;

Public list<student> getstudentslist () {
return student_list;
}

Public list<teacher> getteacherslist () {
return teacher_list;
}
}

As you can see, there are two instance variables in the Jsonresponse class, which are collections of Student and Teacher. Imagine now if you want to request data from the server, the server returns you a string of JSON data, how do you parse them into student sets and teacher collections? Simply, you just need to design the Student class and Teacher classes in the form corresponding to the JSON data one by one, such as:

JSON data if this is the case:

{
  "student_list": [
    {
      "std_id": "1",
       "Std_name": "John",
      "std_age": "A",
       "std_addr": "Hefei",
      "Std_avatar": "./public/uploads/avatar/ 9132035730.jpg "
   },
    {
     " std_id ":" 2 ",
      "std_name": "Dick",
      "std_age": ","
 & nbsp;    "std_addr": "Shanghai",
      "Std_avatar": "/public/uploads/avatar /9132035730.jpg
   }
 
}
 
then your student class is designed like this:

public class student{
private int std_id;
Private String Std_name;
Private String std_age;
Private String std_addr;
Private String Std_avatar;
... The Get method is not written.
}

Note that the variable names in the class are strictly consistent with the keys in the JSON data, including the student_list in the Jsonresponse, as well as the one that begins with the JSON data, or the Teacher approach. The requested data is then converted directly into the Jsonresponse object, and Gson is automatically converted to list<student> or list<teacher> based on the contents of the JSON data. Just like this:

Gson Gson = new Gson ();
Sjson is the JSON data above.
Jsonresponse response = Gson.fromjson (Sjson, Jsonresponse.class);
list<student> students = Response.getstudentslist ();
for (Student student:students) {
System.out.println (Student.getstd_name ());
}

Output results:

Often the requested data may be preceded by additional data such as status codes, which can also be parsed in the Jsonresonse class. is not very convenient ~

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.