GSON Annotations Example using JsonAdapter

This tutorial shows you how to create GSON Annotations Example using JsonAdapter. The @JsonAdapter annotation is one of userful GSON annotations. This annotation be used at field or class level to specify the Gson TypeAdapter for serializing or deserializing.

GSON converts java classes to JSON using its built-in type adapters by default. Sometimes, They doesn’t fit your specified requirements. So you can customize them by implementing custom type adapters.

Other interesting posts you may like

Table of contents:
1. Project structure
2. Create POJO
3. Create custom type adapter
4. Create Main class

Project structure
We will create project with structure like this:

GSON Annotations Example using JsonAdapter

Create POJO
First, we need to create POJO which is annotated with custom type adapter. It looks like below:

As you can see, the above Fruit POJO is annotated with MyCustomTypeAdapter using @JsonAdapter annotation.

Now, we’re starting to create our custom type adapter named MyCustomTypeAdapter. The MyCustomTypeAdapter class looks like below:

Above is a custom type adapter which extends TypeAdapter class and we simply overrides read and write methods. These methods are used for serialization and deserialization.

These read and write methods are implemented with token based approach. During deserialization process, we read token and iterate over them one by one using JsonReader’s hasNext and nextName methods. One more thing, We must process opening and closing brackets using beginObject and endObject (or beginArray/endArray) methods.

Notices that @JsonAdapter annotation can be used on both class and field level. In this GSON Annotations Example using JsonAdapter, we are using it on class level.

Finally, we create main class for this GSON Annotations Example using JsonAdapter:

Running the above main class on Eclipse, we get the output like this:

GSON Annotations Example using JsonAdapter

Notices that we can register our custom type adapter with GsonBuilder instead of using this annotation @JsonAdapter. This registration looks like below:

And we will get same result as annotation usage.

That’s it. Hope that this GSON Annotations Example using JsonAdapter tutorial helps you create your own custom type adapter.

Download source code, click link below

Gson-JsonAdapter-Annotation-Example.zip

Leave a Comment

*

Please share it if you found this useful
Hide Buttons