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

相关推荐
一线大码2 小时前
Gradle 基础篇之基础知识的介绍和使用
后端·gradle
Java猿_2 小时前
Spring Boot 集成 Sa-Token 实现登录认证与 RBAC 权限控制(实战)
android·spring boot·后端
小王师傅662 小时前
【轻松入门SpringBoot】actuator健康检查(上)
java·spring boot·后端
码事漫谈3 小时前
C++高并发编程核心技能解析
后端
码事漫谈3 小时前
C++与浏览器交织-从Chrome插件到WebAssembly,开启性能之门
后端
陌颜39113 小时前
JSON在线工具:从数据混沌到清晰洞察的智能助手
json
JIngJaneIL3 小时前
基于java+ vue农产投入线上管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
源代码•宸4 小时前
goframe框架签到系统项目(BITFIELD 命令详解、Redis Key 设计、goframe 框架教程、安装MySQL)
开发语言·数据库·经验分享·redis·后端·mysql·golang
⑩-4 小时前
SpringCloud-Nacos 配置中心实战
后端·spring·spring cloud
java1234_小锋5 小时前
[免费]SpringBoot+Vue勤工助学管理系统【论文+源码+SQL脚本】
spring boot·后端·mybatis·勤工助学