2017-03-29 189 views
-3

我已經使用了JSON庫,試圖解析以下JSON數據:解析JSON陣列

{"dailygameschedule": { 
    "lastUpdatedOn": "2016-12-19 12:32:56 AM", 
    "gameentry": [ 
     { 
      "id": "37705", 
      "date": "2016-04-03", 
      "time": "1:30PM", 
      "awayTeam": { 
       ID: "133", 
       City: "St. Louis", 
       Name: "Cardinals" 
       Abbreviation: "STL" 
      }, 
      "homeTeam": { 
       "ID": "132", 
       "City": "Pittsburgh", 
       "Name": "Pirates", 
       "Abbreviation": "PIT" 
      }, 
      "location": "PNC Park" 
     }, 

     ... 

    ] 
} 

我無法弄清楚如何獲得"gameentry"陣列。我正在尋找其他線索的指導,但它不適合我。繼承人是我到目前爲止有:

JSONObject obj = new JSONObject(todaysGames); 
    String pageName = obj.getJSONObject("dailygameschedule").getString("lastUpdatedOn"); 



    System.out.println("2 asdfasdf "+ pageName); 


    JSONArray arr = obj.getJSONArray("gameentry"); 
    for (int i = 0; i < arr.length(); i++) 
    { 
     //String post_id = arr.getJSONObject(i).getString("id"); 
     System.out.println(arr.getJSONObject(i).getString("awayTeam.ID")); 
    } 

有錯誤即時得到的是:在線程 「主要」 org.json.JSONException

例外: 的JSONObject [ 「gameentry」]沒有找到。

謝謝!

+1

這不是有效的JSON – khelwood

+3

但如果它是有效的JSON,你必須得到'''''''''''''''''''''''''的對象,然後從中得到''gameentry'''。 – khelwood

回答

2

試試這個,

JSONArray arr=obj.getJSONObject("dailygameschedule").getJSONArray("gameentry"); 
for (int i = 0; i < arr.length(); i++) 
{ 
    JSONObject obj = arr.getJSONObject(i); 
    String id = obj.getString("id"); 

    JSONObject awayTeam_obj=obj.getJSONObject("awayTeam"); 
    String awayTeam_ID = awayTeam_obj.getString("ID"); 
    String awayTeam_City = awayTeam_obj.getString("City"); 
    String awayTeam_Name = awayTeam_obj.getString("Name"); 

    JSONObject homeTeam_obj=obj.getJSONObject("homeTeam"); 
    String homeTeam_ID = homeTeam_obj.getString("ID"); 
    String homeTeam_City = homeTeam_obj.getString("City"); 
    String homeTeam_Name = homeTeam_obj.getString("Name"); 

} 
+0

這很好。如果試圖訪問「離開團隊」內的某個元素,我該怎麼做? –

+0

@DeanAllen檢查更新代碼 – user2025187

+0

@ user2025187你能幫我解決這個問題嗎? https://stackoverflow.com/questions/44275601/display-the-list-of-events-within-the-calendar – seon

0

gameentry陣列是dailygameschedule對象的成員,所以你需要先訪問它。

JSONArray arr = obj.getJSONObject("dailygameschedule").getJSONArray("gameentry"); 
    for (int i = 0; i < arr.length(); i++) 
    { 
     //String post_id = arr.getJSONObject(i).getString("id"); 
     System.out.println(arr.getJSONObject(i).getString("awayTeam.ID")); 
    } 
0

這不是一個有效的JSON對象,只需添加「}」和gameentry不是根元素,你應該得到dailygamesschedule,然後再拿到gameentry