Java json rest API';s错误:ClassCastException:org.json.JSONObject无法强制转换为org.json.JSONArray
我是编程的初学者 因此,我有一个API的响应:Java json rest API';s错误:ClassCastException:org.json.JSONObject无法强制转换为org.json.JSONArray,java,json,Java,Json,我是编程的初学者 因此,我有一个API的响应: { "status": 404, "error": "Postcode not found" } 这是我的代码,只返回特定邮政编码的国家和地区 while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); break; } JSONObject jsObject = new JSONObject(stringBui
{
"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");
}
while((line=bufferedReader.readLine())!=null){
stringBuilder.append(行);
打破
}
JSONObject jsObject=新的JSONObject(stringBuilder.toString());
JSONArray JSONArray=(JSONArray)jsObject.get(“结果”);
output.append(“的详细信息”).append(邮政编码).append(“是:\n”);
if(jsonArray.length()!=0){
for(int i=0;i
我的代码显示错误:
ClassCastException:org.json.JSONObject不能强制转换为
org.json.JSONArray
jsObject.get(“result”);
是一个对象而不是数组,所以下面的行将抛出类强制转换异常
JSONArray jsonArray = (JSONArray) jsObject.get("result");
你的评论中的JSON
{
"status": 200,
"result": {
"postcode": "L6 6DG",
"quality": 1,
"eastings": 337113,
"northings": 391146,
"country": "England",
"nhs_ha": "North ...
}
}
这条线应该是
JSONObject result = jsObject.getJsonObject("result");
您的API响应没有国家或地区。它给您404。请查看链接,我的意思是如果您输入正确的邮政编码,API响应会给出{“状态”:200,“结果”:{“邮政编码”:“L6 6DG”,“质量”:1,“东庭”:337113,“北庭”:391146,“国家”:“英格兰”,“nhs_ha”:“北…”