How to map an Hashmap to key-value-attributes in XML using xstream

回眸只為那壹抹淺笑 提交于 2019-12-05 19:26:27

I wrote an own Converter:

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;
    }
}
Vertex

The NamedMapConverter can achieve this. Take a look at http://x-stream.github.io/javadoc/com/thoughtworks/xstream/converters/extended/NamedMapConverter.html

The third example shows exactly that, what you want:

    new NamedMapConverter(xstream.getMapper(), "entry", "key", String.class, "value", Integer.class, true, true, xstream.getConverterLookup());

Creates this xml output:

    <map>
        <entry key="keyValue" value="0"/>
    </map>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!