Search code examples
javaxmljacksondeserializationpojo

Jackson: deserialize custom attributes in XML to POJO


I would like to deserialize and map to class following values by name attribute. This is piece of my XML file.

                <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>

And This is piece of my pojo class

@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;
}

}

Do you know ho to properly read values from those attribues by name ? Currently im receiving null


Solution

  • I am not sure what the result is supposed to look like, but if you want to parse the complete xml into matching objects they would look like this:

    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;
    
        ...
    }
    

    Note that the localName="name3" from your question is not referring to a property at all.