You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot接收自定义JSONObject参数为空问题求助

解决SpringBoot中@RequestBody接收JSONObject为空的问题

核心原因

Spring Boot默认使用Jackson作为JSON处理库,若你用的是Fastjson的JSONObject,Jackson无法自动将请求体解析为Fastjson的对象,最终得到空的{}。


解决方案1:适配Fastjson的JSONObject

  1. 确认Fastjson依赖
    在pom.xml中添加正确依赖(Maven):

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.83</version> <!-- 选用最新稳定版本 -->
    </dependency>
    
  2. 配置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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 03:27:10