繁体   English   中英

通过JSON 5天天气预报获取有关明天天气的数据

[英]Get data about tomorrow's weather from JSON 5 days forecast

您好:)我正在写一个电报机器人,该机器人显示今天和明天的天气。 作为数据,我正在使用openweathermap.org。

现在,我做了getTodaysWeather方法,该方法从http://www.jsonschema2pojo.org上的 JSON获取有关Java对象的信息,并写成这样:

public class Weather {

    public static final String URL_SOURCE = "http://api.openweathermap.org/data/2.5/weather?q=";
    public static final String API_KEY = "&APPID=3ad54740fd37f3f14a3a32a09f09cd25";
    public static final String UNITS = "&units=metric";
    public static final String LANG = "&lang=ru";

    public static String getWeather(String message) throws IOException{

        URL url = new URL(URL_SOURCE + message + LANG + UNITS + API_KEY);

        InputStreamReader reader = new InputStreamReader(url.openStream());

        Scanner in = new Scanner((InputStream) url.getContent());
        String result = "";

        while (in.hasNext()) {
            result += in.nextLine();
        }

        OneDayWeather obj = null;
        Gson gson = new Gson();
        String json = result;

        obj = gson.fromJson(json, OneDayWeather.class);

        System.out.println("City " + obj.getName() + "(" + obj.getSys().getCountry()+ ")" + "today's "+ System.lineSeparator() +
                "Temperature: " + obj.getMain().getTemp() + "°C, " + System.lineSeparator()+
                "Humidity: " + obj.getMain().getHumidity() + "%, " + System.lineSeparator()+
                "Rain: " + obj.getWeather().get(0).getDescription()+ System.lineSeparator()+
                "Wind speed: " + obj.getWind().getSpeed() + " m/s";
    }
}

现在,我需要编写一种从JSON数据中获取明天天气数据的方法http://api.openweathermap.org/data/2.5/forecast?q=London&APPID=21f2aefa331b0d3f72e50b14a06ff983如果我认为正确,我需要在数据中找到该块日期接近“明天1:00 pm”,并获取有关温度,湿度,风等的信息。每个块都以““ dt”开头:1547672400”。 我认为这意味着日期和时间的格式不同。 如果是这样,我需要找到正确的块并跳过其他块。

不幸的是,我不知道如何实现这种方法。 如果有人可以帮助我,我将非常感激:)

您可以做的是 “明天1:00 pm”转换为UTC,然后转换为unix时间戳。 将此值存储为tomorrow13Unix

现在,对于列表中的每个预测,您都可以将其与tomorrow13Unix进行比较,如果相同,则可以找到所需的内容。

请注意 ,API将时间分为三部分,因此您可能希望查找大于tomorrow13Unix的最大时间。


这是我如何获取明天下午1点的纪元时间:

long tomorrow13Unix = java.time.OffsetDateTime.now(java.time.ZoneOffset.UTC).with(java.time.LocalTime.of(13, 0)).plusDays(1).toEpochSecond();

注意

上面的代码将获得UTC的当前时间,将该时间截断为下午1点,然后添加一天。 这可能不是您想要的。 您可能要改用本地时间,将其添加一天,将其截断为下午1点,然后将结果转换为UTC,在这种情况下,您可能要改用此时间:

long tomorrow13Unix = java.time.LocalDateTime.now().plusDays(1).with(java.time.LocalTime.of(13, 0)).toEpochSecond(java.time.ZoneOffset.UTC);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM