为什么每个循环不适用于JSON数组 [英] Why for each loop is not applicable for JSON array

查看:188
本文介绍了为什么每个循环不适用于JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试解析json数组时,工作室给了我一个编译错误,指出 foreach不适用于json数组. 尽管我知道如何获取所有对象并进行解析;我只是想知道为什么foreach不适用,即使json数组是一个数组

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

推荐答案

每个循环都像这样-

例如对于和整数类型ArrayList<Integer> list;

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

但是JSONArray可以在其中包含任何类型的值.

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

例如-

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

这是一个有效的JSONArray,但是它包含各种对象,即-JSONObject,Integer,Boolean.因此,每次循环我们都会得到不同类型的值.

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.

因此要对该数组的每个循环应用a,我们必须首先将所有内容强制转换为Object类-

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.

这篇关于为什么每个循环不适用于JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆