我有这个对象,作为复杂对象的节点:
公共类Parameter实现Serialized {
@XmlElement(name = "Key")
protected String key;
@XmlElement(name = "Value")
protected Object value;
}
属性“Value”可以是一个字符串,有效地使参数成为一个映射
例如,以下两个 XML 片段均有效:
<Parameter>
<Key>MyKey</Key>
<Value>MyValue</MyValue>
</Parameter>
<Parameter>
<Key>Key1</Key>
<Value>
<Key>Key2</Key>
<Value>
<Key>Key3</Key>
<Value>ValueInString1</Value>
</Value>
<Value>
<Key>Key4</Key>
<Value>ValueInString2</Value>
</Value>
</Value>
我正在寻找一种实现可以处理此问题的 XMLAdapter 的方法。 两个主要想法是:
想法 #1 停留在如何整理键值对列表上 想法 #2 继续,如果值是参数,如何调用 Parameter.class 的通用编组器
您可以使用 MapAdapter 将 Map 转换为 MapElements 数组,如下所示:
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;
}
}