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
In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.
A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With