How to Marshal and Unmarshal XML with Jackson

Learn to convert a Java object to XML or from XML document to Java object using Jackson library. Jackson is an excellent solution if we are looking to convert a Java object to XML without JAXB.

Just to re-iterate, marshalling is the process of transforming Java objects into XML documents. Unmarshalling is the process of reading XML documents into Java objects.

1. Setting Up Jackson

Include the latest version of jackson-dataformat-xml from Maven repo.

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
  <version>2.13.0</version>
</dependency>

After importing Jackson, we can start using its XmlMapper class for reading and writing XML.

XmlMapper xmlMapper = new XmlMapper();

//POJO -> XML
String xml = xmlMapper.writeValueAsString(pojo);

//XML -> POJO
Class pojo = xmlMapper.readValue(xml);

See Also: Jackson – Marshal and Unmarshal Java Objects to JSON

2. XMLMapper class

XMLMapper is the most important class for handling XML documents with Jackson. It provides methods to read and write XML to the following sources and targets.

  • String
  • Byte[]
  • java.io.File
  • java.io.InputStream and java.io.OutputStream
  • java.io.Reader and java.io.Writer
//Write to String
String xml = xmlMapper.writeValueAsString(pojo);
//Write to file
xmlMapper.writeValue(new File("data.xml"), pojo);

//Read from String
Pojo pojo = xmlMapper.readValue(xmlString, Pojo.class);
//Read from File
Pojo pojo = xmlMapper.readValue(new File("data.xml"), Pojo.class);

Using its enable() and disable() methods, we can trun on and off various behaviors specific to XML marshalling and unmarshalling such as:

  • Handling null and empty values.
  • Handling date and time values
  • Handling enum values
  • Handling elements ordering
  • Pretty printing, etc.
xmlMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
xmlMapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

xmlMapper.disable(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
xmlMapper.disable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

3. Customing Conversion with Jackson Annotations

Let us take an example of Article class. We will first check the default XML generated for its instance, and then we will customize the XML by applying annotations to the Article class.

class Article {

	private Long id;
	private String title;
	private List<String> tags;

	//Constructors, getters, setters and toString method
}

In the following examples, we use the same code for marshalling.

XmlMapper xmlMapper = new XmlMapper();
Article article = new Article(1L, "Test Title", List.of("Tag1", "Tag2"));

String articleXml = xmlMapper.writeValueAsString(article);
System.out.println(articleXml);

3.1. Default XML without Annotations

The default XML takes the XML tag names from class and member field names, including capitalization.

<Article><id>1</id><title>Test Title</title><tags><tags>Tag1</tags><tags>Tag2</tags></tags></Article>

3.2. Root Element’s Name

Use @JacksonXmlRootElement to customize the name of the root element.

@JacksonXmlRootElement(localName = "article")
class Article { ... }

Check out the generated XML putout.

<article>....</article>

3.3. Making XML Attribute

Use @JacksonXmlProperty(isAttribute = true) to mark a field as an XML attribute rather than an XML element.

@JacksonXmlRootElement(localName = "article")
class Article {

	@JacksonXmlProperty(isAttribute = true)
	private Long id;

	...
}

Check out the generated XML putout.

<article id="1">...</article>

3.4. Customizing Lists

Use @JacksonXmlElementWrapper to on a List type to create the list wrapper element. The individual elements can be customized using the @JacksonXmlProperty.

@JacksonXmlRootElement(localName = "article")
class Article {
	@JacksonXmlProperty(isAttribute = true)
	private Long id;
	private String title;

	@JacksonXmlElementWrapper(localName = "tags")
	@JacksonXmlProperty(localName = "tag")
	private List<String> tags;
	...
}

Check out the generated XML putout.

<article id="1"><title>Test Title</title><tags><tag>Tag1</tag><tag>Tag2</tag></tags></article>

4. Pretty Printing the XML Output

If we want to pretty print the XML output then we can turn on the SerializationFeature.INDENT_OUTPUT on XMLMapper.

XmlMapper xmlMapper = new XmlMapper();
xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);

Article article = new Article(1L, "Test Title", List.of("Tag1", "Tag2"));

String articleXml = xmlMapper.writeValueAsString(article);
System.out.println(articleXml);

It will print the following XML.

<article id="1">
  <title>Test Title</title>
  <tags>
    <tag>Tag1</tag>
    <tag>Tag2</tag>
  </tags>
</article>

5. Conclusion

This Jackson tutorial taught us to serialize and deserialize the Java Object to XML document with simple and easy examples. We learned to customize and use the XmlMapper class for controlling the specific behavior during the conversion processes.

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode