GSON makes the conversion JSON to POJO very easily

As a java developer one should know JSONObject very well. On the other hand, if one depends so heavily on JSONObject, the conversion from JSON to POJO becomes sometimes a burden if the structure of JSON string is very complex. One has to write so many codes to call JSONObject.getString("") and so on. Thanks GSON, there is a better way to convert JSON to java object.

 Define a java class to be an exact model of the JSON string like: 
{"book":{"translations":[{"translatedText":"Bonjour tout le monde"}]}} 
The java class:
class BookWrapper {
    public Book book;

    public static BookWrapper fromJson(String s) {
        return new Gson().fromJson(s, DataWrapper.class);
    public String toString() {
        return new Gson().toJson(this);
class Book {
    public List<Translation> translations;
class Translation { 
    public String translatedText;
As you can see, it's very convenient and elegant to use BookWrapper.fromJson(JsonString) to convert a JSON string to the java object.
Furthermore, GSON supports the versioning of a java object. It's helpful when the JSON structure has been changed with some versions.

Usage taken from the GSON user guide:

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();gson = new Gson();
jsonOutput = gson.toJson(someObject);

======== OUTPUT ========

No comments: