springboot中,怎么把对象的空属性转为json的时候过滤掉

全局配置 ObjectMapper

java Bean

java 复制代码
@Data
@Component
@NoArgsConstructor
@AllArgsConstructor
@ConfigurationProperties(prefix = "person")
public class Person {
	private String userName;
	private Boolean boss;
	private Date birth;
	private Integer age;
	private Pet pet;
	private String[] interests;
	private List<String> animal;
	private Map<String, Object> score;
	private Set<Double> salarys;
	private Map<String, List<Pet>> allPets;
}

application.yaml

yaml 复制代码
person:  # 表示一个人的信息
  userName: wdw  # 用户名
  boss: false  # 是否是老板
  birth: 2019/12/12 20:12:33  # 出生日期
  age: 18  # 年龄
  pet:  # 宠物信息
    name: tomcat  # 宠物名字
    weight: 23.4  # 宠物体重
  interests: [篮球, 游泳]  # 兴趣爱好
  animal:  # 动物列表
    - jerry
    - mario
  salarys: [3999, 4999.98, 5999.99]  # 工资列表

表单提交

html 复制代码
    <form action="/saveUser" method="post">
        姓名: <input name="userName" value="zhangsan"/> <br/>
        年龄: <input name="age" value="18"/> <br/>
        生日: <input name="birth" value="2019/12/10"/> <br/>
        宠物: <input name="pet" value="小白,23"/>
        <input type="submit" value="保存"/>
    </form>

页面视图

在Spring Boot中全局配置 ObjectMapper,使其在序列化时忽略 null 值。

java 复制代码
1import com.fasterxml.jackson.databind.ObjectMapper;
2import org.springframework.context.annotation.Bean; 	
3import org.springframework.context.annotation.Configuration;
4
5@Configuration
6public class JacksonConfig {
7
8    @Bean
9    public ObjectMapper objectMapper() {
10        ObjectMapper objectMapper = new ObjectMapper();
11        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
12        return objectMapper;
13    }
14}

通过这种方式,所有的对象在序列化为JSON时都会忽略 null 值。

外链图片转存中...(img-Ntiqt1xQ-1735741450802)

通过这种方式,所有的对象在序列化为JSON时都会忽略 null 值。

相关推荐
Bruce_Liuxiaowei21 分钟前
基于Flask的勒索病毒应急响应平台架构设计与实践
后端·python·flask
inxunoffice22 分钟前
批量将 JSON 转换为 Excel/思维导入等其它格式
json·excel
!!!52526 分钟前
Spring Boot MongoDB 分页工具类封装 (新手指南)
spring boot·后端·mongodb
程序员鱼皮34 分钟前
2025全新 Java 面经:字节飞书实习一面真实复盘,附答案整理+ Java 题库!
java·后端·面试
爱的叹息36 分钟前
关于 Spring Boot + Vue 前后端开发的打包、测试、监控、预先编译和容器部署 的详细说明,涵盖从开发到生产部署的全流程
vue.js·spring boot·后端
穷儒公羊1 小时前
第一部分——Docker篇 第三章 构建自定义镜像
java·运维·后端·学习·docker·云原生·容器
isfox1 小时前
速学!Java 原子操作,开启并发编程新境界
后端·程序员
楽码2 小时前
只需一文!深入理解闭包的实现
后端·go·编程语言
cong_2 小时前
🌟摸鱼 TV 搭建属于自己的视频站
前端·后端·github
bobz9652 小时前
内网网络 rp_filter 参数配置
后端