【问题标题】:Jackson JsonNode to typed CollectionJackson JsonNode 到类型化集合
【发布时间】:2016-08-30 22:08:10
【问题描述】:

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

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

还有其他“正确”的方式还是其中之一?

【问题讨论】:

    标签: java json collections jackson type-erasure


    【解决方案1】:

    使用描述您想要的类型化集合的TypeReference 获取ObjectReaderObjectMapper#readerFor(TypeReference)。然后用ObjectReader#readValue(JsonNode)解析JsonNode(大概是一个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);
    

    【讨论】:

    • 在较早的 Jackson 版本(2.5 及之前)中,没有 readerFor() 方法。请改用 reader() 方法。
    【解决方案2】:

    如果迭代器更有用...

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

    sample.json

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

    所以,List&lt;String&gt;JsonNodes 之一内。

    Java

    当您将该内部节点转换为 ArrayNode 时,您可以使用 elements() 方法,该方法返回 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() 方法。是一样的:

    与调用相同 .elements();实现了方便的“for-each”循环 用于循环遍历 JSON Array 结构的元素。

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

    【讨论】:

      【解决方案3】:

      ObjectMapper.convertValue() 函数既方便又能识别类型。它可以在树节点和 Java 类型/集合之间执行各种转换,反之亦然。

      如何使用它的示例:

      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>>>() {});
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-16
        相关资源
        最近更新 更多