繁体   English   中英

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

[英]org.json.JSONException: JSONObject[“weather”] is not a string

我目前正在使用来自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 ,则返回一个String

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

你应该做:

json.getJSONArray("weather");

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

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

除非您 100% 确定JSON结构。

你应该使用getString作为字符串值,如果它的 boolean 你应该使用getBoolean如果十进制getDouble什么的..

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM