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

相关推荐
JohnYan20 分钟前
工作笔记- 记一次MySQL数据移植表空间错误排除
数据库·后端·mysql
程序员清风43 分钟前
阿里二面:Kafka 消费者消费消息慢(10 多分钟),会对 Kafka 有什么影响?
java·后端·面试
CodeSheep1 小时前
宇树科技,改名了!
前端·后端·程序员
hstar95271 小时前
三十五、面向对象底层逻辑-Spring MVC中AbstractXlsxStreamingView的设计
java·后端·spring·设计模式·架构·mvc
楽码1 小时前
AI决策树:整理繁杂问题的简单方法
人工智能·后端·openai
星辰大海的精灵1 小时前
基于Dify+MCP实现通过微信发送天气信息给好友
人工智能·后端·python
import_random1 小时前
[深度学习]5大神经网络架构(介绍)
后端
pengyu2 小时前
【Java设计原则与模式之系统化精讲:壹】 | 编程世界的道与术(实战指导篇)
java·后端·设计模式
陈随易2 小时前
一行代码,将网页元素变成图片!比 html2canvas 快 93 倍的截图神器来了!
前端·后端·程序员
Kookoos2 小时前
性能剖析:在 ABP 框架中集成 MiniProfiler 实现性能可视化诊断
后端·c#·.net·abp vnext·miniprofiler