以下是我用于反序列化从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]
将此JSON反序列化为与杰克逊的POJO列表的正确方法是什么?
答案 0 :(得分:0)
您必须为POJO
根对象创建根JSON
。例如:
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]]]
答案 1 :(得分:-1)
尝试使用mapper直接反序列化
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));