【问题标题】:Deserialize JSON string into a List of POJOs将 JSON 字符串反序列化为 POJO 列表
【发布时间】:2014-06-27 14:16:54
【问题描述】:

这是我用于反序列化从 Google App Engine Cloud Endpoint 返回的响应的代码:

String jsonString = IOUtils.toString(
    httpResponse.getEntity().getContent(), "UTF-8");

ObjectMapper mapper = new ObjectMapper();
ArrayList<myPOJO> myList= 
    mapper.readValue(jsonString, new TypeReference<ArrayList<MyPOJO>>(){});

jsonString 看起来像这样:

{
  "items" : [ {
    "id" : "12345",
    "name" : "test1"
  }, {
    "id" : "121212",
    "name" : "test2"
  } ]
}

但我收到此错误:

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at [Source: java.io.StringReader@547a7880; line: 1, column: 1]

使用 Jackson 将此 JSON 反序列化为 POJO 列表的正确方法是什么?

【问题讨论】:

  • 你的 jsonString 是一个对象,而不是列表。
  • 您可以为此目的使用杰克逊库。

标签: java json google-app-engine jackson google-cloud-endpoints


【解决方案1】:

您必须为您的JSON 根对象创建根POJO。例如:

class Root {

    private List<Entity> items;

    //getters, setters, toString, etc
}

class Entity {

    private long id;
    private String name;

    //getters, setters, toString, etc
}

简单的应用:

ObjectMapper mapper = new ObjectMapper();
Root list = mapper.readValue(json, Root.class);
System.out.println(list);

打印:

Root [items=[Entity [id=12345, name=test1], Entity [id=121212, name=test2]]]

【讨论】:

    【解决方案2】:

    尝试使用映射器直接反序列化

    String jsonString = IOUtils.toString(
            httpResponse.getEntity().getContent(), "UTF-8");
    
        ObjectMapper mapper = new ObjectMapper();
    
        List<MyPOJO> myList= mapper.convertValue(jsonString, mapper.getTypeFactory().constructCollectionType(List.class, MyPOJO.class));
    

    【讨论】:

    • 那行不通。错误只是更改为Caused by: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 2021-01-08
    • 1970-01-01
    相关资源
    最近更新 更多