5

When I was trying to parse a json array, the studio gave me a compilation error stating foreach is not applicable for json array. Although I know how to get all objects and parse; I just wanted to know why foreach is not applicable even though the json array is an array

2
  • Please show some code. Commented Mar 3, 2016 at 11:51
  • Add some part of code Commented Mar 3, 2016 at 11:51

3 Answers 3

9

For each loop works like this -

For example for and Integer type ArrayList<Integer> list;

for (int x : list)
    // process x here

But a JSONArray can have any type of value inside it.

For example -

[{"name" : John}, {"name" : Joe}, 1, false]

This is a valid JSONArray but it contains all kinds of objects namely - JSONObject, Integer, Boolean. So we would get a different type of value each time in for each loop.

So to apply a for each loop on this array we'll have to cast everything to Object class first -

for (Object o : myJsonArray)

Which doesn't makes much sense and would require a lot of useless effort.

Sign up to request clarification or add additional context in comments.

Comments

9

Because JSONArrayclass doesn't implement Iterable interface.

Comments

4

Because JSONArray derives from Object and foreach expects the collection to be iterable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.