2013-09-30 4 views
2

나는 내가 직렬화 잭슨 ObjectMapper를 사용하고직렬화 내부 JSON 객체

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

같은 JSON이 클래스 POJO

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

있습니다. 다른 부모 클래스를 만들지 않고 List<Pojo>을 얻으려면 어떻게해야합니까?

가능하지 않은 경우 Pojojson 문자열의 첫 번째 요소 즉,이 경우 id="1a"name="foo"을 보유 할 수 있습니까?

+0

비슷한 것 같다 to [이 게시물에 대한 배열 deserialization.] (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>>() {});