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
Deserializer
working 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:
ImmutableList
ImmutableSet
ImmutableSortedSet
ImmutableMap
ImmutableSortedMap
The idea is simple, transform the passed
Type
representing anImmutableList<T>
into aType
representingList<T>
, use the build-inGson
's capability to create aList
and convert it to anImmutableList
.There are multiple
ParameterizedTypeImpl
classes 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.Type
which mislead me to usingParameterizedType
, where simply usingClass
does the job:One more implementation without ParameterizedTypeImpl
@maaartinus already covered the second question, so I'll post a complementary Guava-based solution to the first question which doesn't require
ParametrizedTypeImpl