2017-09-24 102 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