jackson xmlwrapper无法将此xml反序列化为pojo?

46scxncf  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(522)

考虑下面给出的XML:

<?xml version="1.0"?>
<Records>
    <Record>
        <Prop name="commerce">sku1</Prop>
        <Prop name="commerce">sku2</Prop>
        <Prop name="commerce">sku3</Prop>
        <Prop name="commerce">sku4</Prop>
    </Record>
    <Record>
        <Prop name="commerce">sku10</Prop>
        <Prop name="commerce">sku20</Prop>
        <Prop name="commerce">sku30</Prop>
        <Prop name="commerce">sku40</Prop>
    </Record>
</Records>

现在考虑我创建的这些POJO(删除GETER和SETTER以简洁)。

public class Records {
    private List<Record> records;
}

public class Record {
    private List<Prop> props;
}

public class Prop {
    // I want to capture name attribute
    private String name;
    // But I also want to capture what comes inside Prop element as well. This would then have values like sku1, sku2 etc
    private String text;
}

现在我有了这样使用xmlwrapper的代码。

File file = ResourceUtils.getFile("classpath:sample.xml"); // the above XML is sample.xml
XmlMapper xmlMapper = XmlMapper.builder().build();
Records records = xmlMapper.readValue(file, Records.class); // this line is failing

但是我遇到了这样的错误

Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Record" (class com.example.demo.model.xml.Records), not marked as ignorable (one known property: "records"])
guz6ccqo

guz6ccqo1#

你必须把这两个词结合起来 @JacksonXmlProperty 使用 @JacksonXmlElementWrapper 注解,指示要与 Collection :在本例中为可选属性 useWrapping 设置为false以显式禁用 Package :

public class Records {
    @JacksonXmlProperty(localName = "Record")
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<Record> records;
}

public class Record {
    @JacksonXmlProperty(localName = "Prop")
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<Prop> props;
}

public class Prop {
    //<Prop name="commerce">sku1</Prop> name is an attribute with value commerce
    @JacksonXmlProperty(localName= "name", isAttribute = true)
    private String name;

    //<Prop name="commerce">sku1</Prop> sku1 is the text inside the Prop tags
    @JacksonXmlText
    private String text;
}
5w9g7ksd

5w9g7ksd2#

即使没有xml注解(在大多数情况下),这个解决方案似乎也适合我。为子孙后代发帖。
步骤1:禁用 Package 。

File file = ResourceUtils.getFile("classpath:sample.xml"); 
XmlMapper xmlMapper = XmlMapper.builder().defaultUseWrapper(false).build();
Records records = xmlMapper.readValue(file, Records.class);

步骤2:使用jsonproperty注解更新POJO(唯一的例外是使用@jacksonxmltext获取内部值。注意:为了简洁起见,删除setter和getter。

public class Records {
    @JsonProperty("Record")
    private List<Record> records;
}

public class Record {
    @JsonProperty("Prop")
    private List<Prop> props;
}

public class Prop {
    @JsonProperty("name")
    private String name;

    @JacksonXmlText
    private String text;
}

以上这些对我很有用。

相关问题