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());
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With