spring-boot-starter-json配置对象属性为空不显示

news2024/7/6 20:07:53

问题背景

在Spring Boot中使用spring-boot-starter-json(通常是通过jackson实现的)时,如果你希望在序列化对象时,如果某个属性为空,则不显示该属性,你可以使用@JsonInclude注解来实现这一点。

pom.xml

<!-- springboot-json by zhengkai.blog.csdn.net -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-json</artifactId>
</dependency>

@JsonInclude注解

@JsonInclude注解可以控制序列化过程中包含哪些属性。它有几个参数,其中JsonInclude.Include枚举定义了不同的行为:

  • ALWAYS:总是包括属性,即使值为null或空。
  • NON_NULL:仅当属性值不为null时才包括。
  • NON_ABSENT:对于Java Optional,仅当值为非空(即Optional.isPresent()为true)时才包括。
  • NON_EMPTY:对于集合或数组,仅当它们不为空时才包括。
  • NON_DEFAULT:仅当属性值不等于其类型的默认值时才包括。

代码实战

package com.softdev.system.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

import java.io.Serializable;

@JsonInclude(value = JsonInclude.Include.NON_NULL)
@Data
public class SysConfig  implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * configId
     */
    @TableId(type = IdType.AUTO)
    Integer id;
    String paramKey;
    String paramValue;
    Integer status;
    String remark;
}

可以看到数据库的Remark字段是空的

由于加了注释,所以他并不会显示出来 

移除@JsonInclude(value = JsonInclude.Include.NON_NULL)注释

局部配置

如果你希望属性为空时不显示,可以在你的类或属性上使用@JsonInclude(JsonInclude.Include.NON_NULL)注解。例如:

import com.fasterxml.jackson.annotation.JsonInclude;
//by zhengkai.blog.csdn.net
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyBean {
    private String property1;
    private String property2;

    // getters and setters
}

在上面的例子中,如果property1property2的值为null,它们将不会被包含在JSON序列化的结果中。

请注意,@JsonInclude注解可以应用于类级别或属性级别。如果应用于类级别,它将影响该类的所有属性。如果应用于属性级别,它将仅影响该特定属性。

全局配置

这个配置可以通过application.propertiesapplication.yml文件进行全局设置,例如:

# application.properties
spring.jackson.default-property-inclusion=non_null

或者

# application.yml
spring:
  jackson:
    default-property-inclusion: non_null

这样配置后,所有的类和属性都会遵循这个规则,除非它们被单独覆盖。

Customize the Jackson ObjectMapper

Spring MVC (client and server side) uses HttpMessageConverters to negotiate content conversion in an HTTP exchange. If Jackson is on the classpath, you already get the default converter(s) provided by Jackson2ObjectMapperBuilder, an instance of which is auto-configured for you.

The ObjectMapper (or XmlMapper for Jackson XML converter) instance (created by default) has the following customized properties:

  • MapperFeature.DEFAULT_VIEW_INCLUSION is disabled

  • DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES is disabled

  • SerializationFeature.WRITE_DATES_AS_TIMESTAMPS is disabled

  • SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS is disabled

Spring Boot also has some features to make it easier to customize this behavior.

You can configure the ObjectMapper and XmlMapper instances by using the environment. Jackson provides an extensive suite of on/off features that can be used to configure various aspects of its processing. These features are described in several enums (in Jackson) that map onto properties in the environment:

EnumPropertyValues

com.fasterxml.jackson.databind.cfg.EnumFeature

spring.jackson.datatype.enum.<feature_name>

truefalse

com.fasterxml.jackson.databind.cfg.JsonNodeFeature

spring.jackson.datatype.json-node.<feature_name>

truefalse

com.fasterxml.jackson.databind.DeserializationFeature

spring.jackson.deserialization.<feature_name>

truefalse

com.fasterxml.jackson.core.JsonGenerator.Feature

spring.jackson.generator.<feature_name>

truefalse

com.fasterxml.jackson.databind.MapperFeature

spring.jackson.mapper.<feature_name>

truefalse

com.fasterxml.jackson.core.JsonParser.Feature

spring.jackson.parser.<feature_name>

truefalse

com.fasterxml.jackson.databind.SerializationFeature

spring.jackson.serialization.<feature_name>

truefalse

com.fasterxml.jackson.annotation.JsonInclude.Include

spring.jackson.default-property-inclusion

alwaysnon_nullnon_absentnon_defaultnon_empty

For example, to enable pretty print, set spring.jackson.serialization.indent_output=true. Note that, thanks to the use of relaxed binding, the case of indent_output does not have to match the case of the corresponding enum constant, which is INDENT_OUTPUT.

This environment-based configuration is applied to the auto-configured Jackson2ObjectMapperBuilder bean and applies to any mappers created by using the builder, including the auto-configured ObjectMapper bean.

The context’s Jackson2ObjectMapperBuilder can be customized by one or more Jackson2ObjectMapperBuilderCustomizer beans. Such customizer beans can be ordered (Boot’s own customizer has an order of 0), letting additional customization be applied both before and after Boot’s customization.

Any beans of type com.fasterxml.jackson.databind.Module are automatically registered with the auto-configured Jackson2ObjectMapperBuilder and are applied to any ObjectMapper instances that it creates. This provides a global mechanism for contributing custom modules when you add new features to your application.

If you want to replace the default ObjectMapper completely, either define a @Bean of that type and mark it as @Primary or, if you prefer the builder-based approach, define a Jackson2ObjectMapperBuilder @Bean. Note that, in either case, doing so disables all auto-configuration of the ObjectMapper.

If you provide any @Beans of type MappingJackson2HttpMessageConverter, they replace the default value in the MVC configuration. Also, a convenience bean of type HttpMessageConverters is provided (and is always available if you use the default MVC configuration). It has some useful methods to access the default and user-enhanced message converters.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1871597.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

net Framework OAuth2.0

grant_type client_credentials 客户端凭证password 密码模式 用于资源所有者密码凭据token 隐藏式 、 简化式 简化模式又称为隐式授权码模式&#xff0c;它是授权码模式的一个简化版本authorization_code 授权码 A. 第三方程序向资源拥有者(用户)发送授权请求&#xf…

如何获得更高质量的回答-chatgpt

在与技术助手如ChatGPT进行交互时&#xff0c;提问的方式直接影响到你获得的答案质量。以下是几个关键的提问技巧&#xff0c;可以帮助你在与ChatGPT的互动中获得更有效的回答&#xff1a; 1. 清晰明了的问题 技巧&#xff1a;确保问题清晰明了&#xff0c;避免含糊不清或模糊的…

【2024最新华为OD-C/D卷试题汇总】[支持在线评测] 特殊加密算法(200分) - 三语言AC题解(Python/Java/Cpp)

&#x1f36d; 大家好这里是清隆学长 &#xff0c;一枚热爱算法的程序员 ✨ 本系列打算持续跟新华为OD-C/D卷的三语言AC题解 &#x1f4bb; ACM银牌&#x1f948;| 多次AK大厂笔试 &#xff5c; 编程一对一辅导 &#x1f44f; 感谢大家的订阅➕ 和 喜欢&#x1f497; &#x1f…

一键智控,舒适无限:网关在风机盘管智能温控中的应用

风机盘管智能控制系统采用钡铼技术系列无线网关&#xff0c;搭配各类风机设备及传感器组成无线物联中央空调室内机管理系统&#xff0c;实现整个办公楼的空调环境智能化管理。在建筑舒适度的前提下&#xff0c;降低能耗&#xff0c;避免能源浪费。 网关通信接口采用无线传输的…

vscode刷LeetCode算法题环境配置

首先&#xff0c;下载nodejs 在vscode中安装LeetCode插件 安装好进行配置 选择leetcode-cn 填上刚才下载node.exe的路径 完成之后重启一下vscode 重启之后登陆LeetCode 完成之后就可以看到题目了 点击 code now 就可以开始刷题了

Flutter循序渐进==>第一个界面

导言 const MyApp({Key? key}) : super(key: key); const: 这个关键字表示这是一个编译时常量构造函数。当一个类使用 const 构造函数初始化时&#xff0c;它的所有字段都将被设置为编译时常量&#xff0c;并且该对象将在编译时就被创建出来。这对于状态不变&#xff08;immu…

基于单片机和LabVIEW 的远程矿井水位监控系统设计

摘要 &#xff1a; 针 对 现 有 矿 井 水 位 监 控 系 统 存 在 结 构 复 杂 和 不 能 远 程 监 控 的 问 题 &#xff0c; 设计了基于单片机和&#xff2c;&#xff41;&#xff42;&#xff36;&#xff29;&#xff25;&#xff37; 的远程矿井水位监控系统 &#xff0c; 详…

python-(opencv)视频转glf

文章目录 前言python-(opencv)视频转glf1. 下载 opencv-python2. cv2&#xff08;OpenCV&#xff09;和imageio的区别3. demo源码 前言 如果您觉得有用的话&#xff0c;记得给博主点个赞&#xff0c;评论&#xff0c;收藏一键三连啊&#xff0c;写作不易啊^ _ ^。   而且听说…

uView 2.0:uni-app生态的利剑出鞘,引领UI框架新纪元

引言 随着移动互联网的快速发展&#xff0c;跨平台应用开发成为了开发者们关注的焦点。uni-app&#xff0c;一个基于Vue.js的跨平台应用开发框架&#xff0c;因其高效、易用的特性而广受欢迎。在uni-app的生态系统中&#xff0c;UI框架的选择对于开发者而言至关重要。今天&…

2024上海CDIE 参展预告 | 一站式云原生数字化平台已成趋势

为什么企业需要进行数字化转型&#xff1f;大家都在讨论的数字化转型面临哪些困境&#xff1f;2024.6.25-26 CDIE数字化创新博览会现场&#xff0c;展位【A18】&#xff0c;期待与您相遇&#xff0c;共同探讨企业如何利用数字化技术驱动业务增长。 一、展会介绍——CDIE数字化…

C语言 | Leetcode C语言题解之第201题数字范围按位与

题目&#xff1a; 题解&#xff1a; int rangeBitwiseAnd(int m, int n) {while (m < n) {// 抹去最右边的 1n & (n - 1);}return n; }

【Linux操作系统】进程地址空间与动态库加载

当系统执行一个依赖动态库的可执行程序时&#xff0c;系统不仅要将该可执行程序加载到内存中还要由加载器将动态库加载到内存中&#xff08;静态库没有&#xff09;&#xff0c;因此必须要让加载器知道该动态库的名称&#xff0c;系统会默认在/lib64路径下查找&#xff0c;解决…

Java将list数组中重复的对象进行去重

/*** 数组去重*/ public class ArrayDistinct {public static void main(String[] args) {ArrayList<Object> list new ArrayList<>();JSONObject jsonObject1 new JSONObject();jsonObject1.put("name","张三");jsonObject1.put("age&…

Vite: 关于Rollup打包

概述 Rollup 是一款基于 ES Module 模块规范实现的 JavaScript 打包工具&#xff0c;在前端社区中赫赫有名&#xff0c;同时也在 Vite 的架构体系中发挥着重要作用不仅是 Vite 生产环境下的打包工具&#xff0c;其插件机制也被 Vite 所兼容&#xff0c;可以说是 Vite 的构建基…

kubekey 安装高可用 kubernetes 集群

1. 准备环境 1.1 机器准备 4 台机器&#xff0c;操作系统&#xff1a;Ubuntu 24.04/RHEL8/CentOS9 10.111.3.53 master1 10.111.3.54 master2 10.111.3.55 master3 10.111.3.57 node41.2 安装依赖和配置 所有节点都需要执行&#xff1a; Ubuntu: apt-get install -y soca…

JeeSite中的数据库表动态建模与管理模块(DBM)

一、引言 在现代软件开发中&#xff0c;数据库作为系统数据存储和管理的核心&#xff0c;其设计和维护的灵活性、可扩展性对于系统的长期稳定运行至关重要。JeeSite作为一款流行的企业级快速开发平台&#xff0c;其数据库表动态管理模块&#xff08;DBM&#xff09;提供了强大…

UWB:DS-TWR( Double-sided two-way ranging)双边测距公式推导:为啥是乘法?

UWB DS-TWR&#xff08; Double-sided two-way ranging&#xff09;双边测距为啥是乘法&#xff1f;&#xff1f; 公式&#xff1a; 我们先看单边 Single-Sided Two-Way Ranging (SS-TWR) 单边很好理解。 symmetric double-sided TWR (SDS-TWR)对称的双边测距 再看双边 Trou…

相机系列——从相机畸变到托勒密地图

by 木一 标签&#xff1a;#相机畸变 #畸变纠正 #鱼眼相机 #折射定律 #托勒密地图 引言 前文[1][2]我们介绍了针孔相机模型&#xff0c;以及针孔相机模型的相机标定过程&#xff0c;但针孔相机模型是对相机成像最简单的描述&#xff0c;实际的相机成像过程要远复杂很多。 首先…

C++ | Leetcode C++题解之第201题数字范围按位与

题目&#xff1a; 题解&#xff1a; class Solution { public:int rangeBitwiseAnd(int m, int n) {while (m < n) {// 抹去最右边的 1n n & (n - 1);}return n;} };

Flutter循序渐进==>Dart之类型、控制流和循环

导言 磨刀不误砍柴工&#xff0c;想搞好Flutter&#xff0c;先学好Flutter&#xff0c;还是本着我学Python的方法&#xff0c;先从数据类型、控制流和循环开始&#xff0c;这是每一种编程语言必用的。编程语言是相通的&#xff0c;基本精通一种后&#xff0c;学其它的就变得很…