Java Google Json (Gson) Custom Serializer

Just as we saw in the previous tutorial, Gson provides way to specify custom serializers and deserializers. Register a custom serializer with the GsonBuilder if you need you own way to convert a java object to json and you a custom deserializer if you dont like Gson’s way of converting json to the java object. The first example below shows a custom serializer and the second example shows a custom deserializer.

Custom Serializer

Create a custom serializer by implementing a com.studytrails.json.gson.JsonSerializer and implementing the public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context); method. src is the source object and Type is the type of the source object. The example below demonstrates a custom Serializer.

The Animal class

The Dog class

Custom DeSerializer

Use a custome De serializer to create a Dog Object from the json. To create a deserializer implement the
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException;

Java Google Json (Gson) Custom Serializer

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to top