使用Jackson序列化具有名为value的属性的XML元素

时间:2019-02-08 10:14:29

标签: java xml-parsing jackson jaxb jackson2

我正在尝试使用下面的元素反序列化/序列化xml内容。

<?xml version="1.0" encoding="utf-8" ?>
<confirmationConditions>
    <condition type="NM-GD" value="something">no modification of guest details</condition>
</confirmationConditions>

如何正确创建带有jackson批注的Java bean来正确解析它。我已经尝试过使用JAXB批注,而杰克逊却说不必必须value个字段。在下面的Java Bean中,出现以下错误。

public class Condition
{
    @JacksonXmlProperty( isAttribute = true, localName = "type" )
    private String type;
    @JacksonXmlProperty( isAttribute = true, localName = "value" )
    private String value;
    private String text;
}

错误

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "" (class Condition), not marked as ignorable (3 known properties: "value", "type", "text"])
 at [Source: (File); line: 3, column: 73] (through reference chain: ConfirmationConditions["condition"]->Condition[""])

基本上我想要的是将元素内容映射到text字段。我无法控制xml,因此更改它对我不起作用。

1 个答案:

答案 0 :(得分:2)

您需要在这里添加@JacksonXmlText

class Condition {
    @JacksonXmlProperty(isAttribute = true)
    private String type;
    @JacksonXmlProperty(isAttribute = true)
    private String value;
    @JacksonXmlText
    private String text;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

并以这种方式解析:

    JacksonXmlModule module = new JacksonXmlModule();
    module.setDefaultUseWrapper(false);
    XmlMapper xmlMapper = new XmlMapper(module);

    xmlMapper.readValue(
            "<condition type=\"NM-GD\" value=\"something\">no modification of guest details</condition>", Condition.class);