This article is based on the author’s daily use combined with Gson source notes and wiki for the original content, reproduced please indicate the source. This paper links: www.jianshu.com/p/e74019622…

JSON (official website) is a text-based data interchange format that is lighter than XML, easier to read and write than binary, and more modally convenient. Its importance is self-evident. There are many ways to parse and generate. The most common libraries in Java are jSON-Java, Gson, Jackson, FastJson, etc. This time I will introduce Gson.

Other articles in this series

  • Do you really know how to use Gson? Gson User Guide (1)
  • Do you really know how to use Gson? Gson User Guide (2)
  • Do you really know how to use Gson? Gson User Guide (3)
  • Do you really know how to use Gson? Gson User Guide (4)

Note: This series is based on Gson 2.4.

If you are confident with Gson, click close.

The main content of this article:

  • The basic usage of Gson
  • Property renaming@SerializedNameUse of annotations
  • Generics are used in Gson

The basic usage of Gson

Gson provides two direct parsing and generation methods fromJson() and toJson(), the former for deserialization and the latter for serialization. Each method also provides overloaded methods, of which I use a total of five.

Parsing of basic data types

Gson gson = new Gson(); int i = gson.fromJson("100", int.class); //100 double d = gson.fromjson ("\"99.99\", double-.class); Boolean b = gson.fromjson ("true", Boolean. Class); // true String str = gson.fromJson("String", String.class); // StringCopy the code

Note: Do you notice anything different in lines 2 and 3

Generation of basic data types

Gson gson = new Gson();
String jsonNumber = gson.toJson(100);       // 100
String jsonBoolean = gson.toJson(false);    // false
String jsonString = gson.toJson("String"); //"String"
Copy the code

Generation and parsing of POJO classes

Public class User {// omit other public String name; public int age; public String emailAddress; }Copy the code

Generate a JSON:

Gson gson = new Gson(); User User = new User(" kidou",24); String jsonObject = gson.toJson(user); // {"name":" kidou","age":24}Copy the code

Parsing JSON:

Gson gson = new Gson(); String jsonString = "{\" name \ ": \" criminal kidou \ "and \" age \ ": 24}"; User user = gson.fromJson(jsonString, User.class);Copy the code

Use of the @serializedName annotation

In the first example, line 3 of string 99.99 is converted to double, but there is also some error tolerance. In the first example, line 3 of string 99.99 is converted to double. Desired JSON format

Kidou {" name ":" criminal ", "age" : 24, "emailAddress" : "[email protected]"}Copy the code

The actual

Kidou {" name ":" criminal ", "age" : 24, "email_address" : "[email protected]"}Copy the code

This is very common for the use of PHP as a background development language, PHP and JS in the naming of the general use of underline style, and Java generally adopt the hump method, let the background brothers change it front-end and background are not happy, but to use their own underline style I will feel uncomfortable, how to do? Isn’t there a way to do both?

We know that Gson uses reflection for serialization and deserialization. When we talk about reflection, we have to think about annotations. In general, all kinds of libraries put annotations in the Annotations package, open the source code, and there is a annotations package in com.google. Gson. There’s a SerializedName annotation class in there, and that should be what we’re looking for.

Email_address = POJO = email_address = POJO = POJO

@SerializedName("email_address")
public String emailAddress;
Copy the code

This way, the front-end, backend, Android/ Java naming conventions are well preserved.

You think that’s the end of it?

If the connection design is not rigorous or the class can be reused elsewhere, all other fields are the same, except the emailAddress field. Let me rewrite it, okay?

Kidou {" name ":" criminal ", "age" : 24, "emailAddress" : "[email protected]"}Copy the code
Kidou {" name ":" criminal ", "age" : 24, "email_address" : "[email protected]"}Copy the code
Kidou {" name ":" criminal ", "age" : 24, "email" : "[email protected]"}Copy the code

Provide alternative property names for POJO fields The SerializedName annotation provides two properties, one of which is used above, and an alternate property, which takes an array of strings. Note: Version 2.4 is required for Alternate

@SerializedName(value = "emailAddress", alternate = {"email", "email_address"})
public String emailAddress;
Copy the code

The correct result is obtained if any of the above three attributes (email_address, email, or emailAddress) are present. Note: When multiple situations occur at the same time, the value of the last occurrence shall prevail.

Gson gson = new Gson(); String json = "{\" name \ ": \" criminal kidou \ "and \" age \ ": 24, \" emailAddress \ ": \" [email protected] \ ", \ "email \" : \ "[email protected] \", \ "email_a ddress\":\"[email protected]\"}"; User user = gson.fromJson(json, User.class); System.out.println(user.emailAddress); // [email protected]Copy the code

Use of generics in Gson

JSON: Number, Boolean, Object, and String. Let’s talk about Array.

Example: JSON string array

["Android","Java","PHP"]
Copy the code

When parsing json through Gson, there are generally two ways: using an array or using a List. List is more convenient for adding and deleting, so the actual use of List is still more.

Arrays are easy

Gson gson = new Gson();
String jsonArray = "[\"Android\",\"Java\",\"PHP\"]";
String[] strings = gson.fromJson(jsonArray, String[].class);
Copy the code

But for List, changing String[]. Class to List

.class doesn’t work. For Java, there’s only one bytecode file for List

and List

and that’s list.class, and that’s one of the things to be aware of when you’re using Java generics generic erasers.


To solve the above problem, Gson provides TypeToken support for generics, so we need to write this when we want to use the above data to parse into List

.

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());
Copy the code

Note: The constructor of TypeToken is protected, which is why it is written as new TypeToken >() {}.getType() instead of new TypeToken >().getType()

The introduction of generics can reduce extraneous code, such as the data returned by my current company’s interface is divided into two categories:

{"code":"0","message":"success","data":{}}
Copy the code
{"code":"0","message":"success","data":[]}
Copy the code

The data we really need is the data that code uses only once and Message hardly ever uses. If Gson does not support generics, or those of you who do not know Gson supports generics, you will define poJOs this way.

public class UserResponse {
    public int code;
    public String message;
    public User data;
}
Copy the code

When the other interface redefines an XXResponse and changes the type of data to XX, it is clear that code and message have been repeatedly defined many times. With generics we can extract the code and message fields into a Result class, In this way, we only need to write the POJOs corresponding to the data field and focus more on our business logic. Such as:

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

If the data field is User, it can be Result

, if it is a List, Result >, and so on.

New TypeToken

and new TypeToken

> Check out my other blog post: ** Fixing Gson Generic Encapsulation **

conclusion

This article introduces you to the basic usage of Gson through code, and more advanced usage will be updated in the future. If you are not familiar with annotations and generics, you should work hard.

If you have other content you would like to know (not limited to Gson) please leave a comment to me, the level is limited, welcome to clap brick.


On April 6, I added that I could not understand how to simplify the Result paragraph. Here are two complete examples: User and List

.

Before the introduction of generics:

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;Copy the code

There are two classes: UserResult and UserListResult. There are two classes: UserResult and UserListResult. Don’t work to death? So generics.

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;Copy the code

See the difference? With the introduction of generics, it takes one more sentence to get information about generics, but the return value types are straightforward and many less extraneous classes are defined.