Spring Boot
Jackson JSON
Customization
JSON Mapper
Java Development

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Spring Boot provides a seamless integration with the Jackson library, which is widely used for JSON processing. By default, Spring Boot uses Jackson's ObjectMapper to convert Java objects to JSON and vice versa. However, customizing the Jackson JSON mapper to fit specific requirements is often necessary. This article will guide you through the process of customizing the Jackson JSON mapper implicitly used by Spring Boot. We will explore different ways to achieve this customization along with relevant examples.

Why Customize Jackson's ObjectMapper?

While Jackson's default configuration satisfies most use cases, there are times when customization is necessary to:

  • Change default serialization or deserialization settings.
  • Support additional data formats or types.
  • Enable or disable specific Jackson features or modules.
  • Implement custom serializers or deserializers for complex types.
  • Modify naming strategies or date formats to fit specific conventions.

Customizing Jackson's ObjectMapper in Spring Boot

Method 1: Using application.properties

Spring Boot allows customization of the JSON mapper via properties. Some commonly used settings can be configured directly through the application.properties or application.yml.

Example:

properties
1# Enables pretty print for JSON output
2spring.jackson.serialization.indent_output=true
3
4# Configures default date format
5spring.jackson.date-format=yyyy-MM-dd
6
7# Sets property naming strategy
8spring.jackson.property-naming-strategy=SNAKE_CASE

Method 2: Using the Jackson2ObjectMapperBuilderCustomizer Interface

For more comprehensive customization, you can use the Jackson2ObjectMapperBuilderCustomizer interface. Implementing this interface allows you to customize the ObjectMapper instance globally.

Example:

java
1import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
2import org.springframework.context.annotation.Bean;
3import org.springframework.context.annotation.Configuration;
4import com.fasterxml.jackson.databind.DeserializationFeature;
5import com.fasterxml.jackson.databind.SerializationFeature;
6
7@Configuration
8public class JacksonConfig {
9
10    @Bean
11    public Jackson2ObjectMapperBuilderCustomizer customizer() {
12        return builder -> {
13            builder.failOnUnknownProperties(false); // Ignore unknown properties in JSON
14            builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
15            builder.featuresToDisable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);
16        };
17    }
18}

Method 3: Direct Customization via ObjectMapper

For situations where more control is needed, you can directly configure an ObjectMapper bean. This method overrides the default mapper instance.

Example:

java
1import org.springframework.context.annotation.Bean;
2import org.springframework.context.annotation.Configuration;
3import com.fasterxml.jackson.databind.ObjectMapper;
4import com.fasterxml.jackson.databind.PropertyNamingStrategies;
5import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
6
7@Configuration
8public class CustomObjectMapperConfig {
9
10    @Bean
11    public ObjectMapper objectMapper() {
12        ObjectMapper mapper = new ObjectMapper();
13        // Set naming strategy
14        mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
15        // Register JavaTimeModule for new date/time API
16        mapper.registerModule(new JavaTimeModule());
17        // Configure additional settings as needed
18        mapper.findAndRegisterModules();
19        return mapper;
20    }
21}

Table: Summary of Customization Methods

MethodDescriptionUse Case
application.propertiesCustomizes via Spring properties.Simple configurations like formatting or enabling pretty print.
Jackson2ObjectMapperBuilderCustomizerProvides a global customization approach.When default features need to be altered or extended globally.
Direct Customization via ObjectMapperOffers direct and comprehensive control over ObjectMapper.Requires complete and specific control over all aspects of mapping.

Additional Details: Handling Complex Types

In some cases, you may need to provide custom serializers or deserializers. For example, serializing a complex object or handling a specific data structure can be done by implementing the JsonSerializer or JsonDeserializer interfaces.

Example: Custom Serializer and Deserializer

java
1import com.fasterxml.jackson.core.JsonGenerator;
2import com.fasterxml.jackson.databind.JsonSerializer;
3import com.fasterxml.jackson.databind.SerializerProvider;
4import com.fasterxml.jackson.databind.annotation.JsonSerialize;
5
6import java.io.IOException;
7
8// Custom Serializer
9public class CustomDateSerializer extends JsonSerializer<Date> {
10    @Override
11    public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
12        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
13        gen.writeString(dateFormat.format(value));
14    }
15}
16
17// Applying the Custom Serializer
18public class Event {
19    @JsonSerialize(using = CustomDateSerializer.class)
20    private Date eventDate;
21
22    // Getters and setters
23}

Conclusion

Customizing Jackson's JSON mapper in Spring Boot is a versatile process, enabling you to configure serialization and deserialization behavior to fit various needs. Whether you're using properties files for quick adjustments or configuring a custom ObjectMapper for granular control, Spring Boot and Jackson offer flexible options to create efficient, tailored JSON processing.


Course illustration
Course illustration

All Rights Reserved.