Search code examples
javaspringresttemplate

I can't get a field from JSON


I have a method looks like:

@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 looks like:

{
    "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
}

But I've got an exception in return:

java.lang.NullPointerException: Cannot invoke "com.fasterxml.jackson.databind.JsonNode.asText()" because the return value of "com.fasterxml.jackson.databind.JsonNode.get(String)" is null


Solution

  • Well, if I'm right you need to first get the 'sys' item from your json and then you will be able to get the sunset like that :

    String temperature = mapper.readTree(json).get("sys").get("sunset").asTest();