【问题标题】:Serialize XML element having property named value using Jackson使用 Jackson 序列化具有名为 value 的属性的 XML 元素
【发布时间】:2019-07-02 13:30:03
【问题描述】:

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

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

如何正确创建带有杰克逊注解的 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,因此更改它对我不起作用。

【问题讨论】:

    标签: java xml-parsing jackson jaxb jackson2


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 2018-01-04
      • 2012-05-09
      • 2015-09-24
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多