Extracting Keys from a JSONObject using keySet()

前端 未结 5 1620
走了就别回头了
走了就别回头了 2020-12-03 22:27

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

5条回答
  •  -上瘾入骨i
    2020-12-03 23:12

    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;
    }
    

提交回复
热议问题