问题背景
在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
}
在上面的例子中,如果property1
或property2
的值为null,它们将不会被包含在JSON序列化的结果中。
请注意,@JsonInclude
注解可以应用于类级别或属性级别。如果应用于类级别,它将影响该类的所有属性。如果应用于属性级别,它将仅影响该特定属性。
全局配置
这个配置可以通过application.properties
或application.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:
Enum | Property | Values |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.