要输入的 Jackson JsonNode Collection

Jackson JsonNode to typed Collection

将 Jackson JsonNode 转换为 java collection 的正确方法是什么?

如果它是一个 json 字符串,我可以使用 ObjectMapper.readValue(String, TypeReference) 但对于 JsonNode 唯一的选项是 ObjectMapper.treeToValue(TreeNode, Class),它不会给出类型 collection,或 ObjectMapper.convertValue(Object, JavaType),因为它接受任何 POJO 进行转换而感觉不对。

还有其他 "correct" 方法还是其中之一?

获得 ObjectReader with ObjectMapper#readerFor(TypeReference) using a TypeReference describing the typed collection you want. Then use ObjectReader#readValue(JsonNode) to parse the JsonNode (presumably an ArrayNode).

例如,要从仅包含 JSON 个字符串的 JSON 数组中获取 List<String>

ObjectMapper mapper = new ObjectMapper();
// example JsonNode
JsonNode arrayNode = mapper.createArrayNode().add("one").add("two");
// acquire reader for the right type
ObjectReader reader = mapper.readerFor(new TypeReference<List<String>>() {
});
// use it
List<String> list = reader.readValue(arrayNode);

ObjectMapper.convertValue()函数方便又type-aware。它可以在树节点和 Java types/collections 和 vice-versa.

之间执行广泛的转换

您可以如何使用它的示例:

List<String> list = new ArrayList<>();
list.add("one");
list.add("two");

Map<String,List<String>> hashMap = new HashMap<>();
hashMap.put("myList", list);

ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.convertValue(hashMap, ObjectNode.class);
Map<String,List<String>> hashMap2 = mapper.convertValue(objectNode, new TypeReference<Map<String, List<String>>>() {});

如果迭代器更有用...

...你也可以使用ArrayNodeelements()方法。示例见下文。

sample.json

{
    "first": [
        "Some string ...",
        "Some string ..."
    ],
    "second": [
        "Some string ..."
    ]
}

因此,List<String> 位于 JsonNode 之一内。

Java

当您将该内部节点转换为 ArrayNode 时,您可以使用 elements() 方法,该方法 returns JsonNodes 的迭代器。

File file = new File("src/test/resources/sample.json");
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(file);
ArrayNode arrayNode = (ArrayNode) jsonNode.get("first");
Iterator<JsonNode> itr = arrayNode.elements();
// and to get the string from one of the elements, use for example...
itr.next().asText();

Jackson 对象映射器的新手?

我喜欢这个教程: https://www.baeldung.com/jackson-object-mapper-tutorial

更新:

你也可以使用ArrayNode.iterator()方法。是一样的:

Same as calling .elements(); implemented so that convenience "for-each" loop can be used for looping over elements of JSON Array constructs.

来自 com.fasterxml.jackson.core:jackson-databind:2.11.0

的 javadoc