![](/img/trans.png)
[英]How to make XStream map unmapped tags to an HashMap when parsing XML?
[英]How to map an Hashmap to key-value-attributes in XML using xstream
我有以下實體:
@XStreamAlias("entity")
public class MapTestEntity {
@XStreamAsAttribute
public Map<String, String> myMap = new HashMap<>();
@XStreamAsAttribute
public String myText;
}
我在xstream中使用它:
MapTestEntity e = new MapTestEntity();
e.myText = "Foo";
e.myMap.put("firstname", "homer");
e.myMap.put("lastname", "simpson");
XStream xstream = new XStream(new PureJavaReflectionProvider());
xstream.processAnnotations(MapTestEntity.class);
System.out.println(xstream.toXML(e));
並獲取以下xml:
<entity myText="Foo">
<myMap>
<entry>
<string>lastname</string>
<string>simpson</string>
</entry>
<entry>
<string>firstname</string>
<string>homer</string>
</entry>
</myMap>
</entity>
但我需要將HashMap
映射到xml中的屬性,如:
<entity myText="Foo" lastname="simpson" firstname="homer" />
我怎么能用XStream做到這一點? 我可以使用自定義轉換器或映射器或類似的東西嗎? TIA!
(當然我的代碼需要確保在xml屬性中沒有重復。)
NamedMapConverter
可以實現這一點。 看看http://x-stream.github.io/javadoc/com/thoughtworks/xstream/converters/extended/NamedMapConverter.html
第三個例子准確地說明了你想要的:
new NamedMapConverter(xstream.getMapper(), "entry", "key", String.class, "value", Integer.class, true, true, xstream.getConverterLookup());
創建此xml輸出:
<map>
<entry key="keyValue" value="0"/>
</map>
我寫了一個自己的轉換器:
public class MapToAttributesConverter implements Converter {
public MapToAttributesConverter() {
}
@Override
public boolean canConvert(Class type) {
return Map.class.isAssignableFrom(type);
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
Map<String, String> map = (Map<String, String>) source;
for (Map.Entry<String, String> entry : map.entrySet()) {
writer.addAttribute(entry.getKey(), entry.getValue().toString());
}
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < reader.getAttributeCount(); i++) {
String key = reader.getAttributeName(i);
String value = reader.getAttribute(key);
map.put(key, value);
}
return map;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.