Get Jackson XMLMapper to set the root element name in code

How do I get XMLMapper from Jackson to set the name of the root xml element during serialization?

There is an annotation to do this if you serialize pojo: @XmlRootElement (name = "blah"). But I am serializing a common Java class, LinkedHashMap, so I cannot use annotation.

There is probably some kind of switch to set it. Expressing Jackson's code, I see a class called SerializationConfig.withRootName (), but I don't know how to use it.

+4
source share
1 answer

XML ObjectWriter.withRootName. :

public class JacksonXmlMapper {

    public static void main(String[] args) throws JsonProcessingException {

        Map<String, Object> map = new LinkedHashMap<String, Object>();
        map.put("field1", "v1");
        map.put("field2", 10);
        XmlMapper mapper = new XmlMapper();
        System.out.println(mapper
                .writer()
                .withRootName("root")
                .writeValueAsString(map));

    }
}

:

<root><field1>v1</field1><field2>10</field2></root>
+13

Source: https://habr.com/ru/post/1543481/


All Articles