2013-09-30 72 views
2

我有一個類POJO反序列化內JSON對象

Class Pojo { 
String id; 
String name; 
//getter and setter 
} 

我有這樣

{ 
    "response" : [ 
     { 
      "id" : "1a", 
      "name" : "foo" 
     }, 
     { 
      "id" : "1b", 
      "name" : "bar" 
     } 
    ] 
} 

我使用傑克遜ObjectMapper反序列化一個JSON。如何在不創建任何其他父類的情況下獲得List<Pojo>

如果不可能,是否有可能得到Pojo對象,該對象只持有json字符串的第一個元素,即在這種情況下爲id="1a"name="foo"

+0

似乎相似[這篇文章關於數組反序列化。](http://stackoverflow.com/questions/6349421/how-to-use-jackson-to-deserialise-an-arra y-of-objects) – Admit

+0

我可以問你爲什麼取消接受的答案嗎? – Enrichman

回答

2

首先,您需要獲得陣列

String jsonStr = "{\"response\" : [ { \"id\" : \"1a\", \"name\" : \"foo\"},{ \"id\" : \"1b\",\"name\" : \"bar\" } ]}"; 
ObjectMapper mapper = new ObjectMapper(); 
JsonNode node = mapper.readTree(jsonStr); 
ArrayNode arrayNode = (ArrayNode) node.get("response"); 
System.out.println(arrayNode); 
List<Pojo> pojos = mapper.readValue(arrayNode.toString(), new TypeReference<List<Pojo>>() {}); 

System.out.println(pojos); 

打印(使用toString()

[{"id":"1a","name":"foo"},{"id":"1b","name":"bar"}] // the json array 
[id = 1a, name = foo, id = 1b, name = bar] // the list contents 
1

您可以使用JsonNode通用readTree:

ObjectMapper mapper = new ObjectMapper(); 
JsonNode root = mapper.readTree(json); 
JsonNode response = root.get("response"); 
List<Pojo> list = mapper.readValue(response, new TypeReference<List<Pojo>>() {});