Java之调用天气API及解析JSON数据

来源:互联网 发布:阿国网络随笔博客 编辑:程序博客网 时间:2024/05/12 19:29

1.构造一个天气的模型(类)

public class WeatherInfo {private String date;//时间private String cityname;//城市名private String weather;//天气private String temperature;//气温private String airquality;//pm2.5public String getDate() {return date;}public void setDate(String date) {this.date = date;}public String getCityname() {return cityname;}public void setCityname(String cityname) {this.cityname = cityname;}public String getWeather() {return weather;}public void setWeather(String weather) {this.weather = weather;}public String getTemperature() {return temperature;}public void setTemperature(String temperature) {this.temperature = temperature;}public String getAirquality() {return airquality;}public void setAirquality(String airquality) {this.airquality = airquality;}@Overridepublic String toString() {return "WeatherInfo [date=" + date + ", cityname=" + cityname+ ", weather=" + weather + ", temperature=" + temperature+ ", airquality=" + airquality + "]";}}

2.编写通过天气API获取天气信息和解析数据的的方法类

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import java.net.URLEncoder;import java.util.zip.GZIPInputStream;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import org.junit.Test;/** * 通过get请求向网站http://wthrcdn.etouch.cn/weather_mini获取某个 城市的天气状况数据,数据格式是Json *  * @author 22786 *  */public class WeatherUtils {/** * 通过城市名称获取该城市的天气信息 *  * @param cityName * @return */public  static String GetWeatherData(String cityname) {StringBuilder sb=new StringBuilder();;try {//cityname = URLEncoder.encode(cityName, "UTF-8");String weather_url = "http://wthrcdn.etouch.cn/weather_mini?city="+cityname;URL url = new URL(weather_url);URLConnection conn = url.openConnection();InputStream is = conn.getInputStream();GZIPInputStream gzin = new GZIPInputStream(is);InputStreamReader isr = new InputStreamReader(gzin, "utf-8"); // 设置读取流的编码格式,自定义编码BufferedReader reader = new BufferedReader(isr);String line = null;while((line=reader.readLine())!=null)sb.append(line+" ");reader.close();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}//System.out.println(sb.toString());return sb.toString();}/** * 将JSON格式数据进行解析 ,返回一个weather对象 * @param str * @return */public static WeatherInfo GetWeather(String weatherInfobyJson){JSONObject dataOfJson = JSONObject.fromObject(weatherInfobyJson);if(dataOfJson.getInt("status")!=1000)return null;//创建WeatherInfo对象,提取所需的天气信息WeatherInfo weatherInfo = new WeatherInfo();//从json数据中提取数据String data = dataOfJson.getString("data");dataOfJson = JSONObject.fromObject(data);weatherInfo.setCityname(dataOfJson.getString("city"));;weatherInfo.setAirquality(dataOfJson.getString("aqi"));//获取预测的天气预报信息JSONArray forecast = dataOfJson.getJSONArray("forecast");//取得当天的JSONObject result=forecast.getJSONObject(0);weatherInfo.setDate(result.getString("date"));String high = result.getString("high").substring(2);String low  = result.getString("low").substring(2);weatherInfo.setTemperature(low+"~"+high);weatherInfo.setWeather(result.getString("type"));return weatherInfo;}}


3.测试类

public class Test {public static void main(String[]  args){String info = WeatherUtils.GetWeatherData("武汉");WeatherInfo weatherinfo = WeatherUtils.GetWeather(info);System.out.println(weatherinfo.toString());}}


4.通过天气API获取到的JSON串

{"data":{"yesterday":{"date":"20日星期一","high":"高温 12℃","fx":"无持续风向","low":"低温 3℃","fl":"","type":"晴"},"city":"武汉","aqi":"105","forecast":[{"date":"21日星期二","high":"高温 13℃","fengli":"","low":"低温 6℃","fengxiang":"无持续风向","type":"多云"},{"date":"22日星期三","high":"高温 13℃","fengli":"","low":"低温 4℃","fengxiang":"北风","type":"多云"},{"date":"23日星期四","high":"高温 14℃","fengli":"","low":"低温 3℃","fengxiang":"无持续风向","type":"多云"},{"date":"24日星期五","high":"高温 15℃","fengli":"","low":"低温 3℃","fengxiang":"无持续风向","type":"多云"},{"date":"25日星期六","high":"高温 16℃","fengli":"","low":"低温 4℃","fengxiang":"无持续风向","type":"多云"}],"ganmao":"天凉,昼夜温差较大,较易发生感冒,请适当增减衣服,体质较弱的朋友请注意适当防护。","wendu":"10"},"status":1000,"desc":"OK"}


5.通过解析获得自己所需的数据

WeatherInfo [date=21日星期二, cityname=武汉, weather=多云, temperature= 6℃~ 13℃, airquality=105]