Skip to content
Advertisement

Get Jackson XMLMapper to set root element name in code

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.

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement