Hallo,
hab schon überall gesucht und leider nichts passendes gefunden. Und zwar möchte ich eine HashMap per marshalling in xml umwandeln. Folgender Code macht das auch schon ganz gut, nur leider stört mich das "map"-Element.
Das Ergebnis ist:
[XML]
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<map>
<entry key="key2">value2</entry>
<entry key="key1">value1</entry>
</map>
</root>
[/XML]
Wie gesagt, mein Ziel ist es das ganze ohne "map"-Element bekommen, also:
[XML]
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<entry key="key2">value2</entry>
<entry key="key1">value1</entry>
</root>
[/XML]
Habs schon ewig versucht, hoffe irgendwer kann mir helfen.
Vielen Dank schonmal im Voraus
hab schon überall gesucht und leider nichts passendes gefunden. Und zwar möchte ich eine HashMap per marshalling in xml umwandeln. Folgender Code macht das auch schon ganz gut, nur leider stört mich das "map"-Element.
Java:
@XmlRootElement(name ="root")
public class HashMapTest {
@XmlJavaTypeAdapter(HashMapAdapter.class)
public Map<String, String> map = new HashMap<String, String>();
public static class HashMapAdapter extends XmlAdapter<MapType, Map<String, String>> {
@Override
public MapType marshal(Map<String, String> map) {
MapType mapType = new MapType();
for (Entry<String, String> entry : map.entrySet()) {
MapEntry mapEntry = new MapEntry();
mapEntry.key = entry.getKey();
mapEntry.value = entry.getValue();
mapType.entryList.add(mapEntry);
}
return mapType;
}
@Override
public Map<String, String> unmarshal(MapType type) throws Exception {
Map<String, String> map = new HashMap<String, String>();
for (MapEntry entry : type.entryList) {
map.put(entry.key, entry.value);
}
return map;
}
}
public static class MapType {
@XmlElement(name ="entry")
public List<MapEntry> entryList = new ArrayList<MapEntry>();
}
public static class MapEntry {
@XmlAttribute
public String key;
@XmlValue
public String value;
}
public static void main(String args[]) throws Exception {
HashMapTest mp = new HashMapTest();
mp.map.put("key1", "value1");
mp.map.put("key2", "value2");
JAXBContext jc = JAXBContext.newInstance(HashMapTest.class);
Marshaller m = jc.createMarshaller();
m.marshal(mp, System.out);
}
}
Das Ergebnis ist:
[XML]
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<map>
<entry key="key2">value2</entry>
<entry key="key1">value1</entry>
</map>
</root>
[/XML]
Wie gesagt, mein Ziel ist es das ganze ohne "map"-Element bekommen, also:
[XML]
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<entry key="key2">value2</entry>
<entry key="key1">value1</entry>
</root>
[/XML]
Habs schon ewig versucht, hoffe irgendwer kann mir helfen.
Vielen Dank schonmal im Voraus