Home >Java >javaTutorial >How to Marshal a Map into `value` Elements with JAXB?
Maps are commonly marshaled into XML structures like:
<map> <entry> <key>KEY</key> <value>VALUE</value> </entry> <entry> <key>KEY2</key> <value>VALUE2</value> </entry> ... </map>
However, sometimes it is desirable to generate XML where the key becomes the element name and the value becomes its content:
<map> <KEY>VALUE</KEY> <KEY2>VALUE2</KEY2> ... </map>
Option 1: Dynamically Named XML Elements
Using dynamic attribute names is not recommended, as it violates XML schema and interface contract principles.
Option 2: Enumerated Key Type
To maintain a strict interface contract, use an enumerated key type for the map:
public enum KeyType { KEY, KEY2; } @XmlJavaTypeAdapter(MapAdapter.class) Map<KeyType, String> mapProperty;
Option 3: Simplified Marshaling
To simplify the default marshaling structure into
class MapElements { @XmlAttribute public String key; @XmlAttribute public String value; // Required by JAXB private MapElements() {} public MapElements(String key, String value) { this.key = key; this.value = value; } } class MapAdapter extends XmlAdapter<MapElements[], Map<String, String>> { @Override public MapElements[] marshal(Map<String, String> arg0) { MapElements[] mapElements = new MapElements[arg0.size()]; int i = 0; for (Entry<String, String> entry : arg0.entrySet()) { mapElements[i++] = new MapElements(entry.getKey(), entry.getValue()); } return mapElements; } @Override public Map<String, String> unmarshal(MapElements[] arg0) { Map<String, String> r = new TreeMap<>(); for (MapElements mapelement : arg0) { r.put(mapelement.key, mapelement.value); } return r; } }
The above is the detailed content of How to Marshal a Map into `value` Elements with JAXB?. For more information, please follow other related articles on the PHP Chinese website!