今天工作中遇到一个问题,有一些Map < String, Object >类型的数据我需要放到redis中,但是从redis中取出来的又是String类型 需要转Map。想了想 只记得 Map.toString()这样可以将Map转换到String。不记得怎么String转map
也试了试Map自带的方法中好像也没有 String 转 Map的
就在网上找了个方法:
public static MapgetValue(String param) { Map map = new HashMap<>(); String str = ""; String key = ""; Object value = ""; char[] charList = param.toCharArray(); boolean valueBegin = false; for (int i = 0; i < charList.length; i++) { char c = charList[i]; if (c == '{') { if (valueBegin == true) { value = getValue(param.substring(i, param.length())); i = param.indexOf('}', i) + 1; map.put(key, value); } } else if (c == '=') { valueBegin = true; key = str; str = ""; } else if (c == ',') { valueBegin = false; value = str; str = ""; map.put(key, value); } else if (c == '}') { if (str != "") { value = str; } map.put(key, value); return map; } else if (c != ' ') { str += c; } } return map; }
然后写了个方法 简单测试一下:
public static void main(String[] args) {
Map map = new HashMap();
map.put("aaa", 11);
map.put("bbb", 22);
map.put("ccc", 33);
map.put("ddd", 44);
String string = map.toString();
System.out.println("map转String"+string);
// Map stringToMap = getStringToMap(string);
Map stringToMap = getValue(string);
for(Object a : stringToMap.keySet()) {
System.out.println(stringToMap.get(a).toString());
}
}
运行结果:
需要注意的是 value 值中 不能带 逗号(,)



