【问题标题】:ResponseEntity<MyDTO> is Returning Missing/Incomplete JSONResponseEntity<MyDTO> 正在返回丢失/不完整的 JSON
【发布时间】:2020-01-29 22:46:37
【问题描述】:

在 Spring Boot 中从我的服务返回响应时,我看到 JSON 中断/丢失/不完整的问题。

例子:

ResponseEntity<MyDTO> responseEntity = myService.getMyDTO();
return responseEntity;
public class MyService {
  public ResponseEntity<MyDTO> getMyDTO() {
    return restTemplate.exchange(requestUrl, HttpMethod.GET, new HttpEntity<>(httpHeaders), MyDTO.class)
  }
}

在调试和检查 ResponseEntity 的主体时,即 MyDTO 实例,它包含 所有预期的字段。

public class MyDTO {
  private Information information;
  private Address address;
}

public class Information {
  private String firstName;
  private String lastName;
}

public class Address {
  private String streetName;
}

调试:

MyDTO
  body
    information
      firstName > "John"
      lastName > "Doe"
    address > null

预期的 JSON:

{
  "information": {
    "firstName": "John",
    "lastName": "Doe"
  },
  "address: null
}

实际 JSON:

{
  "information": {
    "firstName": "Jo

是的,响应 JSON 中甚至缺少结尾括号。

注意:地址为空,因为来自上游服务的响应返回 400,我们将该响应映射到我们的 DTO (MyDTO)。最初,我认为这是问题所在,直到调试确认映射已正确完成。

这才是真正奇怪的地方。如果我将该 ResponseEntity 的主体放入另一个 ResponseEntity 中,则它会返回正常并且可以正常工作。该服务甚至返回更快,这也很奇怪。

ResponseEntity responseEntity = myService.getMyDTO();
return new ResponseEntity(responseEntity.getBody(), responseEntity.getStatusCode());

有人知道发生了什么吗?是网络、Spring Boot 还是我的代码问题?为什么返回新的 ResponseEntity 会解决问题?

【问题讨论】:

  • 你能分享myService.getMyDTO();的代码吗?
  • 刚刚添加了 MyService.getMyDTO 的代码
  • 我认为是超时。 RestTemplate 请求的超时时间是多少?
  • 我没有考虑过,但不确定是否是这种情况,因为 MyDTO 的所有字段都存在。这只是在客户端出乎意料。
  • 发生异常时客户端必须断开连接

标签: spring spring-boot


【解决方案1】:

发现问题。上游服务包含一个“Content-Length”标头,该标头太小,导致客户端 JSON 缺失/不完整。

【讨论】:

    【解决方案2】:

    这是因为您正在调用restTemplate.exchange() 方法;如果您使用 getForObject() 方法(在 post call postForObject() 的情况下),它将起作用。

    此方法将首先创建 MyDTO 类对象,然后您需要将该对象添加到 ResponseEntity 对象中以返回它。

    例子:

    MyDTO myDtoObject = restTemplate.getForObject(requestUrl, MyDTO.class);
    return new ResponseEntity<>(myDtoObject, HttpStatus.OK);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-24
      • 2021-08-06
      • 2021-07-27
      • 1970-01-01
      • 2023-03-25
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多