Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 977
ccleve Avatar asked Jun 05 '14 21:06

ccleve


People also ask

Does Jackson use JAXB?

With XML module Jackson provides support for JAXB (javax. xml. bind) annotations as an alternative to native Jackson annotations, so it is possible to reuse existing data beans that are created with JAXB to read and write XMLs.

Can Jackson parse XML?

Jackson is a library for handling JSON in Java systems and now has support for XML from version 2. DOM4J is a memory-efficient library for parsing XML, XPath, and XSLT (eXtensible Stylesheet Language). JDom which is an XML parsing library with support for XPath and XSLT.

What is Jackson Dataformat XML?

Jackson XML is a Data Format which uses the Jackson library with the XMLMapper extension to unmarshal an XML payload into Java objects or to marshal Java objects into an XML payload.

What is JacksonXmlElementWrapper?

JacksonXmlElementWrapper. The @JacksonXmlElementWrapper annotation is used to override the default setting from setDefaultUseWrapper – as seen above. This can ensure that a collection either does or does not use a wrapper element, and can control what the wrapper element uses for namespace and local name.


2 Answers

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>
like image 195
Alexey Gavrilov Avatar answered Oct 09 '22 18:10

Alexey Gavrilov


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

like image 29
IPP Nerd Avatar answered Oct 09 '22 19:10

IPP Nerd