SoFunction
Updated on 2025-04-06

SpringBoot uses Jackson to explain in detail

Overview

Springboot configures JackSon to process class attributes, JavaBeans are serialized into JSON format, commonly used frameworks: Alibaba fastjson, Google gson, Jackson, etc.

  • ① Performance: Jackson > Fastjson > Gson > Same structure
  • ② Jackson, Fastjson, and Gson library each has its own characteristics and their own expertise.

Jackson is part of the spring-boot-starter-json dependency, and spring-boot-starter-web contains spring-boot-starter-json. That is to say, when the project is introduced

After spring-boot-starter-web, spring-boot-starter-json will be automatically introduced without the need to be introduced separately.

Common annotations

Basic annotations

annotation usage
@JsonProperty Used as an attribute, converting the name of the attribute into another name when serializing it. Example: @JsonProperty("birth_date") private Date birthDate
@JsonIgnore It can be used on fields, getter/setter, and constructor parameters. The same effect will have an impact on the corresponding fields. Make the corresponding fields not participate in serialization and deserialization.
@JsonIgnoreProperties This annotation is a class annotation, so that the corresponding fields do not participate in serialization and deserialization. eg:@JsonIgnoreProperties({"password","id"}) public class Person
@JsonFormat Used as an attribute or method, converting the format of the attribute into a specified format when serializing the attribute. Example: @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm") public Date getBirthDate()
@JsonPropertyOrder This annotation is a class annotation, similar to the index attribute of @JsonProperty, which specifies the order of properties in json during serialization. Example: @JsonPropertyOrder({ "birth_Date", "name" }) public class Person
@JsonCreator It is used for construction methods and is used in conjunction with @JsonProperty, and is suitable for construction methods with parameters. Example: @JsonCreator public Person(@JsonProperty("name")String name) {…}
@JsonAnySetter Used for attributes or methods, set the undeserialized attribute names and values ​​to store them as key values ​​in the map @JsonAnySetter public void set(String key, Object value) { (key, value); }
@JsonAnyGetter Apply to attributes or methods to get all unserialized properties public Map<String, Object> any() { return map; }
@JsonSetter Apply to attributes or methods, specifying the deserialized field name @JsonSetter("_id") public String setId(String id) { return =id; }
@JsonGetter Apply to a method or field, specifying the serialized field name @JsonGetter("_id") public String getId() { return id; }
@JsonNaming Class annotation. During serialization, this annotation can convert the field names named camels into underscore-separated lowercase letter naming. When deserializing, underscore-separated lowercase letters can be converted to camel-named field names. Example: @JsonNaming()
@JsonRootName Class annotation. It needs to be enabled (SerializationFeature.WRAP_ROOT_VALUE), which is used to output a JSON string with the root attribute name during serialization, in the form {"root_name":{"id":1,"name":"zhangsan"}}.
@JsonAutoDetect Specify the attribute (de)serialization range
@JsonIgnoreType This type of (de)serialization will be ignored
@JsonInclude How to serialize null values
@JsonPropertyDescription JSON's schema description
@JsonUnwrapped Pull its properties up to expand them by a level
@JsonView Return different attributes under different interfaces eg: Use of @JsonView
@JacksonInject There are some missing attributes in the json field. When changing to entity class, the attributes that do not exist will be null, but in some requirements, we need to set the attributes that are null as default.
@JsonEnumDefaultValue Enumeration value when deserialized unknown
@JsonRawValue Use the original value without escaping eg:"content":"Test content", not \"content\":\"Test content\"
@JsonValue It can be used for up to one property of the class (multiple properties will throw an exception if applied to this annotation), and pull this property up to expand it at a level, and other fields do not participate in (de)serialization
@JsonKey At most one property of a class can be used (multiple properties will throw an exception if applied to this annotation). When this type object is used as the key of the Map data structure, the property value marked with this annotation will be used as the field name of the json string.
@JsonFilter Apply to properties, filter attribute eg:@JsonFilter("non-pwd") private char[] password = new char[]{'0', '\u0343', '&'}; (new SimpleFilterProvider().addFilter("non-pwd", ("password")));
@JsonAlias Apply to attributes, multiple candidate field names can be mapped to the same attribute during deserialization.
@JsonMerge Apply to attributes, when deserializing the collection type attribute, fuse the elements in Json with the default elements in the field eg:@JsonMerge private List<String> hobbies = new ArrayList<>(("basketball"));

Common annotation examples

1、JsonProperty

Similar to the alias of fields in SQL, used for serialization, use annotation field attributes to replace the original field attributes

@JsonProperty("userName")
private String name;
The serialization result is:In serializedjsonIn the string,userNameReplacedname
{"userName":"tom"}

2、JsonIgnore

Ignore this field when serializing

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
    @JsonIgnore
    private Long id;
    @JsonProperty("userName")
    private String name;
    @JsonIgnore
    private Integer age;
    @JsonIgnore
    private Date birthday;
}

The serialization result is:
{"userName":"tom"}

3、JsonIgnoreProperties

  • Serialization @JsonIgnoreProperties is similar to @JsonIgnore. It is used on classes. The annotation uses field alias.
import ;
import ;
import ;
import ;
import ;
import ;

import ;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties({"id","userName","birthday"})
public class User {
    private Long id;
    @JsonProperty("userName")
    private String name;
    private Integer age;
    private Date birthday;
}

The serialization result is:
{"age":23}
  • @JsonIgnoreProperties(ignoreUnknown = true) is used to ignore field mismatch, which is equivalent to (DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

【@JsonTypeName @JsonTypeInfo】 Used on the class and add a layer during serialization

import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonTypeName(value = "user")
@JsonTypeInfo(include = .WRAPPER_OBJECT, use = )
public class User {
    private Long id;
    @JsonProperty("userName")
    private String name;
    private Integer age;
    private Date birthday;
}

Serialization results:

{"user":{"id":1,"age":23,"birthday":1587891781603,"userName":"tom"}}

4、JsonRootName

Combining the annotation @JsonRootName("user") and (SerializationFeature.WRAP_ROOT_VALUE) on the serialization, deserialization is useless;

5、JsonFormat

Format date format

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    @JsonProperty("userName")
    private String name;
    private Integer age;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss:SSS",locale = "zh", timezone = "GMT+8")
    private Date birthday;
}
Serialization results:

{"id":1,"age":23,"birthday":"2020-04-26 17:09:32:818","userName":"tom"}

Configuration

Basic configuration

spring:
  jackson:
    # Set the property naming strategy, corresponding to the constant value in PropertyNamingStrategy under jackson, SNAKE_CASE-returned json camel to underscore, json body underscore is automatically transferred to the backend    property-naming-strategy: SNAKE_CASE
    # Global setting of @JsonFormat format pattern    date-format: yyyy-MM-dd HH:mm:ss
    # Local time zone    locale: zh_CN
    # Set the global time zone    time-zone: GMT+8
    # Commonly used, globally set the serialization method of pojo or attribute annotated by @JsonInclude    default-property-inclusion: NON_NULL #Attributes that are not empty will be serialized, the specific attributes can be found    # The general default is that the enumeration attribute in the enumeration class SerializationFeature is key, and the value is boolean sets the jackson serialization feature. For the specific key, please refer to the SerializationFeature source code.    visibility:
      #Visible range of attribute serialization      getter: non_private
      #Visible range of attribute deserialization      setter: protected_and_public
      #Deserialization of static factory methods      CREATOR: public_only
      #Field      FIELD: public_only
      #Bole serialization      IS_GETTER: public_only
      #All types (i.e. getter setter FIELD) are not affected and meaningless      NONE: public_only
      #All types (i.e. getter setter FIELD) are affected by it (use with caution)      ALL: public_only
    serialization:
      #Detecting whether there is a root node      WRAP_ROOT_VALUE: false
      #Whether to use indentation, format the output      INDENT_OUTPUT: false
      FAIL_ON_EMPTY_BEANS: true # Whether an error is reported when the object does not contain any fields, the default is true      FAIL_ON_SELF_REFERENCES: true #Report error in circular reference      WRAP_EXCEPTIONS: true #Is the packaging abnormal?      FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS: true Whether the class marked with #JsonUnwrapped has type information reported an error      WRITE_SELF_REFERENCES_AS_NULL: false #Return null by loop reference      CLOSE_CLOSEABLE: true #If the object implements the CLOSEABLE interface, will the Close method be called after serialization      FLUSH_AFTER_WRITE_VALUE: false #Whether to force refresh after stream object serialization      WRITE_DATES_AS_TIMESTAMPS: true # The returned conversion to a timestamp      WRITE_DATES_WITH_ZONE_ID: true #2011-12-03T10:15:30+01:00[Europe/Paris] with time zone id      WRITE_DURATIONS_AS_TIMESTAMPS: true #Convert DURATIONS to timestamp      WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS: false #Whether the character array outputs the json array (false outputs the string)      WRITE_ENUMS_USING_TO_STRING: false # toString enum output      WRITE_ENUMS_USING_INDEX: false #Enum Subscript      WRITE_ENUM_KEYS_USING_INDEX: false #Enum key similar      WRITE_NULL_MAP_VALUES: false # Whether to output an empty entry in the map (this feature has expired, please use JsonInclude annotation)      WRITE_EMPTY_JSON_ARRAYS: true # Is the object attribute value empty set outputting an empty json array      WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED: false #Whether to expand the set of individual elements, (i.e., remove the array symbol "[]")      WRITE_BIGDECIMAL_AS_PLAIN: false #Whether to call BigDecimal#toPlainString() output      WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS: #Output timestamp as nanoseconds      ORDER_MAP_ENTRIES_BY_KEYS: false After #map serialization, whether to sort it with key      EAGER_SERIALIZER_FETCH: true #Whether to get the serializer immediately      USE_EQUALITY_FOR_OBJECT_ID: false #Whether objectId is used to compare whether it is equal (applied in the ORM framework Hibernate)
    # The enumeration attribute in the enumeration class DeserializationFeature is key, and the value is boolean sets the jackson deserialization feature. For specific keys, please refer to the DeserializationFeature source code.    deserialization:
      USE_BIG_DECIMAL_FOR_FLOATS: false #Deserialize floating point numbers to BIG_DECIMAL      USE_BIG_INTEGER_FOR_INTS: false #Deserialize integers to BIG_INTEGER      USE_LONG_FOR_INTS: false #Deserialize the integer into a long whole      USE_JAVA_ARRAY_FOR_JSON_ARRAY: false #When there is no clear type, is it deserialized to the json array (if true, it corresponds to Object[], otherwise it is List<?>)      FAIL_ON_UNKNOWN_PROPERTIES: false # Commonly used, whether an error is reported when the attribute in json does not exist, default true      FAIL_ON_NULL_FOR_PRIMITIVES: false #Detect null as a basic data type? Is it an error?      FAIL_ON_NUMBERS_FOR_ENUMS: false #Does it report an error if an integer deserializes it as an enum?      FAIL_ON_INVALID_SUBTYPE: false #No error is reported if the appropriate subclass cannot be found (such as the subtype specified by JsonTypeInfo)      FAIL_ON_READING_DUP_TREE_KEY: false #Does the duplicate json field report an error?      FAIL_ON_IGNORED_PROPERTIES: false #If there is an explicitly marked field in the java entity field in json, is it reported an error      FAIL_ON_UNRESOLVED_OBJECT_IDS: true #If deserialization occurs, does it report an error?      FAIL_ON_MISSING_CREATOR_PROPERTIES: false #If the parameters of the static factory method are missing, whether the error is reported (false, use null instead of the required parameters)      FAIL_ON_NULL_CREATOR_PROPERTIES: false #Whether the parameters of the binding empty value to the constructor or static factory method are reported as errors      FAIL_ON_MISSING_EXTERNAL_TYPE_ID_PROPERTY: false #Annotation#EXTERNAL_PROPERTY tag attribute is missing, is it reported an error      FAIL_ON_TRAILING_TOKENS: false #Whether the trailing token is reported as an error (if true, call JsonParser#nextToken to check the integrity of json)      WRAP_EXCEPTIONS: true #Whether the exception occurred when packaging deserialization      ACCEPT_SINGLE_VALUE_AS_ARRAY: true #Whether an object is encapsulated into a single element array during deserialization      UNWRAP_SINGLE_VALUE_ARRAYS: false #Whether to expand a single element array into an object during deserialization      UNWRAP_ROOT_VALUE: false #Will the root node be unwrapped      ACCEPT_EMPTY_STRING_AS_NULL_OBJECT: false #Whether to use the null character ("") string as a null object      ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT: false #Whether to accept empty array ("[]") as null      ACCEPT_FLOAT_AS_INT: true #Whether to accept floating point numbers as integers      READ_ENUMS_USING_TO_STRING: false #Read according to the enum toString() method, (false is read according to the enum name() method)      READ_UNKNOWN_ENUM_VALUES_AS_NULL: false #Read unknown enum as null      READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE: false #Read an unknown enum and treat it as an enum marked by JsonEnumDefaultValue annotation      READ_DATE_TIMESTAMPS_AS_NANOSECONDS: true # Treat timestamps as nanoseconds (false, then milliseconds)      ADJUST_DATES_TO_CONTEXT_TIME_ZONE: true #Detectification will adapt to the time zone provided by DeserializationContext#getTimeZone() (this feature is only valid for time/date in java8)      EAGER_DESERIALIZER_FETCH: true  #Whether to get the deserializer immediately    # The enumeration attribute in the enumeration class MapperFeature is key, and the value is boolean sets the jackson ObjectMapper feature.    # ObjectMapper is responsible for json reading and writing, json and pojo, and json tree in jackson. For specific features, please refer to MapperFeature, the regular default is    mapper:
      USE_ANNOTATIONS: true #Whether to use annotations to reflect on yourself (check these for JsonProperties)      # Use getter instead of setter detection attributes. This is for the collection type, and the properties of the collection can be directly modified.      USE_GETTERS_AS_SETTERS: true #default false      PROPAGATE_TRANSIENT_MARKER: false #How to deal with transient fields, if true (this property cannot be accessed), if false, it cannot be accessed through the field (it can still be accessed using getter and setter)      AUTO_DETECT_CREATORS: true # Whether to automatically detect constructors or static factory methods with single parameter named valueOf      AUTO_DETECT_FIELDS: true # Whether to automatically detect fields (if true, all public instance fields will be treated as attributes)      AUTO_DETECT_GETTERS: true #Determine whether to automatically detect the conventional "getter" method according to the standard bean naming convention (excluding is getter)      AUTO_DETECT_IS_GETTERS: true #Determine whether to automatically detect the "is getter" method according to the standard bean naming convention      AUTO_DETECT_SETTERS: false # Determine whether to automatically detect the "setter" method according to the standard bean naming convention      REQUIRE_SETTERS_FOR_GETTERS: false The #getter method must have corresponding setter or field or constructor parameters to be considered as an attribute      ALLOW_FINAL_FIELDS_AS_MUTATORS: true #Is it possible to modify the final member field      INFER_PROPERTY_MUTATORS: true # Can attributes be inferred (that is, it is invisible using fields and setters, but getters can be visible to infer attributes)      INFER_CREATOR_FROM_CONSTRUCTOR_PROPERTIES: true # Whether to automatically infer the ConstructorProperties annotation      CAN_OVERRIDE_ACCESS_MODIFIERS: true #Call AccessibleObject#setAccessible to true. Change the originally invisible property to visible      OVERRIDE_PUBLIC_ACCESS_MODIFIERS: true #Call AccessibleObject#setAccessible on all properties and set it to true. (that is, use is public)      USE_STATIC_TYPING: false #Serialize the declared static type or dynamic type JsonSerialize#typing annotation can override it      USE_BASE_TYPE_AS_DEFAULT_IMPL: false # Whether to use basic classes as the default implementation of deserialization @      DEFAULT_VIEW_INCLUSION: true #Whether attributes without JsonView annotation tags will be included in the json serialized view      SORT_PROPERTIES_ALPHABETICALLY: false #Serialize fields in alphabetical order (if false, in the order of field declaration)      ACCEPT_CASE_INSENSITIVE_PROPERTIES: false #Case-insensitive when deserializing attributes (true will affect performance)      ACCEPT_CASE_INSENSITIVE_ENUMS: false #Enum deserialization does not differ from case      ACCEPT_CASE_INSENSITIVE_VALUES: false #Allow some enumerations to parse text-based value types but ignore the case of deserialized values, such as date/time type deserializer      USE_WRAPPER_NAME_AS_PROPERTY_NAME: false # Override the property name with the wrapper name AnnotationIntrospector#findWrapperName specified      USE_STD_BEAN_NAMING: false # Is it a function that is strictly compatible with the Bean name, if enabled (getURL()) becomes a URL (jackson default false, url)      ALLOW_EXPLICIT_PROPERTY_RENAMING: false #Whether JsonProperty annotation is allowed to override PropertyNamingStrategy      ALLOW_COERCION_OF_SCALARS: true # Is it allowed to use text titles, that is, the string "true" is regarded as boolean true, and the string "1.0" is regarded as "double"      IGNORE_DUPLICATE_MODULE_REGISTRATIONS: true #If the module is the same (Module#getTypeId() returns the same value), only the first time you can actually call the registration method      IGNORE_MERGE_FOR_UNMERGEABLE: true #Whether to ignore the error when merging properties that cannot be merged      BLOCK_UNSAFE_POLYMORPHIC_BASE_TYPES: false #Block unsafe base classes (such as Object Closeable Cloneable AutoCloseable Serializable)    parser:
      AUTO_CLOSE_SOURCE: true # Whether to automatically close the underlying input stream that does not belong to the parser      ALLOW_COMMENTS: false #Whether json annotation is allowed (the Json specification cannot be annotated, but it can be configured here)      ALLOW_YAML_COMMENTS: false #Is yaml comment allowed      ALLOW_UNQUOTED_FIELD_NAMES: false #Is it allowed field names without quotes      ALLOW_SINGLE_QUOTES: false # Whether to allow single quotes, default false      ALLOW_UNQUOTED_CONTROL_CHARS: false #Is it allowed to unescaped control characters      ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER: false #Is it possible to escape backslashes for all characters      ALLOW_NUMERIC_LEADING_ZEROS: false #Whether leading zero 000001 is allowed      ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS: false # Whether to allow leading small dots, such as ".04314", will be parsed into "0.04314"      ALLOW_NON_NUMERIC_NUMBERS: false #Whether NaN type floating point numbers are allowed ("INF" is regarded as positive infinite "-INF" is regarded as negative infinite "NaN" is not a number, and the type is 0 in the divisor)      ALLOW_MISSING_VALUES: false # Whether to allow missing values ​​in json arrays (such as ["value1", "value3",] will be deserialized to ["value1", null, "value3", null])      ALLOW_TRAILING_COMMA: false # Are you allowed to have commas at the end of json (such as {"a": true,})      STRICT_DUPLICATE_DETECTION: false # Whether to enable strict field name repeated checking (it will increase performance overhead by about 20-30% after opening)      IGNORE_UNDEFINED: false #Attribute definition is not found whether an error is reported (this is not for json, but for Avro, protobuf, etc., which requires Schema)      INCLUDE_SOURCE_IN_LOCATION: false # Whether it contains its source information (such as total number of bytes, total number of characters, line number, column number)    generator:
      AUTO_CLOSE_TARGET: true # Whether to automatically close the underlying output stream that does not belong to the generator      AUTO_CLOSE_JSON_CONTENT: true #Whether to automatically complete json (when there is a mismatched JsonToken#START_ARRAY JsonToken#START_OBJECT)      FLUSH_PASSED_TO_STREAM: true #Whether to refresh the generator      QUOTE_FIELD_NAMES: true #Whether to add quotes to the field name      QUOTE_NON_NUMERIC_NUMBERS: true #Whether to quote the NaN floating point number      ESCAPE_NON_ASCII: false #Does non-ASCII codes need to be escaped?      WRITE_NUMBERS_AS_STRINGS: false #Output numbers as strings (prevent Javascript length limits from being truncated)      WRITE_BIGDECIMAL_AS_PLAIN: false #Press BigDecimal's toPlainString() output      STRICT_DUPLICATE_DETECTION: false # Whether to enable strict field name duplicate checking      IGNORE_UNKNOWN: false #Whether the attribute definition is not found or not, the error is reported(This is not forjson,Yes forAvro, protobufWait for needSchemaFormat)

Common configurations

spring:
  jackson:
    #Time formatting    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    #How to serialize empty    default-property-inclusion: non_null    
    serialization:
       #Format output      indent_output: true
      #Ignore objects that cannot be converted      fail_on_empty_beans: false
    deserialization:
      #Allow objects to ignore properties that do not exist in json      fail_on_unknown_properties: false
    parser:
      #Allow special characters and escape characters      allow_unquoted_control_chars: true
      #Single quotes are allowed      allow_single_quotes: true

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.