我正在尝试使用Android和Java构建一个简单的天气预报应用程序。我按照这里的一些说明(https://www.androdocs.com/java/creating-an-android-weather-app-using-java.html)来启动和运行,这是可行的。然而,我只能了解当前的天气。开放天气预报API调用似乎要持续5天。没关系,但我如何获得天气--比如温度和风速--在未来5天内由用户指定的特定日期?
下面是一个示例JSON响应(缩写)。即使我可以在晚上12点左右提取特定日期的信息,并获得那个日期的温度和风速,那也就足够了。如何解析这个JSON响应以获得特定日期的温度和风速?非常感谢..。抱歉我是初学者..。
{“cod”:"temp_min":281.68,"temp_max":281.75,“压力”:995,"sea_level":995,"grnd_level":980,“湿度”:93,"temp_kf":0.07},“天气”:{“id”:501,“主”:“雨”,“描述”:“中雨”,“图标”:“10n”},“云”:{“所有”:100},“风”:{“速度”:4.82,"deg":147},“雨”:{“3h”:5.38},"sys":{"pod":"n"},“dt_txt”:“2019-11-2021:00”},{"dt":1574294400,“主要”:{“临时”:281.79,"temp_min":281.74,"temp_max":281.79,“气压”:995,"sea_level":995,"grnd_level":980,“湿度”:91,“temp_kf”:281.79},“天气”:{“id”:500,“主”:“雨”,“描述”:“小雨”,“图标”:“10n”},“云”:{“全部”:100},“风”:{“速度”:5.55,“德格”:140},“雨”:{“3h”:1.75},"sys":{"pod":"n"},"dt_txt":"2019-11-21 00:00:00"},{"dt":1574305200,“主”:{“temp”:279.48,"temp_min":279.44,"temp_max":279.48,“气压”:994,"sea_level":994,"grnd_level":980,“湿度”:95,"temp_kf":0.04},“天气”:{“id”:500,“主”:“雨”,“描述”:“小雨”,“图标”:“10n”},“云”:{“所有”:100},“风”:{“速度”:2.37,"deg":155},“下雨”:{“3h”:0.94},"sys":{"pod":"n"},"dt_txt":"2019-11-21 03:00“},{"dt":1574316000,”主“:{”temp“:278.56,"temp_min":278.54,"temp_max":278.56,”压力“:995,"sea_level":995,"grnd_level":980,”湿度“:94,"temp_kf":0.02}、“天气”:{“id”:500、“主”:“雨”、“描述”:“小雨”、“图标”:“10n”}、“云”:{“所有”:100}、“风”:{“速度”:1.73、"deg":128}、“雨”:{“3h”:0.06}、"sys":{"pod":"n"},"dt_txt":"2019-11-21 06:00:00"},{"dt":1574326800,{“temp”:279.19,"temp_min":279.19,"temp_max":279.19,“压力”:995,"sea_level":995,"grnd_level":981,“湿度”:95,"temp_kf":0},“天气”:{“id”:804,“主”:“Clouds”,“描述”:“阴云”、“图标”:“04d”}、“云”:{“所有”:100}、“风”:{“速度”:1.79、"deg":104}、"sys":{"pod":"d"}、"dt_txt":"2019-11-21 09:00:00"}、{"dt":1574337600、"main":{"temp":282.2、"temp_min":282.2,"temp_max":282.2、“气压”:995、"sea_level":995、"grnd_level":980、“湿度”:85、"temp_kf":0}、“天气”:{“id”:500、“主”:“雨”、“描述”:“小雨”、“图标”:“10d”}、“云”:{“所有”:100}、“风”:{“速度”:2.78、"deg":129},“下雨”:{“3h”:0.19},"sys":{"pod":"d"},"dt_txt":"2019-11-21 12:00:00"}
发布于 2019-11-21 01:02:34
您可以通过任何一个最流行的JSON库(如Jackson或Gson )将响应JSON字符串序列化为POJO,然后检索日期字段等于给定日期的对象的字段。顺便说一句,您的JSON字符串是无效的,它的末尾缺少]}。
POJOs
@JsonIgnoreProperties(ignoreUnknown = true)
class Response {
List<Weather> list;
//general getters and setters
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Weather {
JsonNode main;
JsonNode wind;
@JsonProperty("dt_txt")
String dtTxt;
//general getters and setters
}使用@JsonIgnoreProperties (由杰克逊提供)忽略那些您在序列化时不关心的字段。
代码片段
ObjectMapper mapper = new ObjectMapper();
Response response = mapper.readValue(jsonStr, Response.class);
String givenDate = "2019-11-21 12:00:00";
response.getList().forEach(e -> {
if (givenDate.equals(e.getDtTxt())) {
System.out.println("temp: " + e.getMain().get("temp").asText());
System.out.println("wind speed:" + e.getWind().get("speed").asText());
}
});控制台输出
温度: 282.2 风速:2.78
发布于 2019-11-21 02:35:43
简简单单
下面是一个使用https://code.google.com/archive/p/json-simple/库解析从OpenWeatherMap.org下载的JSON数据的示例应用程序。
package work.basil.example;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Weather
{
public static void main ( String[] args )
{
Weather app = new Weather();
app.demo();
}
private void demo ( )
{
//Creating a JSONParser object
JSONParser jsonParser = new JSONParser();
try
{
// Download JSON.
String yourKey = "b6907d289e10d714a6e88b30761fae22";
URL url = new URL( "https://samples.openweathermap.org/data/2.5/forecast/hourly?zip=79843&appid=b6907d289e10d714a6e88b30761fae22" + yourKey ); // 79843 = US postal Zip Code for Marfa, Texas.
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
// Parse JSON
JSONObject jsonObject = ( JSONObject ) jsonParser.parse( reader );
System.out.println( "jsonObject = " + jsonObject );
JSONArray list = ( JSONArray ) jsonObject.get( "list" );
System.out.println( "list = " + list );
// Loop through each item
for ( Object o : list )
{
JSONObject forecast = ( JSONObject ) o;
Long dt = ( Long ) forecast.get( "dt" ); // Parse text into a number of whole seconds.
Instant instant = Instant.ofEpochSecond( dt ); // Parse the count of whole seconds since 1970-01-01T00:00Z into a `Instant` object, representing a moment in UTC with a resolution of nanoseconds.
ZoneId z = ZoneId.of( "America/Chicago" ); // Specify a time zone using a real `Continent/Region` time zone name. Never use 2-4 letter pseudo-zones such as `PDT`, `CST`, `IST`, etc.
ZonedDateTime zdt = instant.atZone( z ); // Adjust from a moment in UTC to the wall-clock used by the people of a particular region (a time zone). Same moment, same point on the timeline, different wall-clock time.
LocalTime lt = zdt.toLocalTime() ;
// … compare with lt.equals( LocalTime.NOON ) to find the data sample you desire.
System.out.println( "dt : " + dt );
System.out.println( "instant : " + instant );
System.out.println( "zdt : " + zdt );
JSONObject main = ( JSONObject ) forecast.get( "main" );
System.out.println( "main = " + main );
Double temp = ( Double ) main.get( "temp" ); // Better to use BigDecimal instead of Double for accuracy. But I do not know how to get the JSON-Simple library to parse the original string input as a BigDecimal.
System.out.println( "temp = " + temp );
JSONObject wind = ( JSONObject ) forecast.get( "wind" );
System.out.println( "wind = " + wind );
System.out.println( "BASIL - wind.getCLass: " + wind.getClass() );
Double speed = ( Double ) wind.get( "speed" );
System.out.println( "speed = " + speed );
System.out.println( "\n" );
}
}
catch ( FileNotFoundException e )
{
e.printStackTrace();
}
catch ( IOException e )
{
e.printStackTrace();
}
catch ( ParseException e )
{
e.printStackTrace();
}
}
}十进制分隔符
注意,当遇到没有十进制分隔符的风速数据点时,这段代码就会爆炸。例如,该数据的发布者应该编写1.0而不是1来实现一致性。如果他们这样做了,库就会将1.0解析为Double,而不是将1解析为Long。
JSON-Simple 1现已失效。
另外,这段代码使用了JSON的原始版本1--简单,现在已经失效了。这个项目是分叉的,产生了截然不同的版本2和3。
有关解析-十进制问题和指向https://stackoverflow.com/q/58964542/642706的链接的详细信息,请参见此页面分叉工程。
不用于生产用途
因此,虽然我不建议在生产中使用来使用,但它可能会对您有帮助。对于实际工作,请考虑JSON的后期版本3--简单或其他几个可用于Java的JSON处理库中的任何一个。
参见这个URL中的示例数据。要使其可读性,可以使用文本编辑器或IDE重新格式化JSON数据。
样本输出:
dt : 1553709600
instant : 2019-03-27T18:00:00Z
zdt : 2019-03-27T13:00-05:00[America/Chicago]
main = {"temp":286.44,"temp_min":286.258,"grnd_level":1002.193,"temp_kf":0.18,"humidity":100,"pressure":1015.82,"sea_level":1015.82,"temp_max":286.44}
temp = 286.44
wind = {"deg":202.816,"speed":5.51}
speed = 5.51
dt : 1553713200
instant : 2019-03-27T19:00:00Z
zdt : 2019-03-27T14:00-05:00[America/Chicago]
main = {"temp":286.43,"temp_min":286.3,"grnd_level":1002.667,"temp_kf":0.13,"humidity":100,"pressure":1016.183,"sea_level":1016.183,"temp_max":286.43}
temp = 286.43
wind = {"deg":206.141,"speed":4.84}
speed = 4.84https://stackoverflow.com/questions/58962911
复制相似问题