1![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
public class MapDeserialize
{
2![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public static void main(String[] args)
{
3
Map<String, String> map = new HashMap<String, String>();
4
map.put("key1", "value1");
5
map.put("key2", null);
6
map.put("key3", "");
7
8
System.out.println(map);
9
10
Map<String, String> emptyMap = new HashMap<String, String>();
11
System.out.println(emptyMap);
12
13
MapDeserialize deserialize = new MapDeserialize();
14
String str1 = "{key3=, key2=null, key1=value1}";
15
String str2 = "{}";
16
Map<String, String> map1 = deserialize.str2Map(str1);
17
System.out.println("map1: " + map1);
18
Map<String, String> map2 = deserialize.str2Map(str2);
19
System.out.println("map2: " + map2);
20
}
21
22
// We are assuming that the str is generated by map.toString(), so the str will be something like:
23
// '{key3=, key2=null, key1=value1}' or '{}'
24![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public Map<String, String> str2Map(String str)
{
25
Map<String, String> map = new HashMap<String, String>();
26
// The parameters map is empty
27![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if("{}".equals(str) || str == null || str.length() == 0)
{
28
return map;
29
}
30
31
// Remove the '{' prefix and '}' suffix
32
str = str.substring(1, str.length() - 1);
33
String[] entries = str.split(",");
34![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for(String entry : entries)
{
35
String[] pair = entry.split("=");
36
String key = pair[0].trim();
37![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if(pair.length == 1)
{
38
map.put(key, "");
39![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
} else
{
40
String value = pair[1].trim();
41![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if("null".equals(value))
{
42
map.put(key, null);
43![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
} else
{
44
map.put(key, value);
45
}
46
}
47
}
48
49
return map;
50
}
51
} 这段代码貌似没什么价值,只是保留着,以后再遇到相应的情况,可以再做改进。
posted on 2011-09-20 15:54
DLevin 阅读(516)
评论(0) 编辑 收藏 所属分类:
CodeTools