Deserialising JSON or XML to a Map using Java

Well, here’s a thing.  Imagine you have some XML or JSON that looks like a map, only you don’t know the names or number of the properties in advance.  For example:

Or some JSON that looks like this:

How can you do it?  Using Jackson @JsonAnyGetter and @JsonAnySetter . All you need is the XML root element name (if you’re using XML).  The XmlMapper also forces us to wrap the Map in a POJO, with JSON it’s possible to simply read into a Map instance.  Here’s a JUnit test showing how it can be done for both JSON and XML using the same POJO:

Easy eh?

Written by Tom

4 Comments

Chase

Thank you for the post. How might you modify this code in order to map an XML document that has more depth?
i.e.


subB1
subB2

c

When attempting to increase the depth of the XML, this exception is thrown:
com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)

Thanks again; good blog.

Reply
Jasbir kaur

I am getting Unrecognized field exception if the map used is of some pojo CLASS

Reply

Leave a Reply to maderlevap Cancel reply