I\'m requesting data from a server which returns data in the JSON format. Casting a HashMap into JSON when making the request wasn\'t hard at all but the other way seems to
You can use this class instead :) (handles even lists , nested lists and json)
public class Utility {
public static Map jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map _jsonToMap_(JSONObject json) throws JSONException {
Map retMap = new HashMap();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map toMap(JSONObject object) throws JSONException {
Map map = new HashMap();
Iterator keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List
To convert your JSON string to hashmap use this :
HashMap hashMap = new HashMap<>(Utility.jsonToMap(response)) ;