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


Gson 庫為其讀取和編寫的 Java 物件提供了一個簡單的版本控制系統,還提供了一個名為 @Since 的註解,用於版本控制概念 @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"
}

更新日期: 04-Jul-2020

閱讀 108 次

開啟你的職業 生涯

透過完成課程獲得認證

開始學習
廣告