import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import java.util.Map;public class JsonStr2Map { public static void main(String[] args){ String str = "{\"key1\":\"悟空\",\"key2\":\"八戒\",\"key3\":\"沙僧\"}"; //第一种 Map maps = (Map)JSON.parse(str); //第二种 Map mapTypes = JSON.parseObject(str); //第三种 Map mapType = JSON.parseObject(str,Map.class); //第四种 Map json = (Map) JSONObject.parse(str); //第五种 JSONObject jsonObject = JSONObject.parseObject(str); //第六种 Map mapObj = JSONObject.parseObject(str,Map.class); Map maps = (Map)JSON.parse(str); for (Object map : maps.entrySet()){ System.out.println(((Map.Entry)map).getKey()+" " + ((Map.Entry)map).getValue()); } Map mapTypes = JSON.parseObject(str); for (Object obj : mapTypes.keySet()){ System.out.println("key为:"+obj+"值为:"+mapTypes.get(obj)); } Map mapType = JSON.parseObject(str,Map.class); for (Object obj : mapType.keySet()){ System.out.println("key为:"+obj+"值为:"+mapType.get(obj)); } Map json = (Map) JSONObject.parse(str); for (Object map : json.entrySet()){ System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue()); } JSONObject jsonObject = JSONObject.parseObject(str); for (Object map : json.entrySet()){ System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue()); } Map mapObj = JSONObject.parseObject(str,Map.class); for (Object map: json.entrySet()){ System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue()); } }}
参考:fastjson将json字符串转化成map的五种方法 - 何其小静 - 博客园 (cnblogs.com)
源码:
第一种
Map maps = (Map)JSON.parse(str);
public abstract class JSON implements JSONStreamAware, JSONAware { public static Object parse(String text) { return parse(text, DEFAULT_PARSER_FEATURE); }}
第二种
Map mapTypes = JSON.parseObject(str);
public abstract class JSON implements JSONStreamAware, JSONAware { public static JSONObject parseObject(String text) { Object obj = parse(text); if (obj instanceof JSONObject) { return (JSONObject)obj; } else { try { return (JSONObject)toJSON(obj); } catch (RuntimeException var3) { throw new JSONException("can not cast to JSONObject.", var3); } } }}
JSONObject实现了Map,所以可以用Map接收
public class JSONObject extends JSON implements Map, Cloneable, Serializable, InvocationHandler {
来源地址:https://blog.csdn.net/u011149152/article/details/130092332