How to convert hashmap to JSON object in Java

前端 未结 29 2007
谎友^
谎友^ 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:56

    You can just enumerate the map and add the key-value pairs to the JSONObject

    Method :

    private JSONObject getJsonFromMap(Map map) throws JSONException {
        JSONObject jsonData = new JSONObject();
        for (String key : map.keySet()) {
            Object value = map.get(key);
            if (value instanceof Map) {
                value = getJsonFromMap((Map) value);
            }
            jsonData.put(key, value);
        }
        return jsonData;
    }
    

提交回复
热议问题