java获取天气信息(和风免费api)并解析json

需要添加下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;
    }
}

你可能感兴趣的:(JAVA)