Java org.json.JSONException:JSONObject[“weather”]不是字符串
我目前正在使用来自的天气API,我正在尝试将JSON页面转换为可打印字符串。更具体地说。我正试图打印出天气数组作为键,但它不起作用:Java org.json.JSONException:JSONObject[“weather”]不是字符串,java,json,Java,Json,我目前正在使用来自的天气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.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);
如果指定键的值是字符串,则返回字符串
在您的例子中,weather的值是JSONArray而不是字符串
你应该做:
json.getJSONArray("weather");
理想情况下,您应该检查该键是否存在,或者是否具有默认值以避免NPE
除非您100%确定JSON结构。您应该使用getString作为字符串值,
如果是布尔型的,那么应该使用getBoolean,如果是十进制的getDouble或其他什么..你想对天气做什么?正如消息和JSON明确显示的那样,它不是字符串,因此getString当然不起作用。我完全知道。。。。所以我要寻求帮助?我不熟悉JSON,但对JAVA和编程并不陌生……当您在IDE中键入它时,autocomplete将提供几种方法来键入JSON.get、getJSONArray和getJSONObject,而其他方法则是特定于原语的,如getInt或用于获取名称,如getNames。下次请更多地关注IDE和文档。
if (json.has("weather") && json.get("weather") instanceof JSONArray) {
json.getJSONArray("weather");
}