java解析json天气api_java 解析天气预报返回 json 字符串 HeWeather data service 3.0

这篇博客介绍了如何使用Java解析HeWeather API获取的JSON天气预报数据。首先调用API获取JSON字符串,然后利用JSONObject和JSONArray进行解析,提取所需信息如天气状况、温度等,并存储到结果字符串中。
摘要由CSDN通过智能技术生成

通过调用一个百度 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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值