Java 如果列表包含不同的类,如何使用 gson 将 json 转换为 arraylist?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27014417/
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
How to use gson to convert json to arraylist if the list contain different class?
提问by CL So
I want to store an arraylist to disk, so I use gson to convert it to string
我想将一个数组列表存储到磁盘,所以我使用 gson 将其转换为字符串
ArrayList<Animal> anim=new ArrayList<Animal>();
Cat c=new Cat();
Dog d=new Dog();
c.parentName="I am animal C";
c.subNameC="I am cat";
d.parentName="I am animal D";
d.subNameD="I am dog";
anim.add(c);
anim.add(d);
Gson gson=new Gson();
String json=gson.toJson(anim);
public class Animal {
public String parentName;
}
public class Cat extends Animal{
public String subNameC;
}
public class Dog extends Animal{
public String subNameD;
}
output string:
输出字符串:
[{"subNameC":"I am cat","parentName":"I am animal C"},{"subNameD":"I am dog","parentName":"I am animal D"}]
Now I want use this string to convert back to arraylist
现在我想用这个字符串转换回 arraylist
I know I should use something like:
我知道我应该使用类似的东西:
ArrayList<Animal> anim = gson.fromJson(json, ArrayList<Animal>.class);
But this is not correct, what is the correct syntax?
但这不正确,正确的语法是什么?
采纳答案by Prasad Khode
you can use the below code to convert json to corresponding list of objects
您可以使用以下代码将 json 转换为相应的对象列表
TypeToken<List<Animal>> token = new TypeToken<List<Animal>>() {};
List<Animal> animals = gson.fromJson(data, token.getType());
回答by norbDEV
Kotlin example:
科特林示例:
val gson = Gson()
val typeToken = object : TypeToken<ArrayList<Animal>>() {}
val list = gson.fromJson<ArrayList<Animal>>(value, typeToken.type)
Faster way:
更快的方法:
val gson = Gson()
val array = gson.fromJson<Array<Animal>>(value, Array<Animal>::class.java)
val arrayList = ArrayList(array.toMutableList())