Skip to content

Instantly share code, notes, and snippets.

@FelixSFD
Last active April 9, 2018 09:18
Show Gist options
  • Save FelixSFD/a134516e7769bd95baa7a528bff9408b to your computer and use it in GitHub Desktop.
Save FelixSFD/a134516e7769bd95baa7a528bff9408b to your computer and use it in GitHub Desktop.
JSONObject/Array to HashMap/List
/**
* Schreibt die Inhalte eines JSONObject in eine HashMap
* @param jsonObj
* @return HashMap
* @throws JSONException
*/
public static HashMap<String, Object> jsonObjectToHashMap(JSONObject jsonObj) throws JSONException {
HashMap<String, Object> map = new HashMap<>();
Iterator keys = jsonObj.keys();
while (keys.hasNext()) {
String key = (String)keys.next();
Object obj = jsonObj.get(key);
if (obj instanceof JSONArray) {
obj = jsonArrayToList((JSONArray)obj);
} else if (obj instanceof JSONObject) {
obj = jsonObjectToHashMap((JSONObject)obj);
} else if (obj == JSONObject.NULL) {
obj = null;
}
map.put(key, obj);
}
return map;
}
/**
* Schreibt die Inhalte eines JSONArray-Objekts in ein List-Objekt
* https://stackoverflow.com/a/24012023/4687348
* @param array
* @return List
* @throws JSONException
*/
public static List<Object> jsonArrayToList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = jsonArrayToList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = jsonObjectToHashMap((JSONObject) value);
}
else if(value == JSONObject.NULL) {
value = null;
}
list.add(value);
}
return list;
} // jsonArrayToList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment