JAXB: how to marshall map into <key>value</key> JAXB: how to marshall map into <key>value</key> xml xml

JAXB: how to marshall map into <key>value</key>


There may be a valid reason why you want to do this, but generating this kind of XML is generally best avoided. Why? Because it means that the XML elements of your map are dependent on the runtime contents of your map. And since XML is usually used as an external interface or interface layer this is not desirable. Let me explain.

The Xml Schema (xsd) defines the interface contract of your XML documents. In addition to being able to generate code from the XSD, JAXB can also generate the XML schema for you from the code. This allows you to restrict the data exchanged over the interface to the pre-agreed structures defined in the XSD.

In the default case for a Map<String, String>, the generated XSD will restrict the map element to contain multiple entry elements each of which must contain one xs:string key and one xs:string value. That's a pretty clear interface contract.

What you describe is that you want the xml map to contain elements whose name will be determined by the content of the map at runtime. Then the generated XSD can only specify that the map must contain a list of elements whose type is unknown at compile time. This is something that you should generally avoid when defining an interface contract.

To achieve a strict contract in this case, you should use an enumerated type as the key of the map instead of a String. E.g.

public enum KeyType { KEY, KEY2;}@XmlJavaTypeAdapter(MapAdapter.class)Map<KeyType , String> mapProperty;

That way the keys which you want to become elements in XML are known at compile time so JAXB should be able to generate a schema that would restrict the elements of map to elements using one of the predefined keys KEY or KEY2.

On the other hand, if you wish to simplify the default generated structure

<map>    <entry>        <key>KEY</key>        <value>VALUE</value>    </entry>    <entry>        <key>KEY2</key>        <value>VALUE2</value>    </entry></map>

To something simpler like this

<map>    <item key="KEY" value="VALUE"/>    <item key="KEY2" value="VALUE2"/></map>

You can use a MapAdapter that converts the Map to an array of MapElements as follows:

class MapElements {    @XmlAttribute    public String key;    @XmlAttribute    public String value;    private MapElements() {    } //Required by JAXB    public MapElements(String key, String value) {        this.key = key;        this.value = value;    }}public class MapAdapter extends XmlAdapter<MapElements[], Map<String, String>> {    public MapAdapter() {    }    public MapElements[] marshal(Map<String, String> arg0) throws Exception {        MapElements[] mapElements = new MapElements[arg0.size()];        int i = 0;        for (Map.Entry<String, String> entry : arg0.entrySet())            mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());        return mapElements;    }    public Map<String, String> unmarshal(MapElements[] arg0) throws Exception {        Map<String, String> r = new TreeMap<String, String>();        for (MapElements mapelement : arg0)            r.put(mapelement.key, mapelement.value);        return r;    }}


the code provided didn't work for me.I found another way to Map :

MapElements :

package com.cellfish.mediadb.rest.lucene;import javax.xml.bind.annotation.XmlElement;class MapElements{  @XmlElement public String  key;  @XmlElement public Integer value;  private MapElements() {} //Required by JAXB  public MapElements(String key, Integer value)  {    this.key   = key;    this.value = value;  }}

MapAdapter :

import java.util.HashMap;import java.util.Map;import javax.xml.bind.annotation.adapters.XmlAdapter;class MapAdapter extends XmlAdapter<MapElements[], Map<String, Integer>> {    public MapElements[] marshal(Map<String, Integer> arg0) throws Exception {        MapElements[] mapElements = new MapElements[arg0.size()];        int i = 0;        for (Map.Entry<String, Integer> entry : arg0.entrySet())            mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());        return mapElements;    }    public Map<String, Integer> unmarshal(MapElements[] arg0) throws Exception {        Map<String, Integer> r = new HashMap<String, Integer>();        for (MapElements mapelement : arg0)            r.put(mapelement.key, mapelement.value);        return r;    }}

The rootElement :

import java.util.HashMap;import java.util.Map;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;@XmlRootElementpublic class Root {    private Map<String, Integer> mapProperty;    public Root() {        mapProperty = new HashMap<String, Integer>();    }    @XmlJavaTypeAdapter(MapAdapter.class)    public Map<String, Integer> getMapProperty() {        return mapProperty;    }    public void setMapProperty(Map<String, Integer> map) {        this.mapProperty = map;    }}

I found the code in this website : http://www.developpez.net/forums/d972324/java/general-java/xml/hashmap-jaxb/


I'm still working on a better solution but using MOXy JAXB, I've been able to handle the following XML:

<?xml version="1.0" encoding="UTF-8"?><root>   <mapProperty>      <map>         <key>value</key>         <key2>value2</key2>      </map>   </mapProperty></root>

You need to use an @XmlJavaTypeAdapter on your Map property:

import java.util.HashMap;import java.util.Map;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;@XmlRootElementpublic class Root {    private Map<String, String> mapProperty;    public Root() {        mapProperty = new HashMap<String, String>();    }    @XmlJavaTypeAdapter(MapAdapter.class)    public Map<String, String> getMapProperty() {        return mapProperty;    }    public void setMapProperty(Map<String, String> map) {        this.mapProperty = map;    }}

The implementation of the XmlAdapter is as follows:

import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import javax.xml.bind.annotation.adapters.XmlAdapter;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class MapAdapter extends XmlAdapter<AdaptedMap, Map<String, String>> {    @Override    public AdaptedMap marshal(Map<String, String> map) throws Exception {        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();        DocumentBuilder db = dbf.newDocumentBuilder();        Document document = db.newDocument();        Element rootElement = document.createElement("map");        document.appendChild(rootElement);        for(Entry<String,String> entry : map.entrySet()) {            Element mapElement = document.createElement(entry.getKey());            mapElement.setTextContent(entry.getValue());            rootElement.appendChild(mapElement);        }        AdaptedMap adaptedMap = new AdaptedMap();        adaptedMap.setValue(document);        return adaptedMap;    }    @Override    public Map<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {        Map<String, String> map = new HashMap<String, String>();        Element rootElement = (Element) adaptedMap.getValue();        NodeList childNodes = rootElement.getChildNodes();        for(int x=0,size=childNodes.getLength(); x<size; x++) {            Node childNode = childNodes.item(x);            if(childNode.getNodeType() == Node.ELEMENT_NODE) {                map.put(childNode.getLocalName(), childNode.getTextContent());            }        }        return map;    }}

The AdpatedMap class is where all the magic happens, we will use a DOM to represent the content. We will trick JAXB intro dealing with a DOM through the combination of @XmlAnyElement and a property of type Object:

import javax.xml.bind.annotation.XmlAnyElement;public class AdaptedMap {    private Object value;    @XmlAnyElement    public Object getValue() {        return value;    }    public void setValue(Object value) {        this.value = value;    }}

This solution requires the MOXy JAXB implementation. You can configure the JAXB runtime to use the MOXy implementation by adding a file named jaxb.properties in with your model classes with the following entry:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

The following demo code can be used to verify the code:

import java.io.File;import javax.xml.bind.JAXBContext;import javax.xml.bind.Marshaller;import javax.xml.bind.Unmarshaller;public class Demo {    public static void main(String[] args) throws Exception {        JAXBContext jc = JAXBContext.newInstance(Root.class);        Unmarshaller unmarshaller = jc.createUnmarshaller();        Root root = (Root) unmarshaller.unmarshal(new File("src/forum74/input.xml"));        Marshaller marshaller = jc.createMarshaller();        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);        marshaller.marshal(root, System.out);    }}