如果 JSON 中没有我们存在的项目,如何显示祝酒词?



当JSON为空时显示此错误:org.json.JSONException: 答案列表没有值

{
"answerList": [
{
"id": 117,
"edu_forum_id": 167,
"edu_forum_answer_id": 0,
"answer": "cvf",
"attachment": "https://testapi.ourschoolzone.org/uploads/upload_eafd8dec-8237-43f0-ae83-7ad05df6209f_cropped6342785145197935935.jpg",
"answerdate": "31/08/2019 04:32 PM",
"school_id": "142388",
"school_name": "Demo-Irvine High School",
"school_address": "Panbazar, Guwahati, Assam",
"school_logo": "http://test.ourschoolzone.org/Upload/9873c7ee-1542-4b42-ba17-771d0b99f26f.png",
"parent_id": "3916",
"parent_name": "Intiaz Khan",
"parent_profile_image": "https://admin.ourschoolzone.org/Images/male_icon.png",
"teacher_id": "",
"teacher_name": "",
"teacher_profile_image": "https://test.ourschoolzone.org/Upload/a0ae18da-940b-47ee-86b1-b159318a0cd6.jpg"
},

这是使用Volley的StringRequest。我正在获取列表视图中的所有详细信息

try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
Log.e("ResponSe",response);

//we have the array named hero inside the object
//so here we are getting that json array
JSONArray heroArray = obj.getJSONArray("answerList");

//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject heroObject = heroArray.getJSONObject(i);

//creating a hero object and giving them the values from json object
ViewAnswersModel hero = new ViewAnswersModel(heroObject.getString("answer"),
heroObject.getString("answerdate"),
heroObject.getString("school_name"),
heroObject.getString("school_logo"),
heroObject.getString("attachment"));



//adding the hero to herolist
heroList.add(hero);
}

**

我如何显示没有找到条目的祝酒词!

**

使用 try catch 处理异常,并在catch块中预制 Toast。

try {
// attempt to parse json
} catch(JSONException exception) {
Toast.makeText(this, "No response from server", Toast.LENGTH_LONG).show();
}  

这样做:-

JSONObject parentObject = new JSONObject(response);
JSONArray jsonArray = parentObject.getJSONArray("answerList");
if (jsonArray.length() == 0) {
// No Data
}else{
//have data
}

最新更新