org.json.JSONObject$1 类型的值 null 无法转换为 JSONObject

新手上路,请多包涵

使用 OpenWeatherMap API 时出现此异常错误。我只是试图让 结果 成为一个 JSONObject,但 null 不断出现。

 @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        // What's coming in as result...
        // Printed to the console...
        // null{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":800,"main":"Clear",
        // "description":"clear sky","icon":"01d"}],...}

        try {
            JSONObject jsonObject = new JSONObject(result);
            String weatherInfo = jsonObject.getString("weather");

            Log.i("Weather Info", weatherInfo);
        } catch (JSONException e) {
            e.printStackTrace();
        }

   }

JSON 数据很好,但我只想让它成为一个 JSONObject,但 null 部分正在捕获。任何想法为什么会发生?

同样来自该站点的 JSON Response 进来的是:

 {"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],.....}

为什么一开始没有空值?谢谢您的帮助。

原文由 SmiffyKmc 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

在您收到的数据中, 天气 是一个 JSONArray。

试试这个 :

  String json = "{\"coord\":{\"lon\":-0.13,\"lat\":51.51},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01d\"}],.....}";

try{
    JSONObject jo = new JSONObject(json);
    JSONArray weather = jo.getJSONArray("weather");
    for(int i = 0;i < weather.length(); i++){
        JSONObject w = weather.getJSONObject(i);
        String main = w.getString("main");
        String description = w.getString("description");
        //...
    }
}catch (Exception e){

}

如您所说,如果服务器返回的结果以 null 开头,您将遇到此异常 org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject

这是因为此结果不是有效的 JSON 内容。

如果您确实从服务器收到此无效内容,解决方法是在解析 JSON 之前删除 null

 String crappyPrefix = "null";

if(result.startsWith(crappyPrefix)){
    result = result.substring(crappyPrefix.length(), result.length());
}
JSONObject jo = new JSONObject(result);

原文由 Guillaume Barré 发布,翻译遵循 CC BY-SA 3.0 许可协议

有时问题是您的响应为空,但您期望的是 JSONObject。最好在服务器端解决它。如果您不能编辑服务器端代码, 这个问题这个 问题可能会有用

原文由 masoud jafari 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题