上善若水
In general the OO style is to use a lot of little objects with a lot of little methods that give us a lot of plug points for overriding and variation. To do is to be -Nietzsche, To bei is to do -Kant, Do be do be do -Sinatra
posts - 146,comments - 147,trackbacks - 0
 1public class MapDeserialize {
 2    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    public Map<String, String> str2Map(String str) {
25        Map<String, String> map = new HashMap<String, String>();
26        // The parameters map is empty
27        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        for(String entry : entries) {
35            String[] pair = entry.split("=");
36            String key = pair[0].trim();
37            if(pair.length == 1{
38                map.put(key, "");
39            }
 else {
40                String value = pair[1].trim();
41                if("null".equals(value)) {
42                    map.put(key, null);
43                }
 else {
44                    map.put(key, value);
45                }

46            }

47        }

48        
49        return map;
50    }

51}
这段代码貌似没什么价值,只是保留着,以后再遇到相应的情况,可以再做改进。
posted on 2011-09-20 15:54 DLevin 阅读(508) 评论(0)  编辑  收藏 所属分类: CodeTools

只有注册用户登录后才能发表评论。


网站导航: