Home >Java >javaTutorial >How to Marshal a Map into `value` Elements with JAXB?

How to Marshal a Map into `value` Elements with JAXB?

Susan Sarandon
Susan SarandonOriginal
2024-11-13 04:25:02339browse

How to Marshal a Map into `value` Elements with JAXB?

Marshalling Map into value with JAXB

Problem

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>

Solution

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 , use a MapAdapter that converts the Map to an array of MapElements:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn