Droider
Droider

Reputation: 93

How do I use custom deserialization on gson for generic type?

For standard POJO, 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());

How about if the POJO is generic? The Gson user guide doesn't mention it. Below is my code but it's not the correct one.

gsonBuilder.registerTypeAdapter(CustomResponse<POJOA>.getClass(), new POJOADeserializer());
gsonBuilder.registerTypeAdapter(CustomResponse<POJOB>.getClass(), new POJOBDeserializer());
gsonBuilder.registerTypeAdapter(CustomResponse<POJOC>.getClass(), new POJOCDeserializer());

Upvotes: 4

Views: 2279

Answers (1)

Egor Neliuba
Egor Neliuba

Reputation: 15054

Instead of doing this:

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

Register your deserializer like so:

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

Upvotes: 10

Related Questions