spring-boot-starter-json配置對象屬性為空不顯示

問題背景

在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>

true,?false

com.fasterxml.jackson.databind.cfg.JsonNodeFeature

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

true,?false

com.fasterxml.jackson.databind.DeserializationFeature

spring.jackson.deserialization.<feature_name>

true,?false

com.fasterxml.jackson.core.JsonGenerator.Feature

spring.jackson.generator.<feature_name>

true,?false

com.fasterxml.jackson.databind.MapperFeature

spring.jackson.mapper.<feature_name>

true,?false

com.fasterxml.jackson.core.JsonParser.Feature

spring.jackson.parser.<feature_name>

true,?false

com.fasterxml.jackson.databind.SerializationFeature

spring.jackson.serialization.<feature_name>

true,?false

com.fasterxml.jackson.annotation.JsonInclude.Include

spring.jackson.default-property-inclusion

always,?non_null,?non_absent,?non_default,?non_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.pswp.cn/diannao/36786.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/36786.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/36786.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Java數據結構算法(最長遞增序列二分查找)

前言: 最長遞增子序列&#xff08;Longest Increasing Subsequence, LIS&#xff09;是指在一個給定的序列中&#xff0c;找到一個最長的子序列&#xff0c;使得這個子序列中的元素是單調遞增的。子序列不要求在原序列中連續。 實現原理 使用一個 tails 列表&#xff0c;其中…

Java對象集合按照指定元素順序排序

需求背景 最近在對一個集合列表的數據進行排序&#xff0c;需求是要集合數據按照一個排序狀態值進行排序&#xff0c;而這個狀態值&#xff0c;不是按照從小到大這樣的順序排序的&#xff0c;而是要按照特定的順序&#xff0c;比如按照1, 0, 2的順序排的&#xff0c;所以需要自…

clickhouse count和uniqCombined

count(distinct ) 和 uniqCombined 獲取去重后的總數。 去重&#xff1a;order by distinct argMax group by 哪個好&#xff1f;&#xff1f; clickhouse數據去重函數介紹&#xff08;count distinct&#xff09;_clickhouse distinct-CSDN博客

stm32-USART通信

什么是usart&#xff1f;和其他通信又有什么區別&#xff1f; 如下圖&#xff1a; USART是一種用于串行通信的設備&#xff0c;可以在同步和異步模式下工作。 usart有兩根數據線&#xff0c;一根發送線&#xff08;tx&#xff09;一根接收線&#xff08;rx&#xff09;&#x…

2D卷積核處理3D(時序)數據

2D卷積核處理3D&#xff08;時序&#xff09;數據 一、Make A Video的處理方法&#xff08;PseudoConv3d&#xff09;二、Tune A Video的處理方法&#xff08;InflatedConv3d&#xff09;比較與分析相似點不同點結論 Conv2D一般用于處理image&#xff0c;dim一般是4&#xff0c…

準備了一些簡單的面試題

當了一次面試官&#xff0c;主要是面試爬蟲崗位&#xff0c;具體涉及scrapy爬蟲框架和一些數據存儲的小問題。具體的問題如下&#xff1a; scrapy框架如何將單機版爬蟲改為分布式爬蟲【使用scrapy_redis】&#xff0c;具體來講需要修改哪幾個組件的哪些具體部分Spider 1. 如何…

python3 List常用函數詳細解釋

python中 列表&#xff08;list&#xff09;的copy辦法 1.先解決一個報錯。 a [1,2,3] b a.copy print( b)報錯&#xff1a; AttributeError: builtin_function_or_method object has no attribute copy這是因為a.copy語句并沒有執行copy函數&#xff0c;而是把a.copy這個函…

React Antd ProTable 如何設置類似于Excel的篩選框

React Antd ProTable 如何設置類似于Excel的篩選框 目標&#xff1a;在web頁面的table表格中完成類似于EXCEL的Filter篩選功能。 示例圖&#xff1a;點擊標題列上方的漏斗狀圖標&#xff0c;即可對數據進行篩選。 ProTable 前景提要 ProTable API中有說明&#xff0c;是有…

解決所有終端中文輸出亂碼的問題

一、系統自帶的cmd.exe 以及 Git的bash.exe、sh.exe、git-bash.exe和git-cmd.exe&#xff0c;和PowerShell默認使用“當前系統區域設置”設定好的936 (ANSI/OEM - 簡體中文 GBK)語言編碼。 1、[當前代碼頁] 的936 (ANSI/OEM - 簡體中文 GBK) 是導致中文亂碼的原因 在控制面板→…

網絡抓包分析工具

摘要 隨著網絡技術的快速發展&#xff0c;網絡數據的傳輸和處理變得日益復雜。網絡抓包分析工具作為網絡故障排查、性能優化以及安全審計的重要工具&#xff0c;對于提升網絡管理的效率和準確性具有重要意義。本文旨在設計并實現一款高效、易用的網絡抓包分析工具&#xff0c;…

期末測試一

字符數組的排序注意的問題 &#xff1a; 1.對于輸入字符的時候 如果給出了要輸入幾個字符 n >>>>> for ( i 0 ; i < n ;i ) { scanf("%c",&ch); } 如果說直到輸入到換行符結束 >>>>>>while ( ch! \ n ) 這個需要額…

CSS|04 復合選擇器偽類選擇器屬性選擇器美化超鏈接

基本選擇器&#xff1a;見上篇基本選擇器 復合選擇器選擇器1,選擇器2{屬性:值;} 多元素選擇器&#xff0c;同時匹配選擇器1和選擇器2&#xff0c;多個選擇器之間用逗號分隔舉例&#xff1a; p,h1,h2{margin:0px;}E F{屬性:值;} 后代元素選擇器&#xff0c;匹配所有屬于E元素后…

基于長短時記憶網絡LSTM的TE過程故障診斷(MATLAB R2021B)

實驗所用 TE 仿真過程的數據集是網上公開的數據集&#xff0c;該數據集中的訓練集和測試集分別包含 20 種故障工況和一種正常工況數據&#xff0c;其中所采集的每個樣本信號包含 41 個測量變量和 11 個控制變量&#xff0c;所以每個時刻采集到的樣本有 52 個觀測變量。 TE 仿真…

NoSQL之Redis配置與管理

目錄 一、關系型數據庫和非關系型數據庫 1.關系型數據庫 2.非關系型數據庫 3.關系型數據庫和非關系型數據庫區別 二、Redis 1.Redis簡介 2.Redis 的優點 3.Redis 使用場景 4.Redis的數據類型 5.哪些數據適合放入緩存中&#xff1f; 6.Redis為什么這么快&#xff1f;…

BUG:AttributeError: module ‘websocket‘ has no attribute ‘enableTrace’

AttributeError: module ‘websocket’ has no attribute enableTrace’ 環境 windows 11 Python 3.10websocket 0.2.1 websocket-client 1.8.0 websockets 11.0.3 rel 0.4.9.19詳情 一開始…

ActiveMQ camel

游覽器輸入地址: http://127.0.0.1:8161/admin/ 訪問activemq管理臺 賬號和密碼默認為: admin/admin# yml配置的密碼也是如下的密碼 activemq:url: failover:(tcp://localhost:61616)username: adminpassword: adminComponent public class ActiveMqReceiveRouter extends Rout…

AudioLM音頻生成模型

GPT-4o (OpenAI) AudioLM&#xff08;Audio Language Model&#xff09;是一種生成音頻的深度學習模型。它可以通過學習語言模型的結構來生成連貫和高質量的音頻信號。這類模型通常應用于語音合成、音樂生成和音頻內容生成等領域。以下是一些與AudioLM相關的核心概念和技術細…

【JavaEE進階】Spring AOP使用篇

目錄 1.AOP概述 2.SpringAOP快速入門 2.1 引入AOP依賴 2.2 編寫AOP程序 3. Spring AOP詳解 3.1 Spring AOP 核心概念 3.1.1切點(Pointcut) 3.1.2 連接點 (Join Point) 3.1.3 通知(Advice) 3.1.4 切面(Aspect) 3.2 通知類型 3.3PointCut 3.4 切面優先級 3.5 切點表…

基于經典滑膜控制的永磁同步電機調速系統MATLAB仿真

滑膜控制器 取PMSM狀態變量為&#xff1a; ωref為目標轉速&#xff0c;ωm為電機輸出轉速。將此式求導得&#xff1a; 定義系統滑模面函數為&#xff1a; 對滑模面函數求導 在電機實際控制時&#xff0c;滑模控制方法存在高頻抖振問題&#xff0c;則需要選取合適的指數趨近率…

web前端——css(一篇教會網頁制作)

目錄 一、基本語法 1.行內樣式表 2.內嵌樣式表 3.外部樣式表 二、選擇器 1.標簽選擇器 2.類選擇器 3.id 選擇器 4.通配選擇器 三、常見修飾 1.文本 2.背景 3.列表 4.偽類 5.透明度 6.塊級、行級、行級塊標簽 7.div 和 span 四、盒子模型&#xff08;重點&…