使用org.json遇迭代报错:JSONArray无法作为Iterable遍历
解决org.json.JSONArray无法用增强for循环遍历的问题
别急,这问题其实很常见,我马上帮你搞定!
问题根源
你用的org.json库中的JSONArray类并没有实现java.lang.Iterable接口,所以直接用增强for循环(for (Object o : historyJson))遍历会触发报错,这就是提示“Can only iterate over an array or an instance of java.lang.Iterable”的核心原因。
快速解决方案(优先推荐,无需改依赖)
直接换成普通的索引式for循环,这是最稳妥且最快能解决的方式,完全适配你的现有代码逻辑:
JSONArray historyJson = new JSONArray(nameHistoryResponse); // 用索引遍历,和你原来的index递增逻辑保持一致 for (int i = 0; i < historyJson.length(); i++) { index++; JSONObject jsonObj = historyJson.getJSONObject(i); String name = jsonObj.getString("name"); if (name.equalsIgnoreCase(data[2].toString())) { foundIndex = index; } }
备选方案(如果坚持用增强for循环)
可以把JSONArray转成List集合,因为List是Iterable的实现类,就能用增强for循环了:
JSONArray historyJson = new JSONArray(nameHistoryResponse); List<Object> jsonList = historyJson.toList(); for (Object o : jsonList) { index++; JSONObject jsonObj = (JSONObject) o; String name = jsonObj.getString("name"); if (name.equalsIgnoreCase(data[2].toString())) { foundIndex = index; } }
长期解决方案(如果允许升级依赖)
如果你的项目可以调整依赖版本,可以升级org.json到20200518及以后的版本——这个版本之后的JSONArray已经实现了Iterable<Object>接口,就能直接用增强for循环了。比如Maven依赖可以改成:
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20240303</version> </dependency>
紧急情况提示
因为你项目需要2小时内完成,优先用第一个普通for循环的方案,不需要改任何依赖,直接替换代码就能正常运行,不会耽误时间。
内容的提问来源于stack exchange,提问作者Abdel Seaf
相关产品推荐
相关产品推荐

