Why for each loop is not applicable for JSON array

后端 未结 3 1742
滥情空心
滥情空心 2021-01-19 10:17

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

相关标签:
3条回答
  • 2021-01-19 10:59

    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.

    0 讨论(0)
  • 2021-01-19 11:00

    Because JSONArrayclass doesn't implement Iterable interface.

    0 讨论(0)
  • 2021-01-19 11:04

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

    0 讨论(0)
提交回复
热议问题