Skip to content Skip to sidebar Skip to footer

Getting All Objects Within An Object Json Java Android

So im trying to consume the League of Legends API which returns a JSON response. Im not using a fancy lib like Jakcson or GSON, {'type':'champion','version':'5.11.1','data':{'Thres

Solution 1:

Get the keys for the JSON Object with keys() and then iterate over them.

Iterator<String> keys = json.keys();

while (keys.hasNext())
{
    // Get the keyString key = keys.next();

    // Get the valueJSONObject value = json.getJSONObject(key);

    // Do something...
}

Solution 2:

You can use Iterator for parsing the data

Iterator<?> keys = jObject.keys();

    while( keys.hasNext() ) {
        String key = (String)keys.next();
        if ( jObject.get(key) instanceofJSONObject ) {
    ...
...
..
        }
    }

Solution 3:

Here's an example to get all Values from JSON Document recursivly. Here import org.json.* is used

publicstaticvoidprintJSON(JSONObject jsonObj) {
    //Iterating Key Setfor (Object keyObj : jsonObj.keySet()) {
        String key = (String) keyObj;
        Object valObj = jsonObj.get(key);
        //If next entry is Objectif (valObj instanceofJSONObject) {
            // call printJSON on nested objectprintJSON((JSONObject) valObj);
        } 
        //iff next entry is nested Arrayelseif (valObj instanceofJSONArray) {
            System.out.println("NestedArraykey : " + key);
            printJSONArray((JSONArray) valObj);

        } else {
            System.out.println("key : " + key);
            System.out.println("value : " + valObj.toString());
        }
    }
}

publicstaticvoidprintJSONArray(JSONArray jarray) {
    //Get Object from Array for (int i = 0; i < jarray.length(); i++) {
        printJSON(jarray.getJSONObject(i));
    }

}

Post a Comment for "Getting All Objects Within An Object Json Java Android"