将json数组转换为java列表对象 [英] Convert json array to a java list object
问题描述
我从服务器回复
获得 json数组:
[{"id":1, "name":"John", "age": 20},{"id":3, "name":"Tomas", "age": 29}, {"id":12, "name":"Kate", "age": 32}, ...]
我想使用 gson 转换上述json数据到Java 列表< Person>
对象。我尝试了以下方式:
I would like to use gson to convert the above json data to a Java List<Person>
object. I tried the following way:
首先,我创建了一个 Person.java 类:
Firstly, I created a Person.java class:
public class Person{
private long id;
private String name;
private int age;
public long getId(){
return id;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
然后,在我的服务类中,我做了以下:
Then, in my service class, I did the following:
//'response' is the above json array
List<Person> personList = gson.fromJson(response, List.class);
for(int i=0; i<personList.size(); i++){
Person p = personList.get(i); //java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to Person
}
我遇到了异常 java.lang.ClassCastException:java.util.LinkedHashMap无法强制转换为Person 。如何摆脱我的问题?我只想将json数组转换为 List< Person>
对象。有什么帮助吗?
I got Exception java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to Person . How to get rid of my problem? I just want to convert the json array to a List<Person>
object. Any help?
推荐答案
您需要使用超类型令牌进行解组,以便Gson知道列表中的泛型类型是。试试这个:
You need to use a supertype token for the unmarshalling, so that Gson knows what the generic type in your list is. Try this:
TypeToken<List<Person>> token = new TypeToken<List<Person>>(){};
List<Person> personList = gson.fromJson(response, token.getType());
并按原样迭代结果:
for(Person person : personList) {
// some code here
}
这篇关于将json数组转换为java列表对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!