Gson

Gson is a Java library that can be used to convert Java Objects into their JSON representation and vice versa.

Add dependency

dependencies {
    implementation 'com.google.code.gson:gson:2.8.6'
}

Gson is very easy to use.

Full example:
// how to use library
    Gson gson = new Gson();
    String dstJson = gson.toJson(srcObj);
    JsonElement dstTree = gson.toJsonTree(srcObj);
    Cls dstObj = gson.fromJson(srcJson, Cls.class);
    System.out.println(dstJson);
    System.out.println(dstObj.map.get("book2"));

You can get more information at Gson on GitHub.

annotations

By default, all fields of an object will be serialized/deserialized.

Google Gson provides useful annotations which can customize the serialization/deserialization of object to/from JSON.

Examples:
annotation description
Expose Indicates how this member should be exposed for JSON serialization or deserialization.
JsonAdapter Specifies the Gson TypeAdapter for a class or field.
SerializedName Specifies the JSON name of field.
Since Indicates the version number since a member or a type has been present.
Until Indicates the version number until a member or a type should be present.

custom serialization and deserialization

By default Gson converts application classes to JSON using its built-in type adapters. Gson allows to provide a custom adapters for

  • JSON serializers - custom serialization for an object
  • JSON deserializers - custom deserialization for a type
  • instance creators - not needed if no-args constructor is available or a deserializer is registered
  • type adapters - if Gson's default JSON conversion isn't appropriate for a type, extend the TypeAdapter class to customize the conversion.

Examples: