Java – deserialize immutablelist using gson
I use a lot of immutable collections, and I'm curious about how to deserialize them using gson No one answered. I found a solution myself. I simplified the problem and put forward my own answer
I have two questions:
>How to write a single deserializer for all immutablelists < XXX > > how to register all immutablelists < XXX >?
Solution
The idea is simple. The conversion represents an immutablelist < T > to a type representing list < T >, and uses the built-in gson capability to create a list and convert it to immutablelist
class MyJsonDeserializer implements JsonDeserializer<ImmutableList<?>> { @Override public ImmutableList<?> deserialize(JsonElement json,Type type,JsonDeserializationContext context) throws JsonParseException { final Type type2 = ParameterizedTypeImpl.make(List.class,((ParameterizedType) type).getActualTypeArguments(),null); final List<?> list = context.deserialize(json,type2); return ImmutableList.copyOf(list); } }
There are multiple parameterizedtypeimpl classes in the Java library I use, but they are not used for public use I use sun reflect. generics. reflectiveObjects. Parameterizedtypeimpl tested it
This part is trivial, and the first parameter registered is Java lang.reflect. Type, which misleads me to use parameterizedtype, which simply uses class to do this:
final Gson gson = new GsonBuilder() .registerTypeAdapter(ImmutableList.class,myJsonDeserializer) .create();