如何配置Gson以在Java中启用版本控制支持?

GSON 库提供了一个简单的 版本控制系统的Java对象,它读取和写入操作,并提供了一个名为注释@Since的版本概念 @Since(VERSIONNUMBER)

我们可以使用GsonBuilder()。setVersion() 方法创建具有版本控制的Gson实例。如果我们像setVersion(2.0)一样提到,则 意味着所有具有2.0或更小的字段都可以解析。

语法

public GsonBuilder setVersion(double ignoreVersionsAfter)

示例

import com.google.gson.*;
import com.google.gson.annotations.*;
public class VersionSupportTest {
   public static void main(String[] args) {
      Person person = new Person();
      person.firstName = "Raja";
      person.lastName = "Ramesh";
      Gson gson1 = new GsonBuilder().setVersion(1.0).setPrettyPrinting().create();
      System.out.println("版本1.0:");
      System.out.println(gson1.toJson(person));
      Gson gson2 = new GsonBuilder().setVersion(2.0).setPrettyPrinting().create();
      System.out.println("版本2.0:");
      System.out.println(gson2.toJson(person));
   }
}
//人类
class Person {
   @Since(1.0)
   public String firstName;
   @Since(2.0)   public String lastName;
}

输出结果

版本1.0:
{
 "firstName": "Raja"
}
版本2.0:
{
 "firstName": "Raja",
 "lastName": "Ramesh"
}