【问题标题】:Convert json array to a java list object [duplicate]将json数组转换为java列表对象[重复]
【发布时间】:2013-02-16 00:34:39
【问题描述】:

我从服务器 response 得到一个 json 数组

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

我想用gson把上面的json数据转换成Java的List<Person>对象。我尝试了以下方法:

首先,我创建了一个 Person.java 类:

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;
  }
}

然后,在我的服务类中,我执行了以下操作:

//'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 cannot be cast to Person。如何摆脱我的问题?我只想将 json 数组转换为 List&lt;Person&gt; 对象。有什么帮助吗?

【问题讨论】:

    标签: java json


    【解决方案1】:

    您需要使用超类型标记进行解组,以便 Gson 知道列表中的泛型类型是什么。试试这个:

    TypeToken<List<Person>> token = new TypeToken<List<Person>>(){};
    List<Person> personList = gson.fromJson(response, token.getType());
    

    并像这样遍历结果:

    for(Person person : personList) {
        // some code here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 2020-02-06
      • 2015-04-21
      • 2021-10-18
      相关资源
      最近更新 更多