Java – How do I use custom deserialization on generic types of gson?

How do I use custom deserialization on generic types of gson?… here is a solution to the problem.

How do I use custom deserialization on generic types of gson?

For standard POJOs, we can use the following

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(MyType2.class, new MyTypeAdapter());
gson.registerTypeAdapter(MyType.class, new MySerializer());
gson.registerTypeAdapter(MyType.class, new MyDeserializer());
gson.registerTypeAdapter(MyType.class, new MyInstanceCreator());

What if POJOs are generic? Gson user guide doesn’t mention it. Below is my code, but incorrect.

<pre class=”lang-java prettyprint-override”>gsonBuilder.registerTypeAdapter(CustomResponse<POJOA>.getClass(), new POJOADeserializer());
gsonBuilder.registerTypeAdapter(CustomResponse<POJOB>.getClass(), new POJOBDeserializer());
gsonBuilder.registerTypeAdapter(CustomResponse<POJOC>.getClass(), new POJOCDeserializer());

Solution

Instead of doing this :

gsonBuilder.registerTypeAdapter(CustomResponse<POJOA>.getClass(), new POJOADeserializer());

Register your deserializer like this:

gsonBuilder.registerTypeAdapter(
        new TypeToken<CustomResponse<POJOA>>(){}.getType(), new POJOADeserializer());

Related Problems and Solutions