![](/img/trans.png)
[英]Deserialize JSON Array with different POJOs in java with Jackson
[英]Deserialize JSON string into a List of POJOs
這是我的代碼,用於反序列化從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列表的正確方法是什么?
您必須為您的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]]]
嘗試直接使用映射器反序列化
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.