Gson——版本支援



Gson 提供 **@Since** 註解以基於其不同版本控制類的 JSON 序列化/反序列化。考慮以下具有版本支援的類。在這個類中,我們最初定義了兩個變數 **rollNo** 和 **name**,之後,我們添加了 **verified** 作為新變數。使用 @Since,我們定義了 **rollNo** 和 **name** 的版本為 1.0,verified 的版本為 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();

示例

讓我們看一個版本支援的實際示例。在 C:\>GSON_WORKSPACE 中建立一個名為 **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("Mahesh Kumar"); 
      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; 
   } 
} 

驗證結果

如下所示,使用 **javac** 編譯器編譯類:-

C:\GSON_WORKSPACE>javac GsonTester.java

現在,執行 GsonTester 以檢視結果:-

C:\GSON_WORKSPACE>java GsonTester

驗證輸出。

{"rollNo":1,"name":"Mahesh Kumar"} 
{"rollNo":1,"name":"Mahesh Kumar","verified":true} 
廣告
© . All rights reserved.