【发布时间】:2016-06-26 13:04:41
【问题描述】:
我正在尝试从 WeatherUnderground API 获取天气预报数据。
到目前为止,我正在使用以下代码:
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5000);
connection.connect();
JsonParser jp = new JsonParser();
JsonElement forecastJson = jp.parse(new InputStreamReader((InputStream) connection.getContent())).getAsJsonObject()
.getAsJsonObject().get("forecast")
.getAsJsonObject().get("simpleforecast")
.getAsJsonObject().getAsJsonArray("forecastday").get(1);
System.out.println("forecastJson = " + forecastJson.toString());
String date = String.valueOf(jp.parse(forecastJson
.getAsJsonObject().get("date")
.getAsJsonObject().get("epoch").getAsString()));
String high = String.valueOf(jp.parse(forecastJson
.getAsJsonObject().get("high")
.getAsJsonObject().get("celsius").getAsString()));
String low = String.valueOf(jp.parse(forecastJson
.getAsJsonObject().get("low")
.getAsJsonObject().get("celsius").getAsString()));
String conditions;
try {
conditions = String.valueOf(jp.parse(forecastJson
.getAsJsonObject().get("conditions").getAsString()));
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
我收到的 JsonElement forecastJson" 看起来像这样:
{
"date": {
"epoch": "1467046800",
"pretty": "7:00 PM CEST on June 27, 2016",
"day": 27,
"month": 6,
"year": 2016,
"yday": 178,
"hour": 19,
"min": "00",
"sec": 0,
"isdst": "1",
"monthname": "June",
"monthname_short": "Jun",
"weekday_short": "Mon",
"weekday": "Monday",
"ampm": "PM",
"tz_short": "CEST",
"tz_long": "Europe/Berlin"
},
"period": 2,
"high": {
"fahrenheit": "77",
"celsius": "25"
},
"low": {
"fahrenheit": "58",
"celsius": "14"
},
"conditions": "Partly Cloudy",
"icon": "partlycloudy",
"icon_url": "http://icons.wxug.com/i/c/k/partlycloudy.gif",
"skyicon": "",
"pop": 0,
"qpf_allday": {
"in": 0,
"mm": 0
},
"qpf_day": {
"in": 0,
"mm": 0
},
"qpf_night": {
"in": 0,
"mm": 0
},
"snow_allday": {
"in": 0,
"cm": 0
},
"snow_day": {
"in": 0,
"cm": 0
},
"snow_night": {
"in": 0,
"cm": 0
},
"maxwind": {
"mph": 15,
"kph": 24,
"dir": "W",
"degrees": 260
},
"avewind": {
"mph": 11,
"kph": 18,
"dir": "W",
"degrees": 260
},
"avehumidity": 48,
"maxhumidity": 0,
"minhumidity": 0
}
我能够获得“日期”、“高”和“低”字符串,但我无法获得“条件”,而且我不明白我做错了什么。
我收到以下异常:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON
据我了解,JSON 没有格式错误。我应该如何获得“条件”值?
我也尝试过其他 JSON 解析器/库,但没有成功。我想继续使用 Gson-Library,我想我已经很接近了,但是卡住了。
感谢您的帮助。
【问题讨论】:
-
顺便说一句,异常说“使用 JsonReader.setLenient(true) 接受格式错误的 JSON”,但就像我写的那样,我没有看到 JSON 格式错误,除此之外我没有创建任何地方的 JsonReader,所以我不知道什么时候可以应用“setLenient(true)。
-
我不明白你的代码。为什么要解析整个 JSON,然后尝试重新解析其所有元素?解析 JSON,然后访问其元素。无需重新解析它们。
-
为什么不为json数据创建一个类并使用
TheClass foo = gson.fromJson(theJson, TheClass.class)然后使用foo? -
@JB Nizet:我是 Java 和 Json 的初学者,所以是的,我实际上认为我每次都需要解析 JSON 以从中获取一些东西。你的问题让我意识到我做错了。感谢您的帮助,我现在也得到了“条件”!
-
@RC.: 好的,我要试试,看起来是个好方法。就像我已经在我的其他评论中写的一样,我是初学者,所以这就是“你为什么不......”的答案:-)