- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we use @Since annotation using Gson in Java?
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" }
Advertisements