Friday, 23 December 2011

Hash-map to XML with recursion

public static class MapEntryConverter implements Converter {

       public boolean canConvert(Class clazz) {
               return AbstractMap.class.isAssignableFrom(clazz);
       }
       public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
        AbstractMap map = (AbstractMap) value;
        for (Object obj : map.entrySet()) {
               Entry entry = (Entry) obj;
               writer.startNode(entry.getKey().toString());
               if (entry.getValue() instanceof HashMap) {
                   marshal(entry.getValue(), writer, context);

               } else {
                   writer.setValue(entry.getValue().toString());
               }
               writer.endNode();
           }      
       }
      
       public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
           Map<String, Object> map = new HashMap<String, Object>();

           while(reader.hasMoreChildren()) {
                   reader.moveDown();
                   map.put(reader.getNodeName(), reader.getValue());
                   reader.moveUp();
               }
               return map;
           }

    }


The code shown above is based on the Xstream code provided in this link from stackoverflow.com. A recursive call is added to take account of nested Hashmaps.