2013-11-04 132 views
4

任何人都可以告诉我如何用XStream序列化HashMap?XStream with HashMap <String,String>

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的?注释可能吗?

回答

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); 
相关问题