java String 转map
时间: 2024-06-13 16:09:23 浏览: 105
以下是两种Java String转Map的例子:
1.使用Java自带的HashMap类
String str = "{ \"key1\":\"value1\", \"key2\":\"value2\", \"key3\":\"value3\" }";
str = str.replaceAll("\\\\", ""); // 去掉转义字符
str = str.substring(1, str.length() - 1); // 去掉大括号
String[] keyValuePairs = str.split(","); // 按逗号分隔成键值对
Map<String, String> map = new HashMap<>();
for (String pair : keyValuePairs) {
String[] entry = pair.split(":"); // 按冒号分隔键和值
map.put(entry[0].trim().replaceAll("\"", ""), entry[1].trim().replaceAll("\"", ""));
}
System.out.println(map);
2.使用阿里巴巴的fastjson库
String str = "{ \"key1\":\"value1\", \"key2\":\"value2\", \"key3\":\"value3\" }";
Map<String, Object> map = JSON.parseObject(str, new TypeReference<Map<String, Object>>() {});
System.out.println(map);
相关推荐
















