小编典典

反序列化内部JSON对象

json

我有一堂课POJO

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

我有一个像

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

我正在使用Jackson ObjectMapper进行反序列化。在List<Pojo>不创建任何其他父类的情况下如何获得?

如果不可能,是否有可能获得Pojo仅包含json字符串的第一个元素的对象,即在这种情况下id="1a"name="foo"


阅读 227

收藏
2020-07-27

共1个答案

小编典典

您首先需要获取数组

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
2020-07-27