解析WunderGround API天气JSON数据时捕获异常求助
问题排查与修复方案
我帮你找出了解析代码里的两个核心问题,这就是触发异常的原因:
错误点分析
- 把对象当成数组处理了:看你提供的API返回数据,
current_observation是一个JSON对象(用{}包裹),但你的代码里却用getJSONArray("current_observation")去获取它,这肯定会抛出类型不匹配的异常。 - 字段获取逻辑错误:
temp_c是current_observation下面的直接数值字段,不是嵌套的JSON对象,所以你不需要再调用getJSONObject去获取它,直接读取这个字段的值就行。
修正后的解析函数
public String getTemperature(String weatherData) { String temperature = null; try { JSONObject parentObject = new JSONObject(weatherData); // 获取current_observation这个对象,而非数组 JSONObject currentObservation = parentObject.getJSONObject("current_observation"); // 直接读取temp_c字段,转为字符串返回 temperature = String.valueOf(currentObservation.getDouble("temp_c")); } catch (Exception e) { e.printStackTrace(); } return temperature; }
拓展:获取其他参数的示例
如果要获取其他天气参数,比如湿度、体感温度,都可以用类似的方式从currentObservation对象中直接读取:
// 获取相对湿度 String humidity = currentObservation.getString("relative_humidity"); // 获取体感温度(摄氏度) String feelsLikeC = currentObservation.getString("feelslike_c");
内容的提问来源于stack exchange,提问作者Viral Parmar
相关产品推荐
相关产品推荐

