Gson版本支持

Gson提供了[@Since](https://github.com/Since "@Since")註解來控制基於其各種版本的類的Json序列化/反序列化。 考慮以下具有版本支持的類。 在這個類中,我們最初定義了兩個變量rollNoname,稍後將其添加爲一個新變量。 使用[@Since](https://github.com/Since "@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}