json rest API的错误:ClassCastException:org.json.JSONObject无法强制转换为org.json.JSONArray

时间:2017-04-14 13:31:32

标签: java 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无法强制转换为   org.json.JSONArray

1 个答案:

答案 0 :(得分:0)

jsObject.get("result");是一个Object而不是一个数组,因此跟随行将抛出类强制转换异常。

JSONArray jsonArray = (JSONArray) jsObject.get("result"); 

评论中的JSON

{
    "status": 200,
    "result": {
        "postcode": "L6 6DG",
        "quality": 1,
        "eastings": 337113,
        "northings": 391146,
        "count‌​ry": "England",
        "nhs_h‌​a": "North ...
    }
}

此行应为

JSONObject result = jsObject.getJsonObject("result");