Home > Java > javaTutorial > body text

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

Susan Sarandon
Release: 2024-11-13 04:25:02
Original
287 people have browsed it

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>
Copy after login

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>
Copy after login

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;
Copy after login

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;
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template