2016-04-03 153 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