星期六, 4月 30, 2011

Versioning Support

Multiple versions of the same object can be maintained by using @Since annotation. This annotation can be used on Classes, Fields and, in a future release, Methods.  In order to leverage this feature, you must configure your Gson instance to ignore any field/object that is greater than some version number.  If no version is set on the Gson instance then it will serialize and deserialize all fields and classes regardless of the version.

public class VersionedClass {
  @Since(1.1) private final String newerField;
  
@Since(1.0) private final String newField;
  private final String field;

  public VersionedClass() {
    this.newerField = "newer";
    this.newField = "new";
    this.field = "old";
  }
}

VersionedClass versionedObject = new VersionedClass();
Gson gson = new GsonBuilder().setVersion(1.0).create();

String jsonOutput = gson.toJson(someObject);
System.out.println(jsonOutput);
System.out.println();
gson = new Gson();
jsonOutput = gson.toJson(someObject);
System.out.println(jsonOutput);


======== OUTPUT ========
{"newField":"new","field":"old"}
{"newerField":"newer","newField":"new","field":"old"}

沒有留言: