转:JSON与Map互转


 

//一、map转为json字符串

    public static String map2jsonstr(Map map){
        return JSONObject.toJSONString(map);
    }

//二、json字符串转Map对象

    public static Map jsonstr2map(String jsonstr){
        return JSONObject.parseObject(jsonstr);
    }

//三、json字符串转Map对象

public static Map parseJSON2Map(String jsonStr){ 
Map map = new HashMap(); 
JSONObject json = JSONObject.parseObject(jsonStr); 
for(Object k : json.keySet()){ 
Object v = json.get(k); 
if(v instanceof JSONArray){ 
List> list = new ArrayList>(); 
Iterator it = ((JSONArray)v).iterator(); 
while(it.hasNext()){ 
JSONObject json2 = (JSONObject)it.next(); 
list.add(parseJSON2Map(json2.toString())); 
} 
map.put(k.toString(), list); 
} else { 
map.put(k.toString(), v); 
}

return map; 
}

测试:

    public static void main(String[] args) {
    
        try {
            
            List list = new ArrayList();
            Map map = new HashMap();
            list.add(1);
            list.add("b");
            map.put("name", "a");
            map.put("age", 12);
            map.put("name", "a");
            map.put("list", list);
            String jsonstr = map2jsonstr(map);
            System.out.println("json字符串:" + jsonstr);
            System.out.println("map对象"+jsonstr2map(jsonstr));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

相关