我无法从 JSON 获取字段

问题描述 投票:0回答:1

我有一个方法看起来像:

@RequestMapping(value = "/weather")
public void printWeather() throws JsonProcessingException {
    String url = mineApiURLwithKey;
    String json = restTemplate.getForObject(url, String.class);
    ObjectMapper mapper = new ObjectMapper();
    String temperature = mapper.readTree(json).get("sunset").asText();
}

JSON 看起来像:

{
    "coord": {
        "lon": 19.7497,
        "lat": 53.5043
    },
    "weather": [
        {
            "id": 500,
            "main": "Rain",
            "description": "light rain",
            "icon": "10n"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 280.67,
        "feels_like": 279.66,
        "temp_min": 279.82,
        "temp_max": 281.48,
        "pressure": 1010,
        "humidity": 72
    },
    "visibility": 10000,
    "wind": {
        "speed": 1.79,
        "deg": 325,
        "gust": 3.13
    },
    "rain": {
        "1h": 0.42
    },
    "clouds": {
        "all": 72
    },
    "dt": 1619039826,
    "sys": {
        "type": 3,
        "id": 2007860,
        "country": "PL",
        "sunrise": 1618975636,
        "sunset": 1619027504
    },
    "timezone": 7200,
    "id": 3093028,
    "name": "Lubawa",
    "cod": 200
}

但我有一个例外作为回报:

java.lang.NullPointerException:无法调用 “com.fasterxml.jackson.databind.JsonNode.asText()”因为返回 “com.fasterxml.jackson.databind.JsonNode.get(String)”的值为 null

java spring resttemplate
1个回答
0
投票

好吧,如果我是对的,你需要首先从 json 中获取“sys”项,然后你就可以像这样获取日落了:

String temperature = mapper.readTree(json).get("sys").get("sunset").asTest();
© www.soinside.com 2019 - 2024. All rights reserved.