HashMap
我想使用 .xml 来调整字段的 XML 表示XmlAdapter
。我用一个ArrayList
来做到这一点。但是,在编组时ArrayList
根本没有编组。这是为什么?
编码
@XmlRootElement
public class Foo {
private HashMap<String, String> hashMap;
public Foo() {
this.hashMap = new HashMap<String, String>();
}
@XmlJavaTypeAdapter(HashMapAdapter.class)
public HashMap<String, String> getHashmap() {
return hashMap;
}
public void setHashmap(HashMap<String, String> hashMap) {
this.hashMap = hashMap;
}
}
public final class HashMapAdapter extends XmlAdapter<ArrayList<HashMapEntry>, HashMap<String, String>> {
@Override
public ArrayList<HashMapEntry> marshal(HashMap<String, String> arg0) throws Exception {
ArrayList<HashMapEntry> result = new ArrayList<HashMapEntry>();
for(Entry<String, String> entry : arg0.entrySet())
result.add(new HashMapEntry(entry.getKey(), entry.getValue()));
return result;
}
@Override
public HashMap<String, String> unmarshal(ArrayList<HashMapEntry> arg0) throws Exception {
HashMap<String, String> result = new HashMap<String, String>();
for(HashMapEntry entry : arg0)
result.put(entry.key, entry.value);
return result;
}
}
public class HashMapEntry {
@XmlElement
public String key;
@XmlValue
public String value;
public HashMapEntry() {
}
public HashMapEntry(String key, String value) {
this.key = key;
this.value = value;
}
}
结果
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><foo><hashmap/></foo>