【发布时间】:2019-07-10 21:03:55
【问题描述】:
我遇到了一些麻烦,因为我在学习如何用简单的 json 解析 JSON 时遇到了障碍。
为了让自己简洁;
我正在尝试从 url 解析这段 JSON
"hourly": {
"summary": "Clear throughout the day.",
"icon": "clear-day",
"data": [
{
"time": 1550379600,
"summary": "Clear",
"icon": "clear-day",
"precipIntensity": 0,
"precipProbability": 0,
"temperature": 20.18,
"apparentTemperature": 14.31,
"dewPoint": 13.79,
"humidity": 0.76,
"pressure": 1024.47,
"windSpeed": 4.08,
"windGust": 5.25,
"windBearing": 30,
"cloudCover": 0.07,
"uvIndex": 0,
"visibility": 10,
"ozone": 342.67
}
所以,在使用简单的 json 时,这就是我解析这个 JSON 的方式
try{
String genreJson = IOUtils.toString(new URL(url));
JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
//get the title
System.out.println(genreJsonObject.get("hourly")); //THIS WORKS
//System.out.println(genreJsonObject.get("visibility"));
//get the data
JSONArray genreArray = (JSONArray) genreJsonObject.get(0);
//get the first genre
//JSONObject firstGenre = (JSONObject) genreArray.get(0);
//System.out.println(firstGenre.get("data"));
}
catch (IOException | ParseException e){
e.printStackTrace();
}
所以,在调用System.out.println(genreJsonObject.get("hourly")); 时,我得到了标题为“每小时”的括号内的所有内容。我的意图是解析“每小时”括号内的数据,尽管我不知道如何解析带标题的括号内的标题。具体来说,我需要时间、precipProbability、precipIntensity 和 precipProbability(示例中没有这个属性)。
对于任何缺乏细节,我深表歉意,因为这是我第一次黑客马拉松的一部分,而且我现在正努力避免睡着。
非常感谢任何人的帮助。
【问题讨论】:
-
如果你创建一个Java POJO并将Json映射到Java类(例如使用Jackson),然后在Java类上调用相应的方法,不是更简单吗?
-
我会调查一下并试一试
标签: java json api parsing weather-api