JSON org.json.JSONException:" NAME"没有值

时间:2016-05-09 23:34:31

标签: android arrays json

我在尝试从JSON文件中获取信息时遇到错误。我正在尝试从'帖子中获取数据,例如' NAME'年份'等,并将其打印到日志。它一直告诉我org.json.JSONException: No value for 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")); 

1 个答案:

答案 0 :(得分:1)

正如您所证明的,这有效:

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

这意味着当你获得jsonPart对象时,第一个级别是&#34; post&#34;对象(这是多余的)。所以你需要再次操作

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

然后

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