Gson版本支持

Gson提供了@Since注解來控制基於其各種版本的類的Json序列化/反序列化。 考慮以下具有版本支持的類。 在這個類中,我們最初定義了兩個變數rollNoname,稍後將其添加為一個新變數。 使用@Since定義了rollNo,名稱從版本1.0開始並經過驗證,版本為1.1

class Student {
   @Since(1.0)
   private int rollNo;

   @Since(1.0)
   private String name;

   @Since(1.1)
   private boolean verified;
}

GsonBuilder提供了setVersion()方法來序列化這樣的版本化類。

GsonBuilder builder = new GsonBuilder();
builder.setVersion(1.0);
Gson gson = builder.create();

讓我們來看一個實際版本支持的例子。 創建一個名為GsonTester的Java類檔:GsonTester.java -

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Since;

public class GsonTester {
   public static void main(String args[]) {
      GsonBuilder builder = new GsonBuilder();
      builder.setVersion(1.0);
      Gson gson = builder.create();

      Student student = new Student();
      student.setRollNo(1);
      student.setName("Maxsu");
      student.setVerified(true);

      String jsonString = gson.toJson(student);
      System.out.println(jsonString);

      gson = new Gson();
      jsonString = gson.toJson(student);
      System.out.println(jsonString);
   }
}
class Student {
   @Since(1.0)
   private int rollNo;

   @Since(1.0)
   private String name;

   @Since(1.1)
   private boolean verified;

   public int getRollNo() {
      return rollNo;
   }
   public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public void setVerified(boolean verified) {
      this.verified = verified;
   }
   public boolean isVerified() {
      return verified;
   }
}

執行上面示例代碼,得到以下結果 -

{"rollNo":1,"name":"Maxsu"}
{"rollNo":1,"name":"Maxsu","verified":true}

上一篇: Gson空對象支持 下一篇: Gson從序列化中排除字段