I\'m trying to extract the keys from a JSON Object. The JSON object, in this case, is obtained by making an API call to a social networking site called SkyRock and
Recursive methods for extracting keys from json objects and arrays (in case of duplicates will merge them since methods return Set, but not Array)
public static Set getAllKeys(JSONObject json) {
return getAllKeys(json, new HashSet<>());
}
public static Set getAllKeys(JSONArray arr) {
return getAllKeys(arr, new HashSet<>());
}
private static Set getAllKeys(JSONArray arr, Set keys) {
for (int i = 0; i < arr.length(); i++) {
Object obj = arr.get(i);
if (obj instanceof JSONObject) keys.addAll(getAllKeys(arr.getJSONObject(i)));
if (obj instanceof JSONArray) keys.addAll(getAllKeys(arr.getJSONArray(i)));
}
return keys;
}
private static Set getAllKeys(JSONObject json, Set keys) {
for (String key : json.keySet()) {
Object obj = json.get(key);
if (obj instanceof JSONObject) keys.addAll(getAllKeys(json.getJSONObject(key)));
if (obj instanceof JSONArray) keys.addAll(getAllKeys(json.getJSONArray(key)));
}
keys.addAll(json.keySet());
return keys;
}