How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?
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;
}