数组转换json数组 java对象,将json数组转换为java列表对象

I got an json array from server response:

[{"id":1, "name":"John", "age": 20},{"id":3, "name":"Tomas", "age": 29}, {"id":12, "name":"Kate", "age": 32}, ...]

I would like to use gson to convert the above json data to a Java List object. I tried the following way:

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 personList = gson.fromJson(response, List.class);

for(int i=0; i

Person p = personList.get(i); //java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to 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 object. Any help?

解决方案

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> token = new TypeToken>(){};

List personList = gson.fromJson(response, token.getType());

And iterate through the results as such:

for(Person person : personList) {

// some code here

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值