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;
}
}