在 Java 中将 String 转换为 Map 的常用方法
JSON 解析法
适用于标准 JSON 格式字符串(如 {"name":"John","age":30}),需依赖第三方库。
1.使用 Gson
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
String jsonStr = "{\"name\":\"John\", \"age\":30}";
Gson gson = new Gson();
Map<String, Object> map = gson.fromJson(jsonStr, new TypeToken<Map<String, Object>>(){}.getType()); // 直接解析为 Map:ml-citation{ref="3,4" data="citationList"}
System.out.println(map.get("name")); // 输出:John:ml-citation{ref="3,4" data="citationList"}
2.使用 FastJSON
import com.alibaba.fastjson.JSON;
String jsonStr = "{\"city\":\"New York\"}";
Map<String, String> map = JSON.parseObject(jsonStr, new TypeReference<Map<String, String>>(){}); // 泛型支持:ml-citation{ref="2,3" data="citationList"}
System.out.println(map.get("city")); // 输出:New York:ml-citation{ref="2,3" data="citationList"}
3.使用 org.json
import org.json.JSONObject;
String jsonStr = "{\"key1\":\"value1\", \"key2\":100}";
JSONObject jsonObject = new JSONObject(jsonStr);
Map<String, Object> map = jsonObject.toMap(); // JSONObject 转 Map:ml-citation{ref="5,7" data="citationList"}
```:ml-citation{ref="5,7" data="citationList"}
===============
浙公网安备 33010602011771号