Get json array keys in android

Answer given by Mr. K is also right but you can also use jsonObject names() method. please find the sample code

for(int i = 0; i<jsonobject.length(); i++){
    Log.e(TAG, "Key = " + jsonobject.names().getString(i) + " value = " + jsonobject.get(jsonobject.names().getString(i)));
}

I hope dis will help you


User this method to iterate json dynamically

private void parseJson(JSONObject data) {

        if (data != null) {
            Iterator<String> it = data.keys();
            while (it.hasNext()) {
                String key = it.next();

                try {
                    if (data.get(key) instanceof JSONArray) {
                        JSONArray arry = data.getJSONArray(key);
                        int size = arry.length();
                        for (int i = 0; i < size; i++) {
                            parseJson(arry.getJSONObject(i));
                        }
                    } else if (data.get(key) instanceof JSONObject) {
                        parseJson(data.getJSONObject(key));
                    } else {
                        System.out.println("" + key + " : " + data.optString(key));
                    }
                } catch (Throwable e) {
                    System.out.println("" + key + " : " + data.optString(key));
                    e.printStackTrace();

                }
            }
        }
    }

above sample json array , how to get the 204, 203 and 202?

No, current String is JSONObject instead of JSONArray. you should get Iterator using JSONObject. keys () if inner JSONObject keys dynamic as:

JSONObject issueObj = new JSONObject(jsonContent);
Iterator iterator = issueObj.keys();
   while(iterator.hasNext()){
    String key = (String)iterator.next();
    JSONObject issue = issueObj.getJSONObject(key);

    //  get id from  issue
        String _pubKey = issue.optString("id");
    }

Tags:

Json

Android