How to convert hashmap to JSON object in Java

前端 未结 29 2339
谎友^
谎友^ 2020-11-22 11:20

How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?

29条回答
  •  遥遥无期
    2020-11-22 11:39

    No need for Gson or JSON parsing libraries. Just using new JSONObject(Map).toString(), e.g:

    /**
     * convert target map to JSON string
     *
     * @param map the target map
     * @return JSON string of the map
     */
    @NonNull public String toJson(@NonNull Map map) {
        final Map flatMap = new HashMap<>();
        for (String key : map.keySet()) {
            try {
                flatMap.put(key, toJsonObject(map.get(key)));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        try {
            // 2 indentSpaces for pretty printing
            return new JSONObject(flatMap).toString(2);
        } catch (JSONException e) {
            e.printStackTrace();
            return "{}";
        }
    }
    

提交回复
热议问题