Yes, use a TypeToken
.
ArrayList<ArrayList<String>> list = gson.fromJson(jsonString, new TypeToken<ArrayList<ArrayList<String>>>() {}.getType());
The TypeToken
allows you to specify the generic type you actually want, which helps Gson find the types to use during deserialization.
It uses this gem: Class#getGenericSuperClass()
. The fact that it is an anonymous class makes it a sub class of TypeToken<...>
. It's equivalent to a class like
class Anonymous extends TypeToken<...>
The specification of the method states that
If the superclass is a parameterized type, the Type
object returned must accurately reflect the actual type parameters used in the source code.
If you specified
new TypeToken<String>(){}.getType();
the Type
object returned would actually be a ParameterizedType
on which you can retrieve the actual type arguments with ParameterizedType#getActualTypeArguments()
.
The type argument would be the Type
object for java.lang.String
in the example above. In your example, it would be a corresponding Type
object for ArrayList<ArrayList<String>>
. Gson would keep going down the chain until it built the full map of types it needs.