[英]How can we convert nested multi level Map to XML in Java?
I tried to do in way that is in below link 我试图用下面的链接来做
How to convert XML to java.util.Map and vice versa 如何将XML转换为java.util.Map,反之亦然
But this is not going all over the Map. 但这并没有遍及整个地图。
Please Advise! 请指教!
You need to use XmlAdapter
and override marshal
and unmarshal
method. 您需要使用
XmlAdapter
并覆盖marshal
和unmarshal
方法。 Here is example code show how to convert Map<String,Boolean>
to XML and vice versa: 以下示例代码显示了如何将
Map<String,Boolean>
转换为XML,反之亦然:
public class MapAdapter extends XmlAdapter<MapElements[], Map<String, Boolean>> {
public MapAdapter() {
}
@Override
public MapElements[] marshal(Map<String, Boolean> v) throws Exception {
MapElements[] elements = new MapElements[v.size()];
int i = 0;
for (Map.Entry<String, Boolean> entry : v.entrySet()) {
elements[i++] = new MapElements(entry.getKey(), entry.getValue());
}
return elements;
}
@Override
public Map<String, Boolean> unmarshal(MapElements[] v) throws Exception {
Map<String, Boolean> map = new HashMap<>();
for (MapElements element : v) {
map.put(element.key, element.value);
}
return map;
}
}
class MapElements {
@XmlElement
public String key;
@XmlElement
public Boolean value;
public MapElements() {
}
public MapElements(String key, Boolean value) {
this.key = key;
this.value = value;
}
}
and use @XmlJavaTypeAdapter
annotation on Map<String,Boolean>
field as follow 并在
Map<String,Boolean>
字段上使用@XmlJavaTypeAdapter
批注Map<String,Boolean>
如下所示
@XmlJavaTypeAdapter(MapAdapter.class)
private Map<String, Boolean> map
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.