使用 Jackson 序列化具有 属性 命名值的 XML 元素

Serialize XML element having property named value using Jackson

我正在尝试 deserialize/serialize xml 满足以下元素。

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

如何正确创建 java 带有 jackson 注释的 bean 以正确解析它。我已经尝试使用 JAXB 注释,但 jackson 没有说它不需要 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,因此更改它对我不起作用。

这里你需要的是添加@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);