Map轉String,再轉回Map

import org.junit.Test;

import java.util.*;
import java.util.regex.Pattern;

/**
 *
 */
public class Test2 {

    @Test
    public void test() {
        Map<String, String> testMap1 = new HashMap<String, String>();
        testMap1.put("key1", "val1");
        testMap1.put("key2", "val2");

        Map<String, String> testMap2 = new HashMap<String, String>();
        testMap2.put("key21", "val21");
        Map<String, Map<String, String>> testMapMap1 = new HashMap<String, Map<String, String>>();
        testMapMap1.put("key1", testMap1);
        testMapMap1.put("key2", testMap2);

        System.out.println(map2String(testMapMap1));
        System.out.println(mapString2Map(map2String(testMapMap1)));
    }


    public static String map2String(Map map){
        java.util.Map.Entry entry;
        StringBuffer sb = new StringBuffer();
        for(Iterator iterator = map.entrySet().iterator(); iterator.hasNext();)
        {
            entry = (java.util.Map.Entry)iterator.next();
            sb.append(entry.getKey().toString()).append( "'" ).append(null==entry.getValue()?"":
                    entry.getValue().toString().substring(1, entry.getValue().toString().length() - 1)).append (iterator.hasNext() ? "^" : "");
        }
        return sb.toString();
    }

    public static Map mapString2Map(String mapString){
        Map map = new HashMap();
        java.util.StringTokenizer items;
        for(StringTokenizer entrys = new StringTokenizer(mapString, "^"); entrys.hasMoreTokens();
            map.put(items.nextToken(), items.hasMoreTokens() ? (mapStringToMap((String) (items.nextToken()))) : null))
            items = new StringTokenizer(entrys.nextToken(), "'");
        return map;
    }

    public static Map mapStringToMap(String text){
        HashMap<String,String> data = new HashMap<String,String>();
        Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
        String[] split = p.split(text);
        for ( int i=0; i+2 <= split.length; i+=2 ){
            data.put( split[i], split[i+1] );
        }
        return data;
    }

}

參考:http://blog.csdn.net/ziwen00/article/details/7976144

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章