Ignore operations that are null properties when serializing entity classes or objects
- 2021-10-15 10:26:50
- OfStack
First, configure in the configuration file
Direct configuration in application. xml, which is global configuration, and all attributes returned to front-end objects as null or "" are not serialized;
spring:
jackson:
# Entity class conversion json When the field is null Do not participate in serialization
default-property-inclusion: NON_EMPTY
Four Types of default-property-inclusion
ALWAYS Default The NON_DEFAULT attribute is not serialized for the default value NON_EMPTY attribute "" or NULL is not serialized No serialization when NON_NULL attribute is NULLSecond, set each class separately
Add @ JsonInclude (Include.NON_NULL) to the object attribute that needs to ignore serialization when it is empty, or directly add it to the class, indicating that 1 does not participate in serialization when the attribute of the whole object is null;
You can set different types in @ JsonInclude parentheses
Include. Include. ALWAYS Default The Include. NON_DEFAULT property is not serialized by default Include. NON_EMPTY attribute "" or NULL is not serialized Include. NON_NULL is not serialized when the attribute is NULLIf the global is configured and an object is annotated, the annotation overrides the global setting.
SpringBoot2. x does not reverse null value attributes
Sometimes, there is no value of the attribute in the data we return, or the value of the attribute is a blank string, which will waste network traffic, or the bug existing in the front-end framework will cause the null value or the blank string to report errors when rendering.
Treatment mode
Type 1
Global way: Add the following attributes to the configuration file of SpringBoot to achieve global filtering
spring.jackson.default-property-inclusion=non_empty
Type 2
Local way: Add the following annotations to the returned entity class attributes or class names to achieve the filtering effect
@JsonInclude(JsonInclude.Include.NON_EMPTY)
Attention
This is also true for empty collections. Attribute 1 has the following optional values
Include. Include. ALWAYS Default The Include. NON_DEFAULT property is not serialized by default Include. NON_EMPTY property is null ("") or NULL is not serialized Include. NON_NULL property is NULL not serialized