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 un-marshal 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: