通过调用一个百度 APIStore 里的免费的天气服务接口,获取了某个城市的天气预报的 json 数据。。格式如下
{"HeWeather data service 3.0":[{"daily_forecast":[{"wind":{"dir":"北风","deg":"97","sc":"微风","spd":"4"},"hum":"65","pcpn":"0.2","astro":{"sr":"07:36","ss":"17:03"},"uv":"2","tmp":{"min":"-4","max":"2"},"pop":"83","pres":"1030","date":"2017-01-05","cond":{"code_d":"502","txt_n":"霾","code_n":"502","txt_d":"霾"}...
解析方式如下:
1、 变量 jsonResult 存储了此 json 字符串
String jsonResult = WeatherServe.request(httpUrl, httpArg);
2、 变量 resultSbf 用以存储 解析 结果
StringBuffer resultSbf = new StringBuffer();
3、 把 json 字符串 放到一个在线的解析及格式化工具上,以便查看层次。。
4、 重点是这两句,第一句把字符串转换成 json 对象,第二句把 json 对象转换成数组(去掉了头部无用的 HeWeather data service 3.0 字符)
JSONObject dataJson = new JSONObject(jsonResult);
JSONArray arrayJson = dataJson.getJSONArray("HeWeather data service 3.0");
5、 大家应该能猜到,上面生成的数组,只有一个元素。拿到它。。
JSONObject info = arrayJson.getJSONObject(0);
6、 然后就可以从里面拿数据了。。
// 最简单的就是这个状态了
String status = info.getString("status");
7、 如果是数组,就这样取。。
// 七天预报
JSONArray daily_forecast = info.getJSONArray("daily_forecast");
8、 对象这么取
// 当天天气
JSONObject currWeather = daily_forecast.getJSONObject(0);
9、 一层一层取下去,然后加入到 resultSbf 里去,就可以返回啦
// 阴晴
JSONObject currCond = currWeather.getJSONObject("cond");
String condTxt_n = currCond.getString("txt_n");
String condTxt_d = currCond.getString("txt_d");
resultSbf.append("白天: " + condTxt_d);