7

How do I get Jackson's XMLMapper to set the name of the root xml element when serializing?

There's an annotation to do it, if you're serializing a pojo: @XmlRootElement(name="blah"). But I'm serializing a generic Java class, LinkedHashMap, so I can't use an annotation.

There's probably some switch somewhere to set it. Poking around in Jackson code, I see a class named SerializationConfig.withRootName(), but I've no clue how to use it.

ccleve
  • 15,239
  • 27
  • 91
  • 157

2 Answers2

24

You can override the root element of the XML output using the ObjectWriter.withRootName method. Here is example:

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

    }
}

Output:

<root><field1>v1</field1><field2>10</field2></root>
Alexey Gavrilov
  • 10,593
  • 2
  • 38
  • 48
3

You can use this annotation: @JsonRootName("MyCustomRootName")

IPP Nerd
  • 992
  • 9
  • 25