简体   繁体   English

Android,无法在for循环内遍历JSONArray

[英]Android, cannot iterate through JSONArray inside for-loop

I'm trying the following to iterate through each JSONObject in an JSONArray but it's not working. 我正在尝试以下内容遍历JSONArray中的每个JSONObject,但是它不起作用。 I check the length of the JSONArray in the Log and it gives me the correct lenght, but I can't get the JSONObject at each element of the JSONArray. 我在日志中检查了JSONArray的长度,它为我提供了正确的长度,但是我无法在JSONArray的每个元素上获取JSONObject。 Also, each element should be a JSONObject with 8 key/value pairs. 此外,每个元素都应该是具有8个键/值对的JSONObject。 Any feedback is greatly appreciated, thanks. 非常感谢任何反馈。

if (getMyJSONArray() != null) {

            newJSONArray = getMyJSONArray();

            try {
                // Did this because the JSONArray was inside a JSONArray
                innerJSONArray = newJSONArray.getJSONArray(0);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (innerJSONArray != null) {

                // This gives me the right length
                Log.i("innerJSONArray.length: ", String.valueOf(innerJSONArray.length()));

                for (int i = 0; innerJSONArray.length() < 0; i++) {

                    try {

                        // This doesn't work
                        JSONObject jsonObject1 = innerJSONArray.getJSONObject(i);

                        // This doesn't work either
                        JSONObject jsonObject2 = new JSONObject(innerJSONArray.getString(i));

            …(more code below to use if the part above works)

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            }

        }

In your for loop innerJSONArray.length() < 0; 在您的for循环中, innerJSONArray.length() < 0; should be i < innerJSONArray.length() . 应该是i < innerJSONArray.length()

Then this line should work as expected: 然后此行应按预期工作:

JSONObject jsonObject1 = innerJSONArray.getJSONObject(i);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM