java String 转map
时间: 2024-06-13 10:09:23 浏览: 93
以下是两种Java String转Map的例子:
1.使用Java自带的HashMap类
```java
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库
```java
String str = "{ \"key1\":\"value1\", \"key2\":\"value2\", \"key3\":\"value3\" }";
Map<String, Object> map = JSON.parseObject(str, new TypeReference<Map<String, Object>>() {});
System.out.println(map);
```
阅读全文