在JAXB(Java Architecture for XML Binding)中使用HashMap属性,需要遵循以下步骤:
import java.util.HashMap;
import java.util.Map;
public class MyClass {
private Map<String, String> attributes = new HashMap<>();
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
}
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class MyClass {
@XmlJavaTypeAdapter(HashMapAdapter.class)
private Map<String, String> attributes = new HashMap<>();
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class HashMapAdapter extends XmlAdapter<HashMapAdapter.MyMapType[], Map<String, String>> {
public static class MyMapType {
public String key;
public String value;
}
@Override
public MyMapType[] marshal(Map<String, String> map) throws Exception {
MyMapType[] items = new MyMapType[map.size()];
int i = 0;
for (Entry<String, String> entry : map.entrySet()) {
MyMapType item = new MyMapType();
item.key = entry.getKey();
item.value = entry.getValue();
items[i] = item;
i++;
}
return items;
}
@Override
public Map<String, String> unmarshal(MyMapType[] items) throws Exception {
Map<String, String> map = new HashMap<>();
for (MyMapType item : items) {
map.put(item.key, item.value);
}
return map;
}
}
推荐的腾讯云相关产品:
产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云