2013-11-04 180 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); 
相關問題