Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

java - is it possible to use Gson.fromJson() to get ArrayList<ArrayList<String>>?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...