在Android / Java中循环JSONArray时出现类型错误

时间:2014-11-19 00:48:49

标签: java android arrays json

我想访问海报并在这个JSON sting中循环它。

{"r":
    {"posters":
       [
        {"rev":10,"poster_id":4,"poster_filename":"545397373c2c7","poster_filepath":"\/poster_files\/545397373c2c7","poster_synopsis":"This is the new synopsis for this exquisite poster I have created. You will marvel at its greatness and ask many questions.","poster_title":"Poster A"},
        {"rev":6,"poster_id":7,"poster_filename":"5453b54b83b5f","poster_filepath":"\/poster_files\/5453b54b83b5f","poster_synopsis":"This is a synopsis that is not real. No one can say what this synopsis really means. It is total B.S..","poster_title":"Poster A"}
       ],
"msg":"72 & 2",
"status":"complete"}
}

我有这个将字符串转换为JSONObject:

JSONObject jsonObject = new JSONObject(result);         

JSONObject r = new JSONObject(jsonObject.getString("r"));

JSONArray posters = r.getJSONArray("posters");

Android Studio说“预期数组类型,当我尝试循环海报时找到org.json.JSONArray:

 int arraySize = posters.length();

 TextView myTextView = (TextView) findViewById(R.id.show_download_list);

 for(int i = 0; i < arraySize; i++) {
     myTextView.append(posters[i]);
     myTextView.append("\n");
 }

我没有正确转换对象吗?

1 个答案:

答案 0 :(得分:1)

JSONObject jsonObject = new JSONObject(result);         

JSONObject r = jsonObject.getJSONObject("r");

JSONArray posters = r.getJSONArray("posters");

我更改了 r JSONObject ,以便从名为 r JSONObject 中获取它,而不是调用字符串名为 r ,因为json字符串中的 r 是一个对象

<强>更新

将循环中的第一行更改为myTextView.append(posters.getJSONObject(i).getString("poster_title"));,这将在每个文本视图上打印海报标题。

  • 这里的问题是您将JSON数组作为普通数组处理。