Skip to content

Instantly share code, notes, and snippets.

@maheshkelkar
Created May 25, 2016 21:34
Show Gist options
  • Save maheshkelkar/10b3f868e6bf4e689a7f3886e5f2929a to your computer and use it in GitHub Desktop.
Save maheshkelkar/10b3f868e6bf4e689a7f3886e5f2929a to your computer and use it in GitHub Desktop.
Simple example on how to convert Json string to Hash Map<String, Object>
//http://stackoverflow.com/questions/21720759/convert-a-json-string-to-a-hashmap
public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> 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<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment