是否可以使用 Gson.fromJson() 来获取 ArrayList<ArrayList<String>>? [英] is it possible to use Gson.fromJson() to get ArrayList<ArrayList<String>>?
问题描述
假设我有一个 json
数组
String jsonString = [["John","25"],["Peter","37"]];
我想将其解析为 ArrayList
对象.当我使用
i would like to parst this into ArrayList<ArrayList<String>>
objects. when i used
Gson.fromJson(jsonString,ArrayList
它似乎不起作用,我通过使用来解决
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?
推荐答案
是的,使用 TypeToken
.
Yes, use a TypeToken
.
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.
它使用这个 gem:Class#getGenericSuperClass()
.它是一个匿名类的事实使它成为 TypeToken<...>
的子类.相当于一个类
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<...>
该方法的规范指出
如果超类是参数化类型,返回的Type
对象必须准确反映源代码中使用的实际类型参数.
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();
返回的 Type
对象实际上是一个 ParameterizedType
,您可以在其上使用 ParameterizedType#getActualTypeArguments()
.
the Type
object returned would actually be a ParameterizedType
on which you can retrieve the actual type arguments with ParameterizedType#getActualTypeArguments()
.
类型参数将是上述示例中 java.lang.String
的 Type
对象.在您的示例中,它将是 ArrayList
的相应 Type
对象.Gson 会继续沿着链条向下移动,直到构建出所需类型的完整地图.
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<ArrayList<String>>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!