GSON Annotations Example

Gson Annotations Example shows you some useful annotations that are provided by Google Gson, for example: @Expose, @SerializedName, @Since, @Until, and @JsonAdapter. With these annotations, we can customize the serialization of java object to JSON or desirialization of object from JSON.

@Expose: this annotation is used to serialize/deserialize a field. This annotation has no effect unless you build Gson with a GsonBuilder and invoke GsonBuilder.excludeFieldsWithoutExposeAnnotation() method.

@SerializedName: this annotation is used to serialize a field with different name instead of using actual field name.

Gson Custom Serialization Sometimes, we need to customize behavior of default serialization/deserialization for our specified requirement. We can do this by writing custom JsonSerializer and JsonDeserializer implementation and registering them with GsonBuilder.

In this Gson Annotations Example, we will customize the importedDate field. We create the MySerializerDate class for serialization like this:

Run the above main on Eclipse, we will get the output like screen shot:

@Since: this annotation is used to manage versioning of Json classes. We can serialize/deserialize a field based on its certain version. @Since annotation and version number indicate a field that we can only serialize/deserialize that field starting that version number. Otherwise, before that version, it will ignored.

@Until: this annotation is used to manage versioning of Json classes. We can serialize/deserialize a field based on its certain version. @Util annotation and version number indicate a field that we can only serialize/deserialize that field util certain version. Otherwise, after that version, it will ignored.

Create Main class using Version for serialization/deserialization Here, We create other main class for serialization/deserialization using version. Simply, we just set version number to GSON builder object like below: