是否有可能使用Gson.fromJson()来获取的ArrayList&LT; ArrayList的&LT;串GT;&GT ;? [英] is it possible to use Gson.fromJson() to get ArrayList<ArrayList<String>>?
问题描述
让我们说我有阵列的 JSON
阵列
let's say i have a json
array of arrays
String jsonString = [["John","25"],["Peter","37"]];
我想parst到的ArrayList&LT这一点; ArrayList的&LT;串GT;&GT;
的对象。当我用
Gson.fromJson(jsonString,ArrayList的&LT; ArrayList的&LT;串GT;&GT;的.class)
它似乎没有工作,我通过做一个变通
it doesn't seem to work and i did a work around by using
Gson.fromJson(jsonString,字符串[] []类)
有没有更好的方式来做到这一点?
is there a better way to do this?
推荐答案
是的,使用<一个href=\"http://google-gson.google$c$c.com/svn/trunk/gson/docs/javadocs/com/google/gson/reflect/TypeToken.html\"><$c$c>TypeToken$c$c>.
ArrayList<ArrayList<String>> list = gson.fromJson(jsonString, new TypeToken<ArrayList<ArrayList<String>>>() {}.getType());
的 TypeToken
允许你指定你真正想要的泛型类型,这有助于GSON找到反序列化类型时使用。
The TypeToken
allows you to specify the generic type you actually want, which helps Gson find the types to use during deserialization.
它使用这种宝石:<一href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getGenericSuperclass%28%29\"><$c$c>Class#getGenericSuperClass()$c$c>.它是一个匿名类的事实使得它的子类 TypeToken&LT的; ...&GT;
。它等同于像
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
如果超类是参数化类型,键入
返回对象必须准确反映源$ C $ C使用的实际类型参数。
If the superclass is a parameterized type, the
Type
object returned must accurately reflect the actual type parameters used in the source code.
如果您指定
new TypeToken<String>(){}.getType();
在键入
对象返回实际上是一个 ParameterizedType
上,您可以检索与<一个实际类型参数href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/ParameterizedType.html#getActualTypeArguments%28%29\"><$c$c>ParameterizedType#getActualTypeArguments()$c$c>.
the Type
object returned would actually be a ParameterizedType
on which you can retrieve the actual type arguments with ParameterizedType#getActualTypeArguments()
.
类型参数将在上面的例子中为 java.lang.String中
的键入
对象。在你的榜样,这将是对应的
。 GSON会保持下去链,直到建立完整的地图,它需要的类型。键入
对象的ArrayList&LT; ArrayList的&LT;弦乐&GT;&GT;
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.
这篇关于是否有可能使用Gson.fromJson()来获取的ArrayList&LT; ArrayList的&LT;串GT;&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!