XStream与HashMap<String,String>

4
有人能告诉我如何使用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个回答

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接