I’m using quite a few immutable collections and I’m curious how to deserialize them using Gson. As nobody answered and I’ve found the solution myself, I’m simplifying the question and presenting my own answer.
I had two problems:
- How to write a single
Deserializerworking for allImmutableList<XXX>? - How to register it for all
ImmutableList<XXX>?
Update: There’s https://github.com/acebaggins/gson-serializers which covers many guava collections:
ImmutableListImmutableSetImmutableSortedSetImmutableMapImmutableSortedMapThe idea is simple, transform the passed
Typerepresenting anImmutableList<T>into aTyperepresentingList<T>, use the build-inGson‘s capability to create aListand convert it to anImmutableList.There are multiple
ParameterizedTypeImplclasses in Java libraries I use, but none of them intended for public usage. I tested it withsun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.That part is trivial, the first argument to register is
java.lang.reflect.Typewhich mislead me to usingParameterizedType, where simply usingClassdoes the job: