我有一个 POJO 类
Class Pojo {
String id;
String name;
//getter and setter
}
我有一个像这样的json
{
"response" : [
{
"id" : "1a",
"name" : "foo"
},
{
"id" : "1b",
"name" : "bar"
}
]
}
我正在使用 Jackson ObjectMapper 进行反序列化。我怎样才能得到List<Pojo>
不创建任何其他父类?
如果不可能,是否可以得到Pojo
仅包含 json 字符串的第一个元素的对象,即在本例中 id="1a"
和name="foo"
?
最佳答案
您首先需要获取数组
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
关于java - 反序列化内部 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19096893/