[英]deserialize inner JSON object
I have a class POJO 我上了一堂POJO
Class Pojo {
String id;
String name;
//getter and setter
}
I have a json like 我有一个像
{
"response" : [
{
"id" : "1a",
"name" : "foo"
},
{
"id" : "1b",
"name" : "bar"
}
]
}
I am using Jackson ObjectMapper for deserialization. 我正在使用Jackson ObjectMapper进行反序列化。 How can I get List<Pojo>
without creating any other parent class? 如何在不创建任何其他父类的情况下获取List<Pojo>
?
If it is not possible, is it possible to get Pojo
object which holds just first element of json string ie in this case id="1a"
and name="foo"
? 如果不可能,是否有可能获得仅保存json字符串的第一个元素的Pojo
对象,即在这种情况下为id="1a"
和name="foo"
?
You'll first need to get the array 您首先需要获取数组
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);
prints (with a toString()
) 打印(带有toString()
)
[{"id":"1a","name":"foo"},{"id":"1b","name":"bar"}] // the json array
[id = 1a, name = foo, id = 1b, name = bar] // the list contents
You can use the generic readTree with JsonNode: 您可以将通用readTree与JsonNode结合使用:
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
JsonNode response = root.get("response");
List<Pojo> list = mapper.readValue(response, new TypeReference<List<Pojo>>() {});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.