mapString转换成Map类型

问题描述

需要实现mapString转换成Map类型,对过程进行一下记录

    /**
     * 将Map字符串转换为Map
     *
     * @param str
     * @return
     */
    private static Map mapStringToMap(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        str = str.substring(1, str.length() - 1);
        String[] strs = str.split(",");
        Map map = new HashMap();
        for (String string : strs) {
            String[] strSplit = string.split("=");
            if (strSplit.length <= 1) {
                return map;
            }
            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) {
        String mapStr = "{key1=value1, key2=value2, key3=value3}";
        Map newMap = mapStringToMap(mapStr);
    }

你可能感兴趣的:(java,java,开发语言)