JSON与Map互转

  • json转Map

  • 用fastJSON最便捷
    private static Map toMap(String jsonStr) {
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(jsonStr);
        HashMap map = new HashMap<>();
        Set> entries = jsonObject.entrySet();
        for (Map.Entry entry : entries) {
            map.put(entry.getKey(),entry.getValue());
        }
        return map;
    }
  • 用原生的json
public static Map jsonToMap (String jsonStr) {

        HashMap map = new HashMap<>();
        JSONObject jsonObject = JSONObject.fromObject(jsonStr);
        for (Object key : jsonObject.keySet()) {
            Object obj = jsonObject.get(key);
            if (obj instanceof JSONArray) {
                List> list = new ArrayList>();
                Iterator iterator = ((JSONArray) obj).iterator();
                while (iterator.hasNext()) {
                    JSONObject next = iterator.next();
                    list.add(jsonToMap(next.toString()));
                }
                map.put(key.toString(),list);
                log.info("key.toString:" + key.toString() + " " + "list:" + list);
            } else {
                map.put(key.toString(), obj);
                log.info("key.toString:" + key.toString() +" "+ "obj:" + obj);
            }
        }
        return map;
    }
  • map转Json

  • 方法用很多种,我采用的是下面这种
public static String mapToJson(Map map) {
        Set keySet = map.keySet();
        String key;
        Object value;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("{");
        for (Iterator iterator = keySet.iterator(); iterator.hasNext(); ) {
            key = iterator.next();
            value = map.get(key);
            stringBuilder.append("\"" + key + "\"" + ":" + "\"" + value + "\"");
            if (iterator.hasNext()) {
                stringBuilder.append(",");
            }
        }
        stringBuilder.append("}");
        return stringBuilder.toString();
    }

 

你可能感兴趣的:(JSON与Map互转)