使用 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 许可协议
在您收到的数据中, 天气 是一个 JSONArray。
试试这个 :
如您所说,如果服务器返回的结果以
null
开头,您将遇到此异常org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
。这是因为此结果不是有效的 JSON 内容。
如果您确实从服务器收到此无效内容,解决方法是在解析 JSON 之前删除
null
。