KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > converters > collections > MapConverter


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 JavaDoc;
11 import java.util.Hashtable JavaDoc;
12 import java.util.Iterator JavaDoc;
13 import java.util.Map JavaDoc;
14
15 /**
16  * Converts a java.util.Map to XML, specifying an 'entry'
17  * element with 'key' and 'value' children.
18  * <p/>
19  * <p>Supports java.util.HashMap, java.util.Hashtable and
20  * java.util.LinkedHashMap.</p>
21  *
22  * @author Joe Walnes
23  */

24 public class MapConverter extends AbstractCollectionConverter {
25
26     public MapConverter(ClassMapper classMapper, String JavaDoc classAttributeIdentifier) {
27         super(classMapper, classAttributeIdentifier);
28     }
29
30     public boolean canConvert(Class JavaDoc type) {
31         return type.equals(HashMap JavaDoc.class)
32                 || type.equals(Hashtable JavaDoc.class)
33                 || (JVM.is14() && type.getName().equals("java.util.LinkedHashMap"));
34     }
35
36     public void marshal(Object JavaDoc source, HierarchicalStreamWriter writer, MarshallingContext context) {
37         Map JavaDoc map = (Map JavaDoc) source;
38         for (Iterator JavaDoc iterator = map.entrySet().iterator(); iterator.hasNext();) {
39             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) 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 JavaDoc unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
50         Map JavaDoc map = (Map JavaDoc) createCollection(context.getRequiredType());
51         populateMap(reader, context, map);
52         return map;
53     }
54
55     protected void populateMap(HierarchicalStreamReader reader, UnmarshallingContext context, Map JavaDoc map) {
56         while (reader.hasMoreChildren()) {
57             reader.moveDown();
58
59             reader.moveDown();
60             Object JavaDoc key = readItem(reader, context, map);
61             reader.moveUp();
62
63             reader.moveDown();
64             Object JavaDoc 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