Created
May 25, 2016 21:34
-
-
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>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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