Gson Tutorial
Gson Useful Resources
Selected Reading
- Excluding fields from Serialization
- Gson - Versioning Support
- Gson - Null Object Support
- Gson - Custom Type Adapters
- Gson - Serializing Inner Classes
- Gson - Serialization Examples
- Gson - Streaming
- Gson - Tree Model
- Gson - Object Data Binding
- Gson - Data Binding
- Gson - Object Serialization
- Gson - Class
- Gson - First Application
- Gson - Environment Setup
- Gson - Overview
- Gson - Home
Gson Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Gson - Versioning Support
Gson - Versioning Support
Gson provides @Since annotation to control the Json seriapzation/deseriapzation 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 seriapze 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; pubpc class GsonTester { pubpc 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; pubpc int getRollNo() { return rollNo; } pubpc void setRollNo(int rollNo) { this.rollNo = rollNo; } pubpc String getName() { return name; } pubpc void setName(String name) { this.name = name; } pubpc void setVerified(boolean verified) { this.verified = verified; } pubpc 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