我有以下实体:
@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属性中没有重复。)
答案 0 :(得分:1)
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>
答案 1 :(得分:1)
我写了一个自己的转换器:
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;
}
}