Summary of simple posture of gson


Summary of simple posture of gson

There are many frameworks for JSON serialization, such as Jackson, the default of spring, and fastjson, which are widely used in the domestic Internet. This paper mainly introduces the simple usage posture of gson, and does not involve the performance comparison of different JSON frameworks

The main content of this paper comes from the official course

<!– more –>

1. Dependency import

First of all, we use Maven to introduce dependency packages and select a version according to our own actual situation (simple usage posture does not have much correlation with specific version)


2. Basic serialization and deserialization

Generally speaking, we use the gson object to realize the serialization and deserialization of JSON. Here are some simple cases of serialization and deserialization

// Serialization
Gson gson = new Gson();
gson.toJson(1);            // ==> 1
gson.toJson("abcd");       // ==> "abcd"
gson.toJson(new Long(10)); // ==> 10
int[] values = { 1 };
gson.toJson(values);       // ==> [1]

// Deserialization
int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String[] anotherStr = gson.fromJson("[\"abc\"]", String[].class);

In the above case, it is mainly through the help ofgson.toJsonTo output the JSON string with the help ofgson.fromJsonDeserialize to get the object

3. Object serialization

Object serialization and deserialization can be said to be the most common, in the use of gson, the recommended object writing method

  • Filed: private modification
  • Members that do not want to be serialized, addtransientModifier
  • Default construction method without parameters (optional, recommended here, reserved, different from fastjson, must exist)
public static class BaseBean {
    private int age;

    private String name;

    private transient int code;

    private String email;

    public BaseBean() {

    public String toString() {
        return "BaseBean{" + "age=" + age + ", name='" + name + '\'' + ", code=" + code + ", email='" + email +
                '\'' + '}';
public void testObjGson() {
    BaseBean bean = new BaseBean();
    bean.age = 10;
    bean.code = 20;  ="A gray blog";

    Gson gson = new Gson();
    String str = gson.toJson(bean);
    System.out.println("json str: " + str);

    BaseBean out = gson.fromJson(str, BaseBean.class);
    System.out.println("after deserialization: " + out);

There is no essential difference between the above posture and the previous one. Let’s take a look at the output

JSON STR: {"age": 10, "name": "a gray blog"}
After deserialization: basebean {age = 10, name ='gray blog ', code = 0, email ='null'}

Please note that:

  • When the JSON string is output, null andtransientDecorated members are not output to the JSON string
  • Objects without get / set methods can still be deserialized (objects do not inherit from the serialize interface. Of course, my personal opinion is to inherit the serialize interface)

If I want to output null members to the JSON string, I can do the following

//Instead of creating a gson object directly, use gsonbuilder instead
Gson gsonWithNUll = new GsonBuilder().serializeNulls().create();
System.out.println("serialize with null: " + gsonWithNUll.toJson(bean));

The output results are as follows

Serialize with null: {"age": 10, "name": "a gray blog", "email": null}

Note: if you want to extend the serialization method, it is a good choice to build the gson object through gsonbuilder

4. Jsonobject and jsonarray

In some scenarios, we may not define a deserialized data object, such as the direct deserialization in fastjson asJSONObject/JSONArrayAnd then manually obtain data for business processing. How can gson support this scenario?

Map map = new HashMap();
map.put("a", "hello world");
map.put(12, true);
map.put("array", Arrays.asList("a", "c", "f", 12));
map.put("obj", Maps.newHashMap("k", "v"));

Gson gson = new Gson();
String str = gson.toJson(map);

//Direct use of jsonparser ා parsestring to achieve deserialization
JsonObject obj = JsonParser.parseString(str).getAsJsonObject();
String a = obj.get("a").getAsString();
boolean b = obj.get("12").getAsBoolean();
JsonArray ary = obj.get("array").getAsJsonArray();
JsonObject o = obj.get("obj").getAsJsonObject();

System.out.println("a:" + a + " b:" + b + " ary:" + ary + " o:" + o);

Please note that we are mainly relying onJsonParser.parseStringMethod. The input parameter can be a string or a stream, and the returned value isJsonElementObject, which is more interesting, provides some basic type output methods, such as

  • Getasstring: return string
  • Getasint: return int
  • Getasjsonarray: return jsonarray (JSON array)
  • Getasjsonobject: return jsonobject (JSON object)

Summary of simple posture of gson

5. Generic serialization

The above belongs to the general basic usage posture. In actual work, it can be said that the serialization and deserialization of generics are very common, so what should be done

public static class ResWrapper<T> {
    private T data;
    private int code;
    private String msg;

public static class User {
    private int age;
    private String name;

public void testGenri() {
    ResWrapper<User> wrapper = new ResWrapper<>();
    wrapper.code = 0;
    wrapper.msg = "name";

    User user = new User();
    user.age = 18;  ="A piece of ash"; = user;

    Gson gson = new Gson();
    String str = gson.toJson(wrapper);

    Type type = new TypeToken<ResWrapper<User>>() {}.getType();
    ResWrapper<User> out = gson.fromJson(str, type);

Summary of simple posture of gson

The core of the above is the generation of typenew TypeToken<ResWrapper<User>>() {}.getType();

6. Advanced

The above content can basically cover 90% of the daily business development scenarios. Of course, gson also supports some more advanced functions

Such as file name mapping

  • @SerializedName("custom_naming")
private class SomeObject {
  private final String someField;
  private final String someOtherField;

  public SomeObject(String a, String b) {
    this.someField = a;
    this.someOtherField = b;

Such as version support

  • @Since(1.1)
public class VersionedClass {
  @Since(1.1) private final String newerField;
  @Since(1.0) private final String newField;
  private final String field;

  public VersionedClass() {
    this.newerField = "newer";
    this.newField = "new";
    this.field = "old";

VersionedClass versionedObject = new VersionedClass();
Gson gson = new GsonBuilder().setVersion(1.0).create();
String jsonOutput = gson.toJson(versionedObject);
System.out.println (); // output: {"Newfield": "new", "field": "old"}

gson = new Gson();
jsonOutput = gson.toJson(versionedObject);
System.out.println (jsonoutput); // output: {"newerfield": "newer", "Newfield": "new", "field": "old"}

Custom type conversion

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(MyType.class, new DateTimeSerializer());
gson.registerTypeAdapter(MyType.class, new DateTimeDeserializer());

private class DateTimeSerializer implements JsonSerializer<DateTime> {
  public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) {
    return new JsonPrimitive(src.toString());

private class DateTimeDeserializer implements JsonDeserializer<DateTime> {
  public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {
    return new DateTime(json.getAsJsonPrimitive().getAsString());

Visual JSON output

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);

2. Others

Blog 1…

A gray personal blog, records all the blog articles in study and work. Welcome to visit

2. Statement

It’s not as good as a letter. The above contents are all from one family. Due to limited personal ability, there are inevitably omissions and mistakes. If you find a bug or have better suggestions, you are welcome to criticize and correct, and thank you

  • Microblog address: xiaohuihui blog
  • QQ: yihuihui / 3302797840

3. Scan attention

A gray blog

Summary of simple posture of gson