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

相关推荐
程序员老邢5 分钟前
【技术底稿 18】FTP 文件处理 + LibreOffice Word 转 PDF 在线预览 + 集群乱码终极排查全记录
java·经验分享·后端·pdf·word·springboot
fox_lht9 分钟前
8.3.使用if let和let else实现简明的程序流控制
开发语言·后端·算法·rust
disgare2 小时前
SpringBoot 请求调用时关于高可用机制选型和落地
java·spring boot·后端
CodeMartain2 小时前
@SpringBootApplication 到底是什么呢?
java·spring boot·intellij-idea
余衫马2 小时前
在 Windows 服务中托管 ASP.NET Core Web API (.net6)
运维·windows·后端·asp.net·.net
许彰午2 小时前
Spring Boot + Vue 实现 XML 动态表单:固定字段 + 自由扩展方案
xml·vue.js·spring boot
indexsunny2 小时前
互联网大厂Java面试实战:Spring Boot微服务与Kafka消息队列深度解析
java·spring boot·微服务·面试·kafka·消息队列·电商
预知同行2 小时前
RAG 架构设计深度解析:从向量数据库选型到生产级检索系统
后端·架构
二哈赛车手2 小时前
github拉取自己项目出现的模块依赖问题解决方案
后端
用户6757049885023 小时前
AI开发实战4、AI总是忘记项目规范?因为你缺了这份终极上下文文件
后端·aigc·ai编程