【发布时间】: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