【发布时间】:2021-11-30 10:34:39
【问题描述】:
我目前正在尝试向外部 API 发送请求。我需要准备一个带有包含报告列表的 JSON 正文的 POST 请求,并使用 RestTemplate 发送它。这是我的代码:
//reportsJson is a list of Report objects containing some data
String postBody;
try {
postBody = objectMapper.copy()
.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE)
.writeValueAsString(reportsJson);
} catch (JsonProcessingException e) {
log.error("Failed to serialize report.", e);
throw new IllegalArgumentException(e);
}
var headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setBearerAuth(getToken());
HttpEntity<?> entity = new HttpEntity<Object>(postBody, headers);
var response = restTemplate.exchange(API_URL, HttpMethod.POST, entity, ReportResponse.class);
不幸的是,我从服务器得到的响应是 HTTP 400 Bad Request:
'[{...},{...},{...}]' is not of type 'object'
编辑: 我注意到问题与 RestTemplate 中 JSON 中双引号的转义有关,例如:
{ \"id\" : { \"name\" : \"xyz\" } ... }
【问题讨论】:
标签: json spring-boot jackson resttemplate objectmapper