一、mapString与Map之间互转
1、map类型转换成string类型
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
System.out.println(map.toString());
执行结果:
{key1=value1, key2=value2, key3=value3}
2、mapString转换成Map类型
/**
* 将Map字符串转换为Map
*
* @param str Map字符串
* @return Map
*/
public static Map<String,String> mapStringToMap(String str){
str = str.substring(1, str.length()-1);
String[] strs = str.split(",");
Map<String,String> map = new HashMap<String, String>();
for (String string : strs) {
String key = string.split("=")[0];
String value = string.split("=")[1];
// 去掉头部空格
String key1 = key.trim();
String value1 = value.trim();
map.put(key1, value1);
}
return map;
}
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
System.out.println("source: " + map.toString());
String mapStr = map.toString();
Map<String, String> newMap = mapStringToMap(mapStr);
System.out.println("transfer: " + map.toString());
}
执行结果:
source: {key1=value1, key2=value2, key3=value3}
transfer: {key1=value1, key2=value2, key3=value3}
注意:
在转换Map类型过程中,存在空格问题,过程中需要调用string.trim()来进行去空格操作,而且需要新定义String变量来存储trim操作之后的string值,因为trim接口不会更改源string值。
二、jsonString与Map之间转换
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
System.out.println("source: " + map.toString());
// map转换成jsonString
String jsonStr = JSON.toJSONString(map);
System.out.println("jsonStr: " + jsonStr);
// jsonString转换成Map
Map<String, String> jsonMap = JSON.parseObject(jsonStr, new TypeReference<HashMap<String, String>>() {
});
System.out.println("jsonMap: " + jsonMap.toString());
}
执行结果:
source: {key1=value1, key2=value2, key3=value3}
jsonStr: {"key1":"value1","key2":"value2","key3":"value3"}
jsonMap: {key1=value1, key2=value2, key3=value3}