2017-09-24 98 views
0

我似乎無法得到這個API Android Studio中的工作 - 這裏是鏈接http://diskizone.com/wp-json/sportspress/v2/teams如何讀取JSON數據到列表

我想什麼做的是閱讀的JSON和每個團隊添加到列表在Android Studio中,但由於某種原因,它不工作,我正在跟隨一個教程,並修改了代碼,這就是我所擁有的。

protected void onPostExecute(String result) { 
     super.onPostExecute(result); 

     try { 

      JSONObject jsonObject = new JSONObject(result); 

      String teamInfo = jsonObject.getString("0"); 

      Log.i("Teams ", teamInfo); 

      JSONArray arr = new JSONArray(teamInfo); 

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

       JSONObject jsonPart = arr.getJSONObject(i); 

       Log.i("id", jsonPart.getString("id")); 
       Log.i("title", jsonPart.getString("title")); 

      } 


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

回答

0

的API實際上是返回一個JSONArray而不是JSONObject。 因此,試試這個:

protected void onPostExecute(String result) { 
    super.onPostExecute(result); 

    try { 

     JSONArray arr = new JSONArray(result); 

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

      JSONObject jsonPart = arr.getJSONObject(i); 
      Log.i("jsonObject : ", jsonPart.toString()); 
      Log.i("id", jsonPart.getString("id")); 
      Log.i("title", jsonPart.getString("title")); 

     } 


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

THanks a mil!第一次工作:) – NathW