Guide to the use of Gson (i)

Source: Internet
Author: User
Tags tojson
first, the basic usage of Gson

The Gson provides the Fromjson () and Tojson () two methods that are directly used for parsing and generating, the former implementing deserialization, and the latter implementing serialization. At the same time, each method provides an overloaded method, I usually have a total of 5.

parsing of basic data types

Gson Gson = new Gson ();
int i = Gson.fromjson ("M", Int.class);
Double D = gson.fromjson ("\" 99.99\ "", Double.class);  99.99
Boolean B = Gson.fromjson ("true", boolean.class);     True
String str = Gson.fromjson ("String", string.class);   String

Note: I don't know if you've noticed anything different in line 2nd and 3.

generation of basic data types

Gson Gson = new Gson ();
String jsonnumber = Gson.tojson (MB);
Jsonboolean = Gson.tojson (false);    False
String jsonstring = Gson.tojson ("string");//"string"

generation and analysis of Pojo class

public class User {
    //omitting other public
    String name;
    public int age;
    Public String emailaddress;
}

Generate JSON:

Gson Gson = new Gson ();
User user = New User ("Strange Theft Kidou",);
String Jsonobject = Gson.tojson (user); {"Name": "Strange Theft Kidou", "Age": 24}

Parse JSON:

Gson Gson = new Gson ();
String jsonstring = "{\ name\": \ "Strange Theft kidou\", "age\": ";
User user = Gson.fromjson (jsonstring, User.class);
use of attribute renaming @SerializedName annotations

From the above Pojo generation and parsing you can see that the fields and values of JSON are the names and types of one by one corresponding, but there are also some fault-tolerant mechanisms (like the first example of the 3rd line of the string 99.99 to double, you do not tell me is a string ah), but sometimes there will be some disharmony, Such as:
The desired JSON format

{"Name": "Strange Theft Kidou", "Age": "EmailAddress": "Ikidou@example.com"}

Actual

{"Name": "Strange Theft Kidou", "Age": "email_address": "Ikidou@example.com"}

This is a common scenario for using PHP as a background development language, PHP and JS in the name of the general use of the underline style, and the general use of Java in the Hump method, so that the background of the Buddies to change the front and backstage are not happy, but to use their own underline style when I will not adapt, how to do? Is it hard to find a way to Qimei?

We know that Gson need to use reflection when serializing and deserializing, when it comes to reflection, you have to think of annotations, and all kinds of libraries put annotations under the annotations package, Open the source code in the Com.google.gson bag really have a annotations, there is a serializedname annotation class, this should be what we are looking for.

The property corresponding to the Pojo in JSON for email_address this property becomes:

@SerializedName ("email_address") public
String EmailAddress;

In this way, it is very good to retain the front-end, backstage, android/java their respective naming habits.

Do you think it's over?

If the design is not rigorous or other places can reuse the class, the other fields are the same, the EmailAddress field is not the same, such as the following three kinds of situation that how? Write a new one?

{"Name": "Strange Theft Kidou", "Age": "EmailAddress": "Ikidou@example.com"}
{"Name": "Strange Theft Kidou", "Age": "email_address": "Ikidou@example.com"}
{"Name": "Strange Theft Kidou", "Age": ", Email": "Ikidou@example.com"}

Provide an alternative property name for the Pojo field
The Serializedname annotation provides two properties, one of which is used, and a property alternate that receives a string array.
Note: Alternate requires 2.4 version

@SerializedName (value = "EmailAddress", alternate = {"Email", "email_address"}) public
String EmailAddress;

The correct results can be obtained when either of the three attributes (email_address, email, emailaddress) are present.
Note: When a variety of situations occur at the same time, the last occurrence of the value will prevail.

Gson Gson = new Gson ();
String json = "{\ name\": \ "Strange Theft kidou\", "age\": 24,\ "emailaddress\": \ "ikidou_1@example.com\", \ "email\": \ "ikidou_2@ Example.com\ ", \" email_address\ ": \" Ikidou_3@example.com\ "}";
User user = Gson.fromjson (JSON, user.class);
System.out.println (user.emailaddress); Ikidou_3@example.com
Gson using generics in three -

See the number, Boolean, object, and string in json above, now say array.

Example: JSON string array

["Android", "Java", "PHP"]

When we want to parse this JSON through Gson, there are generally two ways: using arrays, using list. and list for additions and deletions are more convenient, so the actual use is still a list more.

The array is relatively simple

Gson Gson = new Gson ();
String jsonarray = "[\ android\", \ "Java\", \ "Php\"];
String[] strings = Gson.fromjson (Jsonarray, String[].class);

But it won't work for List to change the String[].class in the above code directly to List<string>.class. For Java, list<string> and list<user> are just one byte-code file, which is List.class, which is a problem to be aware of when Java generics are used. generic erasure .

In order to solve the above problem, Gson provides us with TypeToken to support generics, so when we want to use the above data to resolve to list<string>, we need to write this.

Gson Gson = new Gson ();
String jsonarray = "[\ android\", \ "Java\", \ "Php\"];
String[] strings = Gson.fromjson (Jsonarray, string[].class);
list<string> stringlist = Gson.fromjson (Jsonarray, New typetoken<list<string>> () {}.getType ());

Note: The TypeToken constructor is protected modified so that it is written as new typetoken<list<string>> () {}.gettype () instead of new typetoken< List<string>> (). GetType ()

The influence of generic parsing on interface Pojo design
The introduction of generics can reduce extraneous code, such as the data returned by my current company interface into two categories:

{"Code": "0", "message": "Success", "Data": {}}
{"Code": "0", "message": "Success", "Data": []}

The data that we really need is contained, and the code is used only once, and the message is almost unused. If the Gson does not support generics or does not know Gson support generics students will definitely define POJO.

public class Userresponse {public
    int code;
    public String message;
    public User data;

When other interfaces redefine a xxresponse to change the type of data to XX, it is obvious that code, and message is repeatedly defined multiple times, and through generics we can extract the code and the Word fields into a result class. So we just need to write the data field corresponding to the Pojo can be more focused on our business logic. Such as:

public class Result<t> {public
    int code;
    public String message;
    public T data;
}

It can be written as result<user> when the data field is User, result<list<user>> when it is a list, and others in the same vein.

PS: Too much trouble each time new typetoken<result<xxx> and new typetoken<result<list<xxx>>, want to further encapsulation? See my other blog: "Get rid of Gson generics package" conclusion

This article mainly through the code to the reader to explain the basic use of Gson, will later update more advanced usage, if you are not familiar with annotations and generics then you have to work harder.

If you have other content you would like to know (not limited to Gson) Please give me a comment, the level is limited, welcome to Pat Bricks.

April 6 Supplementary
There is said to understand the result of the paragraph how to simplify the method, the following gives a complete example of two, User and list<user>.

Before the generics are introduced:

public class Userresult {public
    int code;
    public String message;
    public User data;
========= public
class Userlistresult {public
    int code;
    public String message;
    public list<user> data;
}
=========
String json = "{. ...}";
Gson Gson = new Gson ();
Userresult Userresult = Gson.fromjson (json,userresult.class);
User user = Userresult.data;

Userlistresult Userlistresult = Gson.fromjson (json,userlistresult.class);
list<user> users = Userlistresult.data;

There are two classes of Userresult and Userlistresult, two fields are duplicated, one or two interfaces even if there are hundreds of what to do? So the introduction of generics.

No longer repeat definition of result class
type usertype = new typetoken<result<user>> () {}.gettype ();
result<user> Userresult = Gson.fromjson (json,usertype);
User user = Userresult.data;

Type Userlisttype = new typetoken<result<list<user>>> () {}.gettype ();
result<list<user>> Userlistresult = Gson.fromjson (json,userlisttype);
list<user> users = Userlistresult.data;

See the difference? After the introduction of generics, although a single sentence is used to get generic information, the return value type is straightforward and many unrelated classes are defined less.

Kidou (author of Jane's book)
Original link: http://www.jianshu.com/p/e740196225a4
Copyright belongs to the author, reproduced please contact the author to obtain authorization, and labeled "Jane book author."

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.