How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?
No need for Gson or JSON parsing libraries.
Just using new JSONObject(Map
, 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 "{}";
}
}