Spring Boot接口JSON反序列化错误及参数无效问题求助
问题解决方案
问题1:多个@RequestBody导致JSON反序列化错误
Spring MVC规范中,一个HTTP请求只能包含一个请求体,控制器方法里不能同时使用多个@RequestBody注解。当你尝试这么做时,Spring会把完整的请求体JSON分别绑定到每个标注了@RequestBody的参数上,导致类型不匹配(比如把整个JSON对象当成Integer反序列化),进而抛出错误。
解决方法
必须用统一的实体类封装所有请求参数,这也是你后续改用EmisionPesosBody的正确方向,无需再尝试多个@RequestBody的写法。
问题2:使用EmisionPesosBody后返回400(参数无效)且响应字段为null
针对这个问题,从以下维度逐一排查:
1. 实体类字段与外部接口参数不匹配
对照外部接口的Swagger文档,检查EmisionPesosBody的字段映射:
- 若字段命名规则不一致(比如接口用蛇形命名
monto_total,你的类用驼峰montoTotal),添加@JsonProperty注解指定对应名称:
public class EmisionPesosBody { @JsonProperty("monto_total") private Integer montoTotal; @JsonProperty("tipo_documento") private String tipoDocumento; // 其他字段及getter/setter方法 }
- 确认字段类型完全匹配:比如接口要求
Integer就不能用Long,必填字段必须赋值,不能为null。
2. 检查RestTemplate的请求配置
- 确保请求头包含
Content-Type: application/json,部分外部接口会拒绝非JSON格式的请求体; - 确认
accessToken已正确放入请求头(如Authorization: Bearer {token}),权限验证失败也可能返回400错误。
示例请求代码:
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setBearerAuth(accessToken); HttpEntity<EmisionPesosBody> requestEntity = new HttpEntity<>(requestBody, headers); ResponseEntity<YourResponseClass> response = restTemplate.exchange( "外部接口URL", HttpMethod.POST, requestEntity, YourResponseClass.class );
3. 验证实际发送的请求体
开启RestTemplate的DEBUG日志,查看实际发送的JSON内容,对比Swagger文档的示例请求:
在application.yml中添加日志配置:
logging: level: org.springframework.web.client.RestTemplate: DEBUG
或者自定义拦截器打印请求体:
public class LoggingInterceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { System.out.println("请求体内容: " + new String(body, StandardCharsets.UTF_8)); return execution.execute(request, body); } } // 注册到RestTemplate restTemplate.getInterceptors().add(new LoggingInterceptor());
检查是否存在字段缺失、类型错误或格式问题。
4. 响应字段为null的排查
响应体所有字段为null,通常是响应JSON的字段名与你的响应实体类不匹配,或者RestTemplate无法解析响应格式:
- 给响应实体类的字段也添加
@JsonProperty注解,匹配外部接口返回的命名规则; - 确认响应的
Content-Type是application/json,若接口返回其他格式(如text/plain),需调整RestTemplate的消息转换器。
内容的提问来源于stack exchange,提问作者Pablo bustamante
相关产品推荐
相关产品推荐

