首页 > 解决方案 > 需要使用 Spring Boot 从 OpenWeather json 获取温度

问题描述

我已经编写了 java spring boot 应用程序来从 openweatherapi 获取温度。我得到了完整的 json 代码,我只需要温度值。

如何解析和获取。

带有 ResponseEntity 响应的 SpringBoot 应用程序

@PostMapping("temperature")
    ResponseEntity<?> getTemperaturebyLocationCoordinates(@ModelAttribute TemperatureBean tempBean) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Object> response = restTemplate
                .getForEntity("https://api.openweathermap.org/data/2.5/weather?lat=" + tempBean.getLatitude() + "&lon="
                        + tempBean.getLongitude() + "&APPID=" + apikey + "&units=metric", Object.class);
        return response;
    }
{
    "coord": {
        "lon": 80.14,
        "lat": 13.36
    },
    "weather": [
        {
            "id": 500,
            "main": "Rain",
            "description": "light rain",
            "icon": "10n"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 31,
        "pressure": 1005,
        "humidity": 70,
        "temp_min": 31,
        "temp_max": 31
    },
    "visibility": 4000,
    "wind": {
        "speed": 4.1,
        "deg": 300
    },
    "clouds": {
        "all": 75
    },
    "dt": 1565012771,
    "sys": {
        "type": 1,
        "id": 9218,
        "message": 0.0132,
        "country": "IN",
        "sunrise": 1564964708,
        "sunset": 1565010350
    },
    "timezone": 19800,
    "id": 1259290,
    "name": "Puduvayal",
    "cod": 200
}

我只想要温度:31

标签: jsonspring-boot

解决方案


只需创建一个包含代表接收到的 JSON 的嵌套类的类。

OpenWeatherResponse.class

public class OpenWeatherResponse {

    private Main main;

    // constructor and getters ommitted
}

主类

public class Main {

    private int temp;

    // constructor and getters ommitted
}

然后替换其余调用中的实体

final String url = "https://api.openweathermap.org/data/2.5/weather?lat=" + tempBean.getLatitude() + "&lon="
                    + tempBean.getLongitude() + "&APPID=" + apikey + "&units=metric";
ResponseEntity<OpenWeatherResponse> response = restTemplate
            .getForEntity(url, OpenWeatherResponse.class);

final int temp = response.getBody().getMain().getTemp();

这是最简单的方法。

您也可以编写自定义序列化程序,但这需要更多的努力。


推荐阅读