1 package com.thoughtworks.xstream.converters.collections; 2 3 import com.thoughtworks.xstream.alias.ClassMapper; 4 import com.thoughtworks.xstream.converters.MarshallingContext; 5 import com.thoughtworks.xstream.converters.UnmarshallingContext; 6 import com.thoughtworks.xstream.core.JVM; 7 import com.thoughtworks.xstream.io.HierarchicalStreamReader; 8 import com.thoughtworks.xstream.io.HierarchicalStreamWriter; 9 10 import java.util.HashMap ; 11 import java.util.Hashtable ; 12 import java.util.Iterator ; 13 import java.util.Map ; 14 15 24 public class MapConverter extends AbstractCollectionConverter { 25 26 public MapConverter(ClassMapper classMapper, String classAttributeIdentifier) { 27 super(classMapper, classAttributeIdentifier); 28 } 29 30 public boolean canConvert(Class type) { 31 return type.equals(HashMap .class) 32 || type.equals(Hashtable .class) 33 || (JVM.is14() && type.getName().equals("java.util.LinkedHashMap")); 34 } 35 36 public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { 37 Map map = (Map ) source; 38 for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) { 39 Map.Entry entry = (Map.Entry ) iterator.next(); 40 writer.startNode("entry"); 41 42 writeItem(entry.getKey(), context, writer); 43 writeItem(entry.getValue(), context, writer); 44 45 writer.endNode(); 46 } 47 } 48 49 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { 50 Map map = (Map ) createCollection(context.getRequiredType()); 51 populateMap(reader, context, map); 52 return map; 53 } 54 55 protected void populateMap(HierarchicalStreamReader reader, UnmarshallingContext context, Map map) { 56 while (reader.hasMoreChildren()) { 57 reader.moveDown(); 58 59 reader.moveDown(); 60 Object key = readItem(reader, context, map); 61 reader.moveUp(); 62 63 reader.moveDown(); 64 Object value = readItem(reader, context, map); 65 reader.moveUp(); 66 67 map.put(key, value); 68 69 reader.moveUp(); 70 } 71 } 72 73 } 74 | Popular Tags |