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

SpringMVC接口返回VO类JSON数据时如何排除null值字段

解决方案

Spring MVC/Spring Boot 默认使用Jackson做JSON序列化,可通过以下两种常用方式实现过滤null字段:

方案1:仅对单个VO类生效(局部配置)

直接在RobotVO类上添加Jackson的@JsonInclude注解即可:

import com.fasterxml.jackson.annotation.JsonInclude;

// 序列化时仅包含非null的字段
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RobotVO {
    private String rbtId;
    private String rbtPower;
    // 其余字段、get/set方法省略
}

注:如果只想过滤单个字段的null值,也可以把注解加在对应字段上,不需要加在类上。

配置后你的接口返回结果就会变成:

{
  "rbtPower": "ON"
}

方案2:对项目所有接口返回的JSON生效(全局配置)

不需要逐个给VO类加注解,直接在项目配置文件中添加Jackson全局序列化规则即可:

  • 如果你用application.yml配置:
spring:
  jackson:
    default-property-inclusion: non_null
  • 如果你用application.properties配置:
spring.jackson.default-property-inclusion=non_null

特殊情况:项目使用FastJSON作为序列化器

如果你的项目替换了默认的Jackson,改用FastJSON做序列化,可通过如下全局配置实现:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        // 配置不序列化null值的字段,不要开启WriteMapNullValue配置即可
        config.setSerializerFeatures(SerializerFeature.PrettyFormat);
        converter.setFastJsonConfig(config);
        converters.add(converter);
    }
}

FastJSON默认就不会输出值为null的字段,只要你没有主动开启SerializerFeature.WriteMapNullValue配置即可。

内容的提问来源于stack exchange,提问作者ringhiosi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:27:08