反序列化内部JSON对象 [英] deserialize inner JSON object
本文介绍了反序列化内部JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类POJO
Class Pojo {
String id;
String name;
//getter and setter
}
我有一个类似的json
I have a json like
{
"response" : [
{
"id" : "1a",
"name" : "foo"
},
{
"id" : "1b",
"name" : "bar"
}
]
}
我使用Jackson ObjectMapper进行反序列化。如何在不创建任何其他父类的情况下获得 List< Pojo>
?
I am using Jackson ObjectMapper for deserialization. How can I get List<Pojo>
without creating any other parent class?
如果不可能,则是有可能获得 Pojo
对象,它只包含json字符串的第一个元素,即在这种情况下 id =1a
和 name =foo
?
If it is not possible, is it possible to get Pojo
object which holds just first element of json string i.e. in this case id="1a"
and 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
这篇关于反序列化内部JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文