Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
like image 905
Droider Avatar asked Dec 25 '22 20:12

Droider


1 Answers

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());
like image 169
Egor Neliuba Avatar answered Dec 27 '22 12:12

Egor Neliuba