首页 > 解决方案 > Jackson - 从嵌套元素开始

问题描述

如何从嵌套元素中读取 XML。

例子:

<main>
    <child>
        <child2>
            <child3>
                <user>
                    <name>John</name>
                </user>
                <user>
                    <name>Doe</name>
                </user>
            </child3>
        </child2>
    <child1>
</main>

现在,我需要使用 Jackson 从这个 XML 构造用户对象。基本上我对 child3 元素很感兴趣。我不想创建 main、child1、child2 类。直接我想从child3读取。我怎样才能做到这一点?请帮忙

标签: spring-bootjacksondeserialization

解决方案


You can probably try reading them in MAP class like below,

 XmlMapper xmlMapper = new XmlMapper();
 Map<String,Object> map = xmlMapper.readValue(xml, Map.class);
 Map<String,Object> child1 = (Map<String, Object>) map.get("child1");
 Map<String,Object> child2 = (Map<String, Object>) child1.get("child2");
 Map<String,Object> child3 = (Map<String, Object>) child2.get("child3");

Child3 Map will only contain the data. You will also need to import below maven library to use XMLMapper

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.11.1</version>
</dependency>

Another way would be to use JSONNode and then finally deserialize it into child3 object. as shown below,

XmlMapper xmlMapper = new XmlMapper();
ObjectMapper jsonMapper = new ObjectMapper(); //To convert JSON to object
JsonNode  map = xmlMapper.readValue(xml, JsonNode.class);
JsonNode child1 = map.get("child1");
JsonNode child2 = child1.get("child2");
JsonNode child3 = child2.get("child3");
Child3 child3 = jsonMapper.readValue(child3.toString(),Child3.class);

推荐阅读