[英]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.