带有HashMap的XStream <string,string> </string,string>

时间:2013-11-04 19:13:19

标签: java annotations hashmap xml-serialization xstream

任何人都可以告诉我如何使用XStream序列化HashMap?

private HashMap<String,String> attributes;
attributes = new HashMap<String,String>();
attributes.put("Description","Value");
attributes.put("Description2","Value2");
attributes.put("Description3","Value3");

我的xml看起来像

<attributes>
       <entry>
           <string>Description</string>
           <string>value</string>
       </entry>
       <entry>
           <string>Description2</string>
           <string>Value2</string>
       </entry>
       <entry>
           <string>Description3</string>
           <string>Value3</string>
       </entry>
    </attributes>

我想要输出

<attributes>
    <attr>
        <description>Description</description>
        <value>Value</value>
    </attr>
    <attr>
        <description>Description2</description>
        <value>Value2</value>
    </attr>
    <attr>
        <description>Description3</description>
        <value>Value</value>
    </attr>
</attributes>

如何使用XStream实现这一目标?是否可以注释?

1 个答案:

答案 0 :(得分:7)

如果您使用的是XStream 1.4.5,则可以使用 NamedMapConverter 来执行您想要的操作。

只需注册转换器即可显示您要如何编组地图,如下例所示:

XStream xstream = new XStream();
NamedMapConverter namedMapConverter = new NamedMapConverter(xstream.getMapper(),"attr","description",String.class,"value",String.class);
xstream.registerConverter(namedMapConverter);