响应实体。控制器截断响应的 JSON 部分

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

我有一个控制器,它使用 RestTemplate 向外部 API 发送请求并获取数据结构。它应该返回这个结构,但是当使用我的控制器时,有时 JSON 响应的末尾会被丢弃。

我尝试自定义 RestTemplate 并增加 application.yaml 中的响应大小

我的控制器:

    @GetMapping(value = "/weather/lat={lat}&lon={lon}")
    @Cacheable(value = "root", key = "{#lat , #lon}")
    public ResponseEntity<Root> getWeather(@PathVariable("lat") String lat, @PathVariable("lon") String lon) {
        try{
            String request = String.format("%s?lat=%s&lon=%s&units=metric&appid=%s",
                    weatherUrl, lat, lon, appId);
            return restTemplate.getForEntity(request, Root.class);
        }catch (RestClientException e){
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

截断查询示例:

{
    "coord": {
        "lat": 1.4,
        "lon": 2.33
    },
    "weather": [
        {
            "id": 804,
            "main": "Clouds",
            "description": "overcast clouds",
            "icon": "04n"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 26.15,
        "feels_like": 26.15,
        "temp_min": 26.15,
        "temp_max": 26.15,
        "pressure": 1014,
        "humidity": 79,
        "sea_level": 1014,
        "grnd_level": 1014
    },
    "visibility": 10000,
    "wind": {
        "speed": 6.34,
        "deg": 198,
        "gust": 6.08
    },
    "clouds": {
        "all": 100
    },
    "dt": 1696111416,
    "sys": {
        "sunrise": 1696052261,
        "sunset": 1696095829
    },
    "timezone": 0,
    "id": 0,
    "name":"co
java json spring resttemplate
1个回答
0
投票

事实证明,ResponseEntity 错误地考虑了 Content-length 标头。发生这种情况是因为外部 API 可能返回带有空字段的对象。要修复此问题,您需要允许 jackson 使用位于 POJO 上方的

@JsonInclude(JsonInclude.Include.NON_NULL)
注释传递空字段。通过将其放在该结构中的所有可序列化字段上,我得到:

    "coord": {
        "lat": 1.4,
        "lon": 2.33
    },
    "weather": [
        {
            "id": 804,
            "main": "Clouds",
            "description": "overcast clouds",
            "icon": "04n"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 26.15,
        "feels_like": 26.15,
        "temp_min": 26.15,
        "temp_max": 26.15,
        "pressure": 1014,
        "humidity": 79,
        "sea_level": 1014,
        "grnd_level": 1014
    },
    "visibility": 10000,
    "wind": {
        "speed": 6.34,
        "deg": 198,
        "gust": 6.08
    },
    "clouds": {
        "all": 100
    },
    "dt": 1696111416,
    "sys": {
        "sunrise": 1696052261,
        "sunset": 1696095829
    },
    "timezone": 0,
    "id": 0,
    "name": "",
    "cod": 200
}```
© www.soinside.com 2019 - 2024. All rights reserved.