Jackson:将XML中的自定义属性反序列化为POJO

时间:2020-03-27 14:29:21

标签: java xml jackson deserialization pojo

我想反序列化并通过name属性映射到以下值的类。 这是我的XML文件。

                <custom-attributes>
                    <custom-attribute name="Name1" dt:dt="string">VALUE</custom-attribute>
                    <custom-attribute name="Name2" dt:dt="string"> 
                        <value>1111</value>
                        <value>1111</value>
                        <value>1111</value>
                    </custom-attribute>
                    <custom-attribute name="Name3" dt:dt="string">VALUE2</custom-attribute>
                    <custom-attribute dt:dt="boolean" name="Name3">VALUE3</custom-attribute> 
                    <custom-attribute dt:dt="boolean" name="Name4">VALUE4</custom-attribute>
                </custom-attributes>

这是我的pojo课的一部分

@JsonIgnoreProperties(ignoreUnknown = true)
public class CustomAttributes {

     @JacksonXmlProperty(localName="name3", isAttribute = true)
     private String roleID;

     public String getRoleID() {
           return roleID;
      }

     public void setRoleID(String roleID) {
          this.roleID = roleID;
}

}

您知道如何正确地从名称中读取值吗?目前我收到null

1 个答案:

答案 0 :(得分:1)

我不确定结果应该是什么样子,但是如果您愿意 将完整的xml解析为匹配的对象,它们看起来像这样:

public class CustomAttributeList {

    @JacksonXmlProperty(localName = "custom-attributes")
    private List<CustomAttributes> list;

    ...
}
@JacksonXmlRootElement(localName = "custom-attribute")
public class CustomAttributes {

    // the name attribute
    @JacksonXmlProperty
    private String name;

    // the datatype from the dt:dt field
    @JacksonXmlProperty(namespace = "dt")
    private String dt;

    // the content between the tags (if available)
    @JacksonXmlText
    private String content;

    // the values in the content (if available)
    @JacksonXmlProperty(localName = "value")
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<String> values;

    ...
}

请注意,您问题中的localName="name3"根本不是在指财产。

相关问题