Version Support in GSON

Gson providing a simple versioning system for the Java objects that it reads and writes.

Gson providing an annotation named @Since for the versioning concept


Way To create Gson instance with versioning:

Gson gson = new GsonBuilder().setVersion(double versionnumber).create();

The above setVersion(versionnumber) will works like this. Assume we mentinoed like this 'setVersion(2.0)' means all the fileds having 2.0 or less are eligible to parse.

Here is an example Person class with its fields annotated with the @Since annotation:

 * @author
package com.tutorialtous.gson;
import java.util.LinkedList;
import java.util.List;
public class Player {
  @Since(1.0) public String name;
  @Since(1.1) public String firstName = null;
  @Since(1.1) public String lastName = null;
  @Since(2.0) public String middleName = null;
  @Since(3.0) public String email = null;
  @Since(1.0) public String gender;
  @Since(1.0) public int age;
  @Since(1.0) public List<String> gamesplayed = new LinkedList<>();

Second, we must create a GsonBuilder and tell it what version it should be serializing to and deserializing from.

 * @author
package com.tutorialtous.gson;
public class VersioningExample {
  public static void main(String args[]) {
    Player obj = new Player();
    obj.age = 29; = "Alex"; obj.gender = null;
    Gson gson = new Gson();
    GsonBuilder builder = new GsonBuilder();
    gson = builder.setVersion(1.0).create();
    System.out.println("1.0 "+gson.toJson(obj));
    gson = builder.setVersion(1.1).create();
    System.out.println("1.1 "+gson.toJson(obj));
    gson = builder.setVersion(3.0).create();
    System.out.println("3.0 "+gson.toJson(obj));
1.0 {"name":"Alex","age":29,"gamesplayed":[]}
1.1 {"name":"Alex","firstName":"Steward","lastName":"Alex","age":29,"gamesplayed":[]}
3.0 {"name":"Alex","firstName":"Steward","lastName":"Alex","email":"",

In the Player example class stated above 'name,gender,age,gamesplayed' are versioned with 1.0 so for the setVersion(1.0) we got those.

Now for the 1.1 version, 1.1 and 1.0 versioned fields will appear (having not null values) similar concept applied for 3.0 versioning means fields <=3.0 @Since anotated ones.

Copyright © 2018-2020 TutorialToUs. All rights reserved.