Java中String类型与Map类型互转 | 您所在的位置:网站首页 › 强制转换为string类型 › Java中String类型与Map类型互转 |
一、mapString与Map之间互转
1、map类型转换成string类型 Map map = new HashMap(); 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 mapStringToMap(String str){ str = str.substring(1, str.length()-1); String[] strs = str.split(","); Map map = new HashMap(); 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 map = new HashMap(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); System.out.println("source: " + map.toString()); String mapStr = map.toString(); Map 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 map = new HashMap(); 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 jsonMap = JSON.parseObject(jsonStr, new TypeReference() { }); 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} |
CopyRight 2018-2019 实验室设备网 版权所有 |