org.json.JSONException: JSONObject[ "weather" ] 不是字符串



我目前正在使用 https://openweathermap.org/api 的天气API,我正在尝试将JSON页面转换为可打印的字符串。更具体地说。我试图打印出"天气"数组作为键,但它不起作用:


import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) throws ParseException, org.json.simple.parser.ParseException {
String URL = "http://api.openweathermap.org/data/2.5/weather?q=miami&appid=2550e0628a9e7428e4ef85626feb1c95";
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet getURL = new HttpGet(URL);
try {
CloseableHttpResponse response1 = httpclient.execute(getURL);
HttpEntity entity = response1.getEntity();
JSONObject json = new JSONObject(EntityUtils.toString(entity));
json.getString("weather");
} catch (IOException e) {
System.out.println("Failed");
}
}
}

JSONObject 结构是这样的:

"coord": {
"lon": -80.19,
"lat": 25.77
},
"weather": [{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04n"
}],
"base": "stations",
"main": {
"temp": 301.17,
"feels_like": 303.16,
"temp_min": 300.93,
"temp_max": 301.48,
"pressure": 1018,
"humidity": 74
},
"visibility": 16093,
"wind": {
"speed": 4.6,
"deg": 80
},
"clouds": {
"all": 90
},
"dt": 1591061650,
"sys": {
"type": 1,
"id": 4896,
"country": "US",
"sunrise": 1591007368,
"sunset": 1591056495
},
"timezone": -14400,
"id": 4164138,
"name": "Miami",
"cod": 200
}

错误:

at org.json.JSONObject.wrongValueFormatException(JSONObject.java:2590)
at org.json.JSONObject.getString(JSONObject.java:863)
at Main.main(Main.java:23)

我试图获取 JSON 的"天气"部分或 JSON 的任何子部分。有人可以帮助我编写代码吗?

json.getString(key);

返回一个字符串if指定key的值为String

在您的情况下,weather的值是JSONArray而不是String

你应该做:

json.getJSONArray("weather");

理想情况下,您应该检查密钥是否存在,或者具有默认值以避免NPE

if (json.has("weather") && json.get("weather") instanceof JSONArray) {
json.getJSONArray("weather");
}

除非您 100% 确定JSON结构。

你应该对字符串值使用getString, 如果它的布尔值你应该使用getBoolean如果十进制getDouble什么的。

最新更新