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 值。

相关推荐
JustHappy6 小时前
古法编程秘籍(七):互联网到底是什么?把两台电脑怎么说话搞懂就够了
前端·后端·网络协议
Hommy886 小时前
【剪映小助手】添加图片接口(Add Images)
后端·github·剪映小助手·视频剪辑自动化
GetcharZp6 小时前
别再盲目用 OpenCV 读图了,这才是 CV 预处理的终极杀手锏!
后端
一 乐10 小时前
家政服务管理系统|基于springboot + vue家政服务管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·家政服务管理系统
IT_陈寒10 小时前
Vite热更新失效?可能你在用Windows
前端·人工智能·后端
椰椰椰耶11 小时前
[SpringCloud][14]OpenFeign参数传递方法
后端·spring·spring cloud
onething36511 小时前
Spring Boot + Spring AI 从入门到实战:7天转型计划 Day 3 —— 消息表设计 + 级联删除 + 事务管理
人工智能·后端
荣江12 小时前
Hermes Agent 代码仓库打包工具使用指南(repomix-rs 高性能版)
后端
王某某人12 小时前
LangChain4j 入门:Java 程序员的第一个 AI 对话程序
人工智能·后端
码农刚子12 小时前
从零开始:在 Windows 服务器上部署 Node.js 项目(小白实战教程)
后端·node.js