SoFunction
Updated on 2025-03-03

Springboot configures json serialization through ObjectMapper

Preface

Spring Boot integrates Jackson by default. ObjectMapper is a core class in the Jackson library. It is the main tool for converting Java objects into JSON strings and converting JSON strings back to Java objects. It is mainly used to format data into a specified format for easy display.

1. ObjectMapper mainly provides the following methods

1. configure(SerializationFeature f, boolean state);// Used to configure serialization, deserialization, JsonParser feature, JsonGenerator feature,
2. enable(T f, T…)//enable function
3. Disable(T f, T…)//Disable function
4. registerModule(Module module)//Register serializer
5. readValue(String content, Class valueType) //Deserialize the JSON string into a Java object of the specified type.
6. writeValueAsString(Object value) //Serialize Java objects into JSON strings.
//The above T can be SerializationFeature, DeserializationFeature,

2. Configure json formatting globally in springboot

By creating a configuration class, registering an ObjectMapper and converting the date to a specified format through a serializer, converting the Long type to a string type. At the same time, the following configuration also solves the problem of the interface receiving unknown parameters without throwing exceptions. In fact, you can copy the following code and add the configuration you need. In fact, there are quite a lot of related json formatting configurations. If you need it, you can query the configuration parameters in the source code.

import ;
import ;
import ;
import ;
import .;
import .;
import .;
import .;
import .;
import .;
import .;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

/**
  * json processing
  * @aporism You are lucky to have someone to help one to help you, is just one should do anything for you, because life is your own, you are responsible for yourself
  */
@Configuration
public class JacksonHandle {
    private static final String DEFAULT_DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
    private static final String DEFAULT_TIME_PATTERN = "HH:mm:ss";
    @Bean
    @Primary
    public ObjectMapper objectMapper(){
        ObjectMapper objectMapper = new ObjectMapper();
        //Date Serializer        JavaTimeModule javaTimeModule = new JavaTimeModule();
        //Date serialization        (, new LocalDateTimeSerializer((DEFAULT_DATE_TIME_PATTERN)));
        (, new LocalDateSerializer((DEFAULT_DATE_PATTERN)));
        (, new LocalTimeSerializer((DEFAULT_TIME_PATTERN)));
        //Date deserialization        (, new LocalDateTimeDeserializer((DEFAULT_DATE_TIME_PATTERN)));
        (, new LocalDateDeserializer((DEFAULT_DATE_PATTERN)));
        (, new LocalTimeDeserializer((DEFAULT_TIME_PATTERN)));
        //Deserialization - Disable throwing exceptions when encountering unknown attributes        (DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        //Register serializer        (javaTimeModule);
        //Custom serializer        SimpleModule module = new SimpleModule();
        //Add to serialize long to string        (, new ToStringSerializer());
        //Register serializer        (module);
        return objectMapper;
    }
}

3. The following are some specific configuration definitions I found. You can refer to it if you need it.

SerializationFeature configuration parameters

The following is the specific meaning of the configuration item in the serialized configuration class SerializationFeature:
1. WRAP_ROOT_VALUE(false)
Meaning: If a serialized Java object is a single value (such as a primitive type or string), it is wrapped in an array.
Default value: false
Example: If a string "hello" is serialized, "hello" is output by default; if set to true, [ "hello"] is output.
2. INDENT_OUTPUT(false)
Meaning: Whether to indent the output JSON to improve readability.
Default value: false
Example: If set to true, the output JSON will be formatted, for example { "name": "John" } becomes:

  {
    "name": "John"
  }
  • FAIL_ON_EMPTY_BEANS(true)
    Meaning: Whether an exception is thrown when an empty Java Bean is serialized.
    Default value: false
    Example: If you serialize a Java Bean without fields, an exception will be thrown when set to true.
  • FAIL_ON_SELF_REFERENCES(true)
    Meaning: Whether an exception is thrown when serializing a circular reference (i.e. the object reference itself).
    Default value: false
    Example: If you serialize an object containing your own reference, an exception will be thrown when set to true.
  • WRAP_EXCEPTIONS(true)
    Meaning: Whether to wrap all exceptions as JsonMappingException.
    Default value: false
    Example: If an exception occurs during serialization, the original exception will be thrown directly by default; if set to true, it will be wrapped as JsonMappingException.
  • FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS(true)
    Meaning: Whether an exception is thrown when deserializing an unwrapped type identifier is encountered.
    Default value: false
    Example: If an unwrapped type identifier is encountered during deserialization, an exception is thrown when set to true.
  • WRITE_SELF_REFERENCES_AS_NULL(false)
    Meaning: Whether to serialize the object referenced to null when serializing the circular reference.
    Default value: false
    Example: If you serialize an object containing your own reference, set to true will serialize the part of the circular reference to null.
  • CLOSE_CLOSEABLE(false)
    Meaning: Whether to close the Closeable object after serialization is completed.
    Default value: false
    Example: If Closeable objects are used during serialization, when set to true, these objects will be closed after serialization is completed.
  • FLUSH_AFTER_WRITE_VALUE(true)
    Meaning: Whether to refresh the output stream immediately after each serialization.
    Default value: false
    Example: If set to true, the output stream will be refreshed immediately after each serialization is complete.
  • WRITE_DATES_AS_TIMESTAMPS(true)
    Meaning: Whether the date is serialized in a timestamp form.
    Default value: true
    Example: If set to false, the date will be serialized as a string.
  • WRITE_DATE_KEYS_AS_TIMESTAMPS(false)
    Meaning: Whether the date key is serialized in a timestamp form.
    Default value: false
    Example: If set to true, the date key will be serialized as a timestamp.
  • WRITE_DATES_WITH_ZONE_ID(false)
    Meaning: Whether the date contains time zone information.
    Default value: false
    Example: If set to true, the date serialization will include time zone information.
  • WRITE_DATES_WITH_CONTEXT_TIME_ZONE(true)
    Meaning: Whether the date is serialized using the time zone in the context.
    Default value: true
    Example: If set to false, the date will be serialized using the UTC time zone.
  • WRITE_DURATIONS_AS_TIMESTAMPS(true)
    Meaning: Whether the duration is serialized in the form of a timestamp.
    Default value: true
    Example: If set to false, the duration will be serialized as a string.
  • WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS(false)
    Meaning: Whether the character array is serialized in the form of a JSON array.
    Default value: false
    Example: If set to true, the character array will be serialized as a JSON array.
  • WRITE_ENUMS_USING_TO_STRING(false)
    Meaning: Whether the enum value is serialized using the result of its toString() method.
    Default value: false
    Example: If set to true, the enum value will be serialized with its toString() result.
  • WRITE_ENUMS_USING_INDEX(false)
    Meaning: Whether the enum value is serialized using its index.
    Default value: false
    Example: If set to true, the enum value is serialized by its index.
  • WRITE_ENUM_KEYS_USING_INDEX(false)
    Meaning: Whether the enumeration key is serialized using its index.
    Default value: false
    Example: If set to true, the enum key is serialized with its index.

DeserializationFeature configuration parameters

  • USE_BIG_DECIMAL_FOR_FLOATS
    Purpose: Whether to use the BigDecimal type when serializing floating point numbers.
    Default: false — Use the double type.
  • USE_BIG_INTEGER_FOR_INTS
    Purpose: Whether to use the BigInteger type when serializing integers.
    Default: false — Use the long type.
  • USE_LONG_FOR_INTS
    Purpose: Whether to use the long type when serializing integers.
    Default: false — Use the int type.
  • USE_JAVA_ARRAY_FOR_JSON_ARRAY
    Purpose: When serializing JSON arrays, whether to use Java's array type.
    Default: false — Use the JsonArray type.
  • FAIL_ON_UNKNOWN_PROPERTIES
    Purpose: Whether an exception is thrown when an unknown property is encountered.
    Default: true — Throw an exception.
  • FAIL_ON_NULL_FOR_PRIMITIVES
    Purpose: Whether an exception is thrown when a null value of the primitive type is encountered.
    Default: false — No exception is thrown.
  • FAIL_ON_NUMBERS_FOR_ENUMS
    Purpose: Whether an exception is thrown when an enum type numeric representation is encountered.
    Default: false — No exception is thrown.
  • FAIL_ON_INVALID_SUBTYPE
    Purpose: Whether an exception is thrown when an invalid subtype is encountered.
    Default: true — Throw an exception.
  • FAIL_ON_READING_DUP_TREE_KEY
    Purpose: Whether an exception is thrown when reading a duplicate tree key.
    Default: false — No exception is thrown.
  • FAIL_ON_IGNORED_PROPERTIES
    Purpose: Whether an exception is thrown when an ignored property is encountered.
    Default: false — No exception is thrown.
  • FAIL_ON_UNRESOLVED_OBJECT_IDS
    Purpose: Whether an exception is thrown when an unresolved object ID is encountered.
    Default: true — Throw an exception.
  • FAIL_ON_MISSING_CREATOR_PROPERTIES
    Purpose: Whether an exception is thrown when the constructor attribute is missing.
    Default: false — No exception is thrown.
  • FAIL_ON_NULL_CREATOR_PROPERTIES
    Purpose: Whether an exception is thrown when the constructor property is null.
    Default: false — No exception is thrown.
  • FAIL_ON_MISSING_EXTERNAL_TYPE_ID_PROPERTY
    Purpose: Whether to throw an exception when the external type ID attribute is missing.
    Default: true — Throw an exception.
  • FAIL_ON_TRAILING_TOKENS
    Purpose: Whether an exception is thrown when a trailing mark is encountered.
    Default: false — No exception is thrown.
  • WRAP_EXCEPTIONS
    Purpose: Whether the packaging is abnormal.
    Default: true — wrapping exception.
  • ACCEPT_SINGLE_VALUE_AS_ARRAY
    Purpose: Whether to accept a single value as an array.
    Default: false — Not accepted.
  • UNWRAP_SINGLE_VALUE_ARRAYS
    Purpose: Whether to unpack a single value array.
    Default value: false — does not unpack.
  • UNWRAP_ROOT_VALUE
    Purpose: Whether to unpack the root value.
    Default value: false — does not unpack.
  • ACCEPT_EMPTY_STRING_AS_NULL_OBJECT
    Purpose: Whether to accept empty strings as null objects.
    Default: false — Not accepted.
  • ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT
    Purpose: Whether to accept empty arrays as null objects.
    Default: false — Not accepted.
  • ACCEPT_FLOAT_AS_INT
    Purpose: Whether to accept floating point numbers as integers.
    Default: true — Accepted.
  • READ_ENUMS_USING_TO_STRING
    Purpose: Whether to use the toString() method to read the enumeration.
    Default: false — Not used.
  • READ_UNKNOWN_ENUM_VALUES_AS_NULL
    Purpose: Whether to read unknown enum value as null.
    Default: false — not read as null.
  • READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE
    Purpose: Whether to use the default value to read unknown enum values.
    Default: false — The default value is not used.
  • READ_DATE_TIMESTAMPS_AS_NANOSECONDS
    Purpose: Whether to read the date timestamp as nanoseconds.
    Default: true — read as nanoseconds.
  • ADJUST_DATES_TO_CONTEXT_TIME_ZONE
    Purpose: Whether to adjust the date to the context time zone.
    Default: true — Adjust.
  • EAGER_DESERIALIZER_FETCH
    Purpose: Whether to urgently obtain the deserializer.
    Default: true — urgently obtained.

This is the end of this article about Springboot configuring json serialization through ObjectMapper. For more related Springboot ObjectMapper configuration json serialization content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!