【发布时间】:2019-06-10 05:44:30
【问题描述】:
你好 :) 我正在编写一个显示今天和明天天气的电报机器人。作为数据,我使用的是 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”的数据块,并获取有关温度、湿度、风等的信息。 每个块都以 ""dt": 1547672400" 开头。我认为这意味着不同格式的日期和时间。如果是这样,我需要找到正确的块并跳过另一个。
不幸的是我不知道如何实现这个方法。 如果有人可以帮助我,我将非常感激:)
【问题讨论】:
-
您应该正确阅读 API 文档,他们似乎有一个端点要求进行 5 天预测
-
API Docs 看起来很清楚:openweathermap.org/forecast5#JSON -
list.dt Time of data forecasted, unix, UTC -
你似乎知道如何解析 JSON - 这个特定结构到底有什么问题?
-
我确实读过它。不知道怎么写代码找到“明天13:00”
-
dt是 UTC 的 unix 时间。如果您不知道那是什么,请查找unix time
标签: java json datetime openweathermap