Skip to content Skip to sidebar Skip to footer

Iterate Through Json Array With Either A For-each Loop Or By Using An Iterator (android Studio)

I'm currently trying to iterate through a JSONArray with either a for-each loop or an Iterator instead of a normal for-loop, but looks like org.json doesn't support them. Any ideas

Solution 1:

You can use an iterator, as JsonArray provides a getIterator method. However these are raw iterators, so there is no specific type associated with them (so every element is considered to be an Object). You can downcast them though.

ArrayList<String> list = newArrayList<>();
    String strJson = loadJsonFromAssetsFolder();
    JSONObject jsonRootObject = newJSONObject(strJson);
    JSONArray jsonArray = jsonRootObject.optJSONArray("restaurant");
    for (Object jsonObject : jsonArray) {
        list.add(((JSONObject) jsonObject).optString("name"));
    }

Is there any reason why you don't want to use a normal for loop? There is no difference really. You could also look into libraries like GSON, which can map it to a Java Object.

Post a Comment for "Iterate Through Json Array With Either A For-each Loop Or By Using An Iterator (android Studio)"