2016-05-09 38 views
0

我在嘗試從JSON文件獲取信息時出現錯誤。我試圖從'post'中獲取數據,比如'NAME','YEAR'等,並將其打印到日誌中。它一直告訴我org.json.JSONException: No value for NAME。有人能指引我朝着正確的方向嗎?JSON org.json.JSONException:「NAME」沒有值

JSON實例:

{"posts":[ 
{"post":{"ID":"74", 
    "TOURN_ID":"999", 
    "YEAR":"2016", 
    "START_DATE":"2016-09-07", 
    "END_DATE":"2016-09-18", 
    "DATE_STRING":"September 7th - 18th 2016", 
    "NAME":"2016 Paralympic Games", 
    "ShortName":"2016 Paralympic Games", 
    "TOURN_TYPE":"International"}}, 

{"post":{"ID":"73", 
    "TOURN_ID":"999", 
    "YEAR":"2016", 
    "START_DATE":"2016-06-23", 
    "END_DATE":"2016-06-25", 
    "DATE_STRING":"June 22nd - 23rd 2016", 
    "NAME":"2016 USABA National Goalball Championships", 
    "ShortName":"2016 US Nationals", 
    "TOURN_TYPE":"Domestic"}}, 

{"post":{"ID":"72", 
    "TOURN_ID":"999", 
    "YEAR":"2016", 
    "START_DATE":"2016-05-12", 
    "END_DATE":"2016-05-14", 
    "DATE_STRING":"May 12th-14th 2016", 
    "NAME":"2016 USABA Western Regional Goalball Tournament", 
    "ShortName":"2016 Utah", 
    "TOURN_TYPE":"Domestic"}} 
]} 

這裏是我的Java:

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

    try { 
     JSONObject jsonObject = new JSONObject(result); 

     String tournInfo = jsonObject.getString("posts"); 

     Log.i("Tourn Info", tournInfo); // displays correctly 

     JSONArray arr = new JSONArray(tournInfo); 

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


      JSONObject jsonPart = arr.getJSONObject(i); 

      String name = jsonPart.optString("NAME"); 

      Log.i("Each Tournament Object", jsonPart.getString("post"));// Work correctly displays all the 'post' items 

這是我得到我的錯誤:

Log.i("Name of Tournament", jsonPart.getString("NAME")); 
+0

JSONArray ARR =新JSONArray(jsonObject.getJSONArray( 「上崗」));並刪除toudnInfo行.---編輯。對不起,它實際上是:JSONObject jsonPart = arr.getJSONObject(i).getJSONObject(「post」); – Guardanis

回答

1

正如你已經證明,這個工程:

Log.i("Each Tournament Object", jsonPart.getString("post")); 

這意味着當你得到你的jsonPart對象時,第一個級別是「post」對象(這是多餘的)。所以,你需要運行另一個層面下來

JSONObject jsonObjectPost = jsonPart.getObject("post"); 

然後

Log.i("Name of Tournament", jsonObjectPost.getString("NAME")); 
+0

工作!非常感謝你! – Tornado973

相關問題