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

javajsonobject oriented programmingprogramming

Gson  库为其读取和写入的 Java 对象提供了一个简单的 版本控制系统,还为版本控制概念 @Since(versionnumber)提供了一个名为 @Since 的注释。

我们可以使用 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("Version 1.0:");
      System.out.println(gson1.toJson(person));
      Gson gson2 = new GsonBuilder().setVersion(2.0).setPrettyPrinting().create();
      System.out.println("Version 2.0:");
      System.out.println(gson2.toJson(person));
   }
}
// Person class
class Person {
   @Since(1.0)
   public String firstName;
   @Since(2.0)   public String lastName;
}

输出

Version 1.0:
{
 "firstName": "Raja"
}
Version 2.0:
{
 "firstName": "Raja",
 "lastName": "Ramesh"
}

相关文章