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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:38:57  来源:igfitidea点击:

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

javagenericsarraylistgson

提问by Thirumalai Parthasarathi

let's say i have a jsonarray 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 TypeTokenallows 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 Typeobject returned must accurately reflect the actual type parameters used in the source code.

如果超类是参数化类型,则Type返回的对象必须准确反映源代码中使用的实际类型参数。

If you specified

如果您指定

new TypeToken<String>(){}.getType();

the Typeobject returned would actually be a ParameterizedTypeon which you can retrieve the actual type arguments with ParameterizedType#getActualTypeArguments().

Type返回的对象实际上是 a ParameterizedType,您可以使用ParameterizedType#getActualTypeArguments().

The type argument would be the Typeobject for java.lang.Stringin the example above. In your example, it would be a corresponding Typeobject 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 会继续沿着这条链走下去,直到它构建出它需要的类型的完整地图。