org.json.JSONException:数组中没有值
StringRequest req = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
try {
questionsList = new ArrayList<QuestionsBean>();
JSONObject jsonObject = new JSONObject(s);
JSONArray question = jsonObject.getJSONArray("questions");
for (int i = 0; i < question.length(); i++) {
JSONObject x = question.getJSONObject(i);
QuestionsBean u = new QuestionsBean();
u.setDate(x.getString("date"));
u.setQuestion(x.getString("question_text"));
JSONObject bject = new JSONObject();
JSONArray answers = bject.getJSONArray("answers");
for (int j = 0; j < answers.length(); j++) {
JSONObject xx = answers.getJSONObject(i);
u.setAnswer_body(xx.getString("Answer_body"));
}
questionsList.add(u);
答案 0 :(得分:3)
您没有在正确的getJSONArray
上致电JSONObject
。使用
JSONArray answers = x.getJSONArray("answers");
此外,由于您的JSONArray
可能为null,请使用optJSONArray
来避免异常,并在继续之前检查它是否为空。
像
这样的东西JSONArray answers = x.optJSONArray("answers");
if (answers != null) {
// for loop
}
答案 1 :(得分:1)
JSONObject bject = new JSONObject();
JSONArray answers = bject.getJSONArray("answers");
你在这里建造了一个空的JSONObject,所以在它里面找不到'答案'是正常的。