How can we use @Since annotation using Gson in Java?

JavaJSONObject Oriented ProgrammingProgramming

The @Since annotation can use with the setVersion() method of the GsonBuilder class. This annotation can apply to a field in java class and accepts float as an argument. This argument represents the version number in which the field has serialized. The same can apply to the deserialization process.

Syntax

@Documented
@Retention(value=RUNTIME)
@Target(value={FIELD,TYPE})
public @interface Since

Example

import com.google.gson.annotations.Since;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonSinceAnnotationTest {
   public static void main(String[] args) {
      Employee emp = new Employee();
      emp.setEmployeeName("Raja Ramesh");
      emp.setEmployeeId(125);
      emp.setEmployeeTechnology("Java");
      emp.setEmploeeAddress("Hyderabad");
      System.out.println("Since version 0.5");
      GsonBuilder gsonBuilder = new GsonBuilder();
      Gson gson = gsonBuilder.setPrettyPrinting().setVersion(0.5).create();
      String jsonString = gson.toJson(emp);
      System.out.println(jsonString);
      System.out.println("Since version 1.0");
      gsonBuilder = new GsonBuilder();
      gson = gsonBuilder.setPrettyPrinting().setVersion(1.0).create();
      jsonString = gson.toJson(emp);
      System.out.println(jsonString);
      System.out.println("Since version 1.1");
      gsonBuilder = new GsonBuilder();
      gson = gsonBuilder.setPrettyPrinting().setVersion(1.1).create();
      jsonString = gson.toJson(emp);
      System.out.println(jsonString);
   }
}
// Employee class
class Employee {
   private String empName;
   private int empId;
   @Since(1.0)
   private String empTech;
   @Since(1.1)
   private String empAddress;
   public String getEmployeeName() {
      return empName;
   }
   public void setEmployeeName(String empName) {
      this.empName = empName;
   }
   public int getEmployeeId() {
      return empId;
   }
   public void setEmployeeId(int empId) {
      this.empId = empId;
   }
   public String getEmployeeTechnology() {
      return empTech;
   }
   public void setEmployeeTechnology(String empTech) {
      this.empTech = empTech;
   }
   public String getEmploeeAddress() {
      return empAddress;
   }
   public void setEmploeeAddress(String empAddress) {
      this.empAddress = empAddress;
   }
}

Output

Since version 0.5
{
   "empName": "Raja Ramesh",
   "empId": 125
}
Since version 1.0
{
   "empName": "Raja Ramesh",
   "empId": 125,
   "empTech": "Java"
}
Since version 1.1
{
   "empName": "Raja Ramesh",
   "empId": 125,
   "empTech": "Java",
   "empAddress": "Hyderabad"
}
raja
Published on 11-Nov-2019 14:10:17
Advertisements