GSON Versioning Support with @Since Annotation

GSON introduced the @Since annotation to support multiple versions of the same object. We can use this annotation on Classes and Fields. In order to enable this feature we need to register a version number to use when serializing/deserializing. If no version number is set on the Gson instance, all the fields will be serialized/deserialized regardless of the version. Gson Versioning basically allows you to hide or add fields of your classes to support multiple versions.

Gson Versioning Support

The @Since annotation is used to annotate your classes or fields with a version number. This annotation takes a double as argument indicating the version number from when this field is available.

package com.memorynotfound.json;

import com.google.gson.annotations.Since;
import java.lang.management.ManagementFactory;

@Since(1.0)
public class Health {

    @Since(1.1)
    private String hostname;
    @Since(1.1)
    private String ip;
    private long startTime;
    private long upTime;

    public Health(String hostname, String ip) {
        this.hostname = hostname;
        this.ip = ip;
        this.startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
        this.upTime = ManagementFactory.getRuntimeMXBean().getUptime();
    }
}

When no version number is specified in the Gson instance, all fields are serialized/deserialized. When a version number is specified, all fields that match that version number are used.

package com.memorynotfound.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class Run {

    public static void main(String... args){
        Health health = new Health("http://memorynotfound.com", "123.123.123.123");
        Gson gson = new GsonBuilder()
                .setPrettyPrinting()
                .create();
        String result = gson.toJson(health);
        System.out.println("Without version: " + result);

        gson = new GsonBuilder()
                .setVersion(1.0)
                .setPrettyPrinting()
                .create();
        result = gson.toJson(health);
        System.out.println("Version 1.0: " + result);

        gson = new GsonBuilder()
                .setVersion(1.1)
                .setPrettyPrinting()
                .create();
        result = gson.toJson(health);
        System.out.println("Version 1.1: " + result);
    }
}

Generated output.

Without version: {
  "hostname": "http://memorynotfound.com",
  "ip": "123.123.123.123",
  "startTime": 1455099486512,
  "upTime": 52
}
Version 1.0: {
  "startTime": 1455099486512,
  "upTime": 52
}
Version 1.1: {
  "hostname": "http://memorynotfound.com",
  "ip": "123.123.123.123",
  "startTime": 1455099486512,
  "upTime": 52
}

References

Download

You may also like...