Search code examples
javajacksonjackson2jackson-dataformat-xmljackson-annotations

With JacksonXML I'd like to deserialize unpredetermined list of elements to the Map<String,String>. What kind of annotations I can use for that?


I have xml tag with attribute names which are not restricted to some specific values,like that:

<to amount="345.00" service="service" purpose="rent" account="381"/>

With JacksonXML I'd like to deserialize that elements to the Map<String,String>. What kind of annotations I can use for that?


Solution

  • I used the @JsonAnySetter annotation to deserialize the XML element to a Map<String, String>. Here's an example:

    public class MyElement {
        private Map<String, String> attributes = new HashMap<>();
    
        @JsonAnySetter
        public void addAttribute(String name, String value) {
            attributes.put(name, value);
        }
    
        public Map<String, String> getAttributes() {
            return attributes;
        }
    }
    

    In this example, the addAttribute method is annotated with @JsonAnySetter, which tells JacksonXML to call this method for any XML attribute that doesn't have a corresponding property in the MyElement class. The method then adds the attribute name and value to the attributes map.

    To deserialize the XML element to a MyElement object, you can use the XmlMapper class:

    String xml = "<to amount=\"345.00\" service=\"service\" purpose=\"rent\" account=\"381\"/>";
    XmlMapper xmlMapper = new XmlMapper();
    MyElement element = xmlMapper.readValue(xml, MyElement.class);
    

    After deserialization, the attributes map in the MyElement object will contain the attribute names and values from the XML element.