2016-04-03 151 views
0

我正在尝试以下遍历JSONArray中的每个JSONObject,但它不工作。我检查日志中的JSONArray的长度,它给了我正确的长度,但是我无法在JSONArray的每个元素上获取JSONObject。另外,每个元素应该是一个带有8个键/值对的JSONObject。任何反馈非常感谢,谢谢。Android,无法遍历JSONArray for循环

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(); 
        } 


       } 
      } 

     } 

回答

0

在你的for循环innerJSONArray.length() < 0;应该是i < innerJSONArray.length()

,这一行应该按预期工作:

JSONObject jsonObject1 = innerJSONArray.getJSONObject(i); 
+1

谢谢!我不知道该怎么看。我修复了它,现在它可以工作。 – eaavendano