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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.