JAvaは天気情報(和風無料api)を取得しjsonを解析する
12109 ワード
Gsonとlombokのmavenの依存を追加する必要があります
//
private static WeatherReportInfo getTodayWeather(String cityName)
throws IOException {
// API
String url1= "https://free-api.heweather.net/s6/weather/now?location="+cityName+"&key=3c3fa198cacc4152b94b20def11b2455";
URL url = new URL(url1);
URLConnection connectionData = url.openConnection();
connectionData.setConnectTimeout(1000);
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(
connectionData.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
String json = sb.toString();
// google Gson , fastJson , fastJson
// api json "{"HeWeather6": "xxxx"}"
WeatherReportInfo weatherReportInfo = new Gson().fromJson(json, WeatherReportInfo.class);
return weatherReportInfo;
} catch (SocketTimeoutException e) {
log.error(" ");
throw new RuntimeException(" ");
}finally {
IOUtils.closeQuietly(br);
}
}
@Data
public class WeatherReportInfo {
private List<Weather> HeWeather6;
}
@Data
public class Weather {
private Basic basic;
private Update update;
private Now now;
private String status;
@Data
public static class Basic {
// / ID
private String cid;
// /
private String location;
// /
private String parent_city;
// /
private String admin_area;
// /
private String cnty;
// /
private String lat;
// /
private String lon;
// /
private String tz;
}
@Data
public static class Update {
// ,24 , yyyy-MM-dd HH:mm
private String loc;
//UTC ,24 , yyyy-MM-dd HH:mm
private String utc;
}
@Data
public static class Now {
private String cloud;
//
private String cond_code;
//
private String cond_txt;
// , :
private String fl;
//
private String hum;
//
private String pcpn;
//
private String pres;
// , :
private String tmp;
// , :
private String vis;
// 360
private String wind_deg;
//
private String wind_dir;
//
private String wind_sc;
// , /
private String wind_spd;
}
}