Java之呼叫天氣API及解析JSON資料
1.構造一個天氣的模型(類)
public class WeatherInfo { private String date;//時間 private String cityname;//城市名 private String weather;//天氣 private String temperature;//氣溫 private String airquality;//pm2.5 public 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; } @Override public String toString() { return "WeatherInfo [date=" + date + ", cityname=" + cityname + ", weather=" + weather + ", temperature=" + temperature + ", airquality=" + airquality + "]"; } }
2.編寫通過天氣API獲取天氣資訊和解析資料的的方法類
3.測試類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 block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.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; } }
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]