Gson - Versioning Support



Gson provides @Since annotation to control the Json serialization/deserialization of a class based on its various versions. Consider the following class with versioning support. In this class, we've initially defined two variables rollNo and name and later on, we added verified as a new variable. Using @Since, we've defined rollNo and name as of version 1.0 and verified to be of version 1.1.

class Student { 
   @Since(1.0) 
   private int rollNo; 
   
   @Since(1.0) 
   private String name; 
   
   @Since(1.1) 
   private boolean verified;  
}

GsonBuilder provides the setVersion() method to serialize such versioned class.

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

Example

Let's see an example of versioning support in action. Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

File - 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; 
   } 
} 

Verify the result

Compile the classes using javac compiler as follows −

C:\GSON_WORKSPACE>javac GsonTester.java

Now run the GsonTester to see the result −

C:\GSON_WORKSPACE>java GsonTester

Verify the output.

{"rollNo":1,"name":"Mahesh Kumar"} 
{"rollNo":1,"name":"Mahesh Kumar","verified":true} 
Advertisements