Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XStream with HashMap<String,String>

Anyone could tell me how to Serialize a HashMap with XStream?

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

My xml looks like

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

I want an output like

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

how can achieve that using XStream? Is possible with annotations?

like image 310
mspasiuk Avatar asked Mar 21 '23 19:03

mspasiuk


1 Answers

If you are using XStream 1.4.5, you have the NamedMapConverter to do what you want.

Just register the converter showing how you want to marshal your map as the example bellow:

XStream xstream = new XStream();
NamedMapConverter namedMapConverter = new NamedMapConverter(xstream.getMapper(),"attr","description",String.class,"value",String.class);
xstream.registerConverter(namedMapConverter);
like image 170
pablosaraiva Avatar answered Mar 26 '23 21:03

pablosaraiva