Mapping java.util.Map to XML using JAXB

One of the thing that can be a bit tricky when using JAXB is to map a java.util.Map to XML. In this example we have a provider object. The provider has a name and a map containing properties.

Below is the provider XML document:

And then the Provider class:

JAXB sees the properties object in the XML document as a list of property entries. Therefore we need to transform the list into a map. To do this we need three supporting classes. The first one is the class containing the entry, or property:

Next we need the class that contains the list of entries, or the properties:

To transform the list into a map we need an XmlAdapter. An XmlAdapter is a class that instructs JAXB on how to marshal and unmarshal an object that does not conform to the JAXB standard. This could for example be a class without a public no args constructor, or as in our case the provider properties map:

Now what is left is to tell JAXB to use the XmlAdaptor when handling the properties field. To do this we use the @XmlJavaTypeAdapter annotation. Below is the fully annotated Provider class:

  • Quentinjs

    Will this convert XML to MAP as well?

  • Yes, just as all mappings in JAXB it will go both ways.

  • Homer

    It was very usuful to me but it's missing the final test with the main() part. thanks!

  • You will have to look at the JAXB documentation for how to wire up JAXB with a main() method. This article assumes that you already have some basic knowledge of JAXB.

  • Sergey

    Where does PropertyEntry come from?

  • I think that's a type on my part when I moved to Github Gists. It should be Property. And it should be fixed now.

    Thanks for spotting 🙂

  • karthik

    change the end tag in the xml

  • marianoncho

    I don't want the tag in my xml document. How should I do this?

  • That, I don't know I'm afraid. It is customary to organise the xml in such a manner and I think it's easier to work with it when it's organised like that.

    If you find a way to do it please share with us.