Gson (GitHub: https://github.com/google/gson) is a Java class library provided by Google for mapping between Java objects and JSON data. You can convert a JSON string into a Java object, or vice versa.
The most important objects in Gson are 2 Gsons and GsonBuilders.
Gson has 2 most basic methods (1) toJson() to convert java objects to JSON
(2) fromJson() converts JSON to java object
Write entity classes:
public class People { String name; int age; boolean setName; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean getSetName() { return setName; } public void setSetName(boolean setName) { this.setName = setName; } @Override public String toString() { return "name=" + name + " age=" + age + " setName=" +setName; }}Write test class GsonTest
import com.google.gson.ExclusionStrategy;import com.google.gson.FieldAttributes;import com.google.gson.Gson;import com.google.gson.GsonBuilder;/** * Convert java object to json. */public class GsonTest { public static void main(String[] args) { People p = new People(); p.setAge(20); p.setName("People"); p.setSetName(true); Gson gson = new Gson(); System.out.println(gson.toJson(p)); }}Output result:
{"name":"People","age":20,"setName":true}This is just the easiest way to use Gson. How to implement it if we need to convert the attribute setName of bool type not to convert when converting it to json?
After searching in Gson's package for a long time, I found that there is an interface under the com.google.gson package: ExclusionStrategy. Although I don't know what it does, based on the name, it can be inferred that this interface is used to set the exclusion strategy for Gson conversion. So I checked this interface on the official website http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html and found that as long as this interface is implemented and the object of the implementing class is stuffed to Gson, when converting it to json, Gson will filter out the specified class or attributes. So the following code is:
import com.google.gson.ExclusionStrategy;import com.google.gson.FieldAttributes;import com.google.gson.Gson;import com.google.gson.GsonBuilder;/** * Convert java object to json, skip specific files. */public class GsonTest { public static void main(String[] args) { People p = new People(); p.setAge(20); p.setName("People"); p.setSetName(true); ExclusionStrategy excludeStrategy = new SetterExclusionStrategy(); Gson gson1 = new GsonBuilder() .setExclusionStrategies(excludeStrategy) .create(); Gson gson2 = new Gson(); String json1 = gson1.toJson(p); String json2 = gson2.toJson(p); System.out.println(json1); System.out.println(json2); People p1 = gson1.fromJson(json1, People.class); People p2 = gson2.fromJson(json2, People.class); System.out.println(p1); System.out.println(p2); } private static class SetterExclusionStrategy implements ExclusionStrategy { public boolean shouldSkipClass(Class<?> clazz) { return false; } public boolean shouldSkipField(FieldAttributes f) { return f.getName().startsWith("set"); } }}It turns out that there are two ways to create Gson objects: new Gson() means to create a Gson object using the default configuration, and if created using the GsonBuilder.create() method, you can customize some settings, mainly to make the created Gson more suitable for certain specific situations. The first blue code in the above example creates a Gson object, which has the configuration of filtering properties starting with the word "set" (if you need to filter out a certain type, you can rewrite the shouldSkipClass(Class<?> clazz) method of the ExclusionStrategy interface. If you need to filter out multiple situations, you can create several ExclusionStrategy implementation class objects and set them in when creating the Gson object). Therefore, in this example, when converting the People object to Json, the attribute setName will be filtered out. Since there is no attribute setName in json1, when deserializing json1 into People object, the setName of boolean type has no value, so when printing, the default value of boolean type is taken. So the following results were obtained:
{"name":"People","age":20}{"name":"People","age":20,"setName":true}name=People age=20 setName=falsename=People age=20 setName=trueGson also supports the use of annotations. In the com.google.gson.annotation package, there are several annotations Expose, SerializedName, Since and Until. They each have their own functions. The following is an official example to introduce commonly used annotations:
Expose:
This annotation acts on the attribute, indicating that when serializing and deserializing, this attribute will be exposed to the Gson object. This annotation is only valid when the Gson object is created using the GsonBuilder method and the GsonBuilder.excludeFieldsWithoutExposeAnnotation() method is called, otherwise it is invalid. Here is an example introducing how to use @Expose annotation:
public class User { @Expose private String firstName; @Expose(serialize = false) private String lastName; @Expose (serialize = false, deserialize = false) private String emailAddress; private String password;}If you create a Gson object in the new Gson() method, the toJson() method and fromJson() method will operate these 4 properties when serializing and deserializing. However, if you use Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create() to create Gson objects, Gson's toJson() and fromJson() methods will exclude password fields, because password fields are not marked by annotation @Expose. This Gson object will also exclude the lastName and emailAddress fields, because the attribute serialize annotated @Expose is set to false. Similarly, Gson will exclude the emailAddress field during deserialization because deserialize is set to false.
SerializedName:
This annotation is used on the attribute, indicating that when this attribute is serialized into Json, the name needs to be serialized into the value specified by the annotation value attribute.
This annotation will override any FieldNamingPolicy, including the default naming policy. Here is an example introducing how @SerializedName annotation is used:
public class SomeClassWithFields { @SerializedName("name") private final String someField; private final String someOtherField; public SomeClassWithFields(String a, String b) { this.someField = a; this.someOtherField = b; }}The following code shows the results of serializing the above test class:
SomeClassWithFields objectToSerialize = new SomeClassWithFields("a", "b");Gson gson = new Gson();String jsonRepresentation = gson.toJson(objectToSerialize);System.out.println(jsonRepresentation);The execution result is:
{"name":"a","someOtherField":"b"}It can be seen that the property "someField" has been serialized to "name".
Note: The attribute name specified in the value of @SerializedName must be a valid Json attribute name.