let's say i have a json
array of arrays
String jsonString = [["John","25"],["Peter","37"]];
i would like to parst this into ArrayList<ArrayList<String>>
objects. when i used
Gson.fromJson(jsonString,ArrayList<ArrayList<String>>.class)
it doesn't seem to work and i did a work around by using
Gson.fromJson(jsonString,String[][].class)
is there a better way to do this?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With