java json rest API的错误:ClassCastException:org。json。无法将JSONObject强制转换为组织。json。杰索纳雷
我是编程的初学者 因此,我有一个API的响应:
{
"status": 404,
"error": "Postcode not found"
}
这是我的代码,只返回特定邮政编码的国家和地区
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
break;
}
JSONObject jsObject = new JSONObject(stringBuilder.toString());
JSONArray jsonArray = (JSONArray) jsObject.get("result");
output.append("The Details for ").append(postcode).append(" are:\n");
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//String region = jsonObject.get("region").toString();
output.append(jsonObject.get("region").toString()).append(", ");
// String country = jsonObject.get("country").toString();
output.append(jsonObject.get("country").toString()).append("\n");
}
我的代码显示错误:
ClassCastException: org.json.JSONObject cannot be cast to org.json.JSONArray
# 1 楼答案
jsObject.get("result");
是一个对象而不是数组,所以下面的行将引发类强制转换异常你的评论中的JSON
这条线应该是