Mapping xml to Java POJOs with Jackson

Jackson is typically used for Json serialization and deserialization, but with the jackson-dataformat-xml dependency you can also use Jackson to easily map to/from XML too.

Maven dependencies:

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

If you have additional elements and attributes on elements that you’re not interested in, similar to Json, just add the ignore annotation at class level:

@JsonIgnoreProperties(ignoreUnknown = true)

In some XML docs you can have elements with the same name at the same level without a parent to exclusively group those elements. For example you can have xml that looks like this with a grouping:

<example>
    <name>example1</name>
    <items>
        <item>1</item>
        <item>2</item>
    </items>
</example>

This would be automatically handled by Jackson if your POJO class has a list of Item called items:

private List<Item> items;

but sometimes you’ll have a doc that looks like this:

<example>
    <name>example1</name>
    <item>1</item>
    <item>2</item>
</example>

To map this you need to use this annotation:

@JacksonXmlElementWrapper(useWrapping = false)
private List<Item> item;

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.