带有HashMap的XStream <String,String>

msp*_*iuk 4 java annotations xstream hashmap xml-serialization

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

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

我的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>
Run Code Online (Sandbox Code Playgroud)

我想要一个输出

<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>
Run Code Online (Sandbox Code Playgroud)

怎么用XStream实现呢?是否可以注释?

pab*_*iva 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);
Run Code Online (Sandbox Code Playgroud)