SpringBoot接收自定义JSONObject参数为空问题求助
解决SpringBoot中@RequestBody接收JSONObject为空的问题
核心原因
Spring Boot默认使用Jackson作为JSON处理库,若你用的是Fastjson的JSONObject,Jackson无法自动将请求体解析为Fastjson的对象,最终得到空的{}。
解决方案1:适配Fastjson的JSONObject
确认Fastjson依赖
在pom.xml中添加正确依赖(Maven):<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> <!-- 选用最新稳定版本 --> </dependency>配置Fastjson作为消息转换器
创建配置类替换Spring默认的JSON处理规则:@Configuration public class FastJsonMvcConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); // 可选:配置序列化规则,比如保留空字段 fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue); fastConverter.setFastJsonConfig(fastJsonConfig); // 设置支持的媒体类型 List<MediaType> mediaTypes = new ArrayList<>(); mediaTypes.add(MediaType.APPLICATION_JSON); fastConverter.setSupportedMediaTypes(mediaTypes); // 优先使用Fastjson转换器 converters.add(0, fastConverter); } }
解决方案2:用Jackson原生JsonNode(零额外配置)
直接使用Spring默认支持的JsonNode,无需引入第三方依赖,同样能灵活处理自定义JSON结构:
@PostMapping("/saveUser") public void saveSingleUser(@RequestBody JsonNode jsonNode) { // 示例:获取字段值 String username = jsonNode.get("username").asText(); String role = jsonNode.get("role").asText(); // 业务逻辑处理 }
额外排查项
- 校验Postman请求:确保请求体是
raw格式的JSON,字段名拼写无误,且Content-Type确实设置为application/json(无拼写错误)。 - 移除手动响应配置:删除
response.setContentType("application/json")和response.setCharacterEncoding("UTF-8"),Spring Boot会自动处理响应头,手动设置可能引发冲突。
内容的提问来源于stack exchange,提问作者Dipak Zad
相关产品推荐
相关产品推荐

