【问题标题】:XStream with HashMap<String,String>XStream 与 HashMap<String,String>
【发布时间】:2013-11-15 12:22:02
【问题描述】:

谁能告诉我如何用 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 实现这一点?可以带注释吗?

【问题讨论】:

    标签: java annotations hashmap xml-serialization xstream


    【解决方案1】:

    如果您使用的是 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);
    

    【讨论】:

      猜你喜欢
      • 2018-07-30
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-07
      • 2013-07-29
      • 2021-12-12
      相关资源
      最近更新 更多