Java 是否可以使用 Gson.fromJson() 来获取 ArrayList<ArrayList<String>>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22271779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is it possible to use Gson.fromJson() to get ArrayList<ArrayList<String>>?
提问by Thirumalai Parthasarathi
let's say i have a json
array of arrays
假设我有一json
组数组
String jsonString = [["John","25"],["Peter","37"]];
i would like to parst this into ArrayList<ArrayList<String>>
objects. when i used
我想把它分解成ArrayList<ArrayList<String>>
对象。当我使用
Gson.fromJson(jsonString,ArrayList<ArrayList<String>>.class)
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)
Gson.fromJson(jsonString,String[][].class)
is there a better way to do this?
有一个更好的方法吗?
采纳答案by Sotirios Delimanolis
Yes, use a TypeToken
.
是的,使用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.
将TypeToken
允许你指定你真正想要的泛型类型,这有助于GSON找到类型来使用反序列化过程。
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#getGenericSuperClass()
。它是一个匿名类的事实使它成为TypeToken<...>
. 它相当于一个类
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.
如果超类是参数化类型,则
Type
返回的对象必须准确反映源代码中使用的实际类型参数。
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()
.
Type
返回的对象实际上是 a ParameterizedType
,您可以使用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.
类型参数将是上面示例中的Type
对象java.lang.String
。在你的榜样,这将是一个相应Type
的对象ArrayList<ArrayList<String>>
。Gson 会继续沿着这条链走下去,直到它构建出它需要的类型的完整地图。