Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring Boot - Customize the Jackson ObjectMapper
Next article icon

Spring Boot - Customize the Jackson ObjectMapper

Last Updated : 17 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

When using JSON format, Spring Boot will use an ObjectMapper instance to serialize responses and deserialize requests. In this article, we will take a look at the most common ways to configure the serialization and deserialization options.

Let us do go through the default configuration. So by default, the Spring Boot configuration will be as follows:

  • Disable MapperFeature.DEFAULT_VIEW_INCLUSION
  • Disable DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES
  • Disable SerializationFeature. WRITE_DATES_AS_TIMESTAMPS

Let's start with a quicker example by implementing the same

Implementation: 

  • The client sends a GET request to our/coffee?name=Lavazza
  • The controller will return a new Coffee object
  • Spring will use customization options by using String and LocalDateTime objects

It is as follows, so primarily we need to create a class named Coffee which is as follows:

// Class  public class Coffee {      // Getters and setters    private String name;    private String brand;    private LocalDateTime date;  }
  • Now we will also be defining a simple REST controller to demonstrate the serialization:
@GetMapping ("/coffee")    public Coffee getCoffee(    @RequestParam(required =  false) String brand,    @RequiredParam(required = false) String name) {      return new Coffee()           .setBrand(brand)           .setDate(FIXED_DATE)           .setName(name);  }
  • By default, the response when calling GET http://localhost:8080/coffee?brand=lavazza will be as follows:
{    "name": null,    "brand": Lavazza",    "date": "2020 - 11 - 16T10: 21: 35.974"  }
  • Now We would like to exclude null values and to have a custom date format (dd-MM-yyy HH:mm). The final response will be as follows:
{    "brand:" "Lavazza",    "date": "04-11-20202 10:34"  }
  • When using Spring Boot, we have the option to customize the default ObjectMapper or to override it. We'll cover both of these options in the next sections.

Now let us roll to eccentric point in article by customizing the Default Object Mapper. Here. we will be discussing how to customize the default ObjectMapper that Spring Boot uses.

Application Properties and Custom Jackson Module

The simplest way to configure the mapper is via application properties.  The general structure of the configuration is as follows:

  spring.jackson.<category_name>.<feature_name>=true, false

As an example, if we want to disable SerializationFeature. WRITE_DATES_AS_TIMESTAMPS, we'll add:

spring.jackson.serialization.write-dates-as-timestamps=false

Besides the mentioned feature categories, we can also configure property inclusion:

spring.jackson.default-property-inclusion=always, non_null, non_absent, non_default, non_empty

Configuring the environment variables in the simplest approach. The downside of this approach is that we can't customize advanced options like having a custom date format for LocalDateTime. At this point, we'll obtain the result which is shown below:

{    "brand": "Lavazza",    "date": "2020-11-16T10:35:34.593"  }

Now in order to achieve our goal, we'll register a new JavaTimeModule with our custom date format:

@Configuration  @PropertySource("classpath:coffee.properties")    // Class  public class CoffeeRegisterModuleConfig {      @Bean      public Module javaTimeModule() {        JavaTimeModule module = new JavaTimeModule();      module.addSerializer(LOCAL_DATETIME_SERIALIZER);        return module;    }  }

Jackson2ObjectMapperBuilderCustomizer

The purpose of this functional interface is to allow us to create configuration beans. They will be applied to the default ObjectMapper created via Jackson2ObjectMapperBuilder.

@Bean  public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {    return builder ->           builder.serializationInclusion(JsonInclude.Include.NON_NULL)           .serializers(LOCAL_DATETIME_SERIALIZER);  }

The configuration beans are applied in a specific order, which we can control using the @Order annotations. This elegant approach is suitable if we want to configure the ObjectMapper from different configurations or modules.

Jackson2ObjectMapperBuilder

Another clean approach is to define a Jackson2ObjectMapperBuilder bean. Actually, Spring Boot is using this builder by default when building the ObjectMapper and will automatically pick up the defined one:

@Bean  public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {    return new           Jackson2ObjectMapperBuilder().serializers(LOCAL_DATETIME_SERIALIZER)           .serializationInclusion(JsonInclude.Include.NON_NULL);  }

It will configure two options by default:

  • Disable MapperFeature.DEFAULT_VIEW_INCLUSION
  • Disable DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES

According to the Jackson2ObjectMapperBuilder documentation, it will also register some modules if they're present on the classpath:

  • jackson-datatype-jdk8:support for other Java 8 types like Optional
  • jackson-datatype-jsr310:support for Java 8 Date and Time API types
  • jackson-datatype-joda:support for Joda-Time types
  • jackson-module-kotlin:support for Kotlin classes and data classes

Note: The advantage of this approach is that the Jackson2ObjectMapperBuilder offers a simple and intuitive way to build an ObjectMapper.

We can just define a bean with the type MappingJackson2HttpMessageConverter, and Spring Boot will automatically use it:

@Bean    // Convertor method  public MappingJackson2HttpMessageConverter() {      Jackson2ObjectMapperBuilder builder = new    Jackson2ObjectMapperBuilder().serializers(LOCAL_DATE_SERIALIZER)    .serializationInclusion(JsonInclude.Include.NON_NULL);      return new MappingJackson2HttpMessageConverter(builder.build());  }

Note: Make sure to check out our Spring Http Message Converters article to learn more.

Testing the Configuration

Lastly, in order to test our configuration, we'll use TestRestTemplate and serialize the objects as String. In this way, we can validate that our Coffee object is serialized without null values and with the custom date format:

@Test    public void whenGetCoffee_thenSerializedWithDateAndNonNull() {      String formattedDate =      DateTimeFormatter.ofPattern(CoffeeConstants.dateTimeFormat).format(FIXED_DATE);    // Our strings    String brand = "Lavazza";    String url = "/coffee?branf=" + brand;    String response = restTemplate.getForObject(url, String.class);      assertThat(response).isEqualTo("{"brand\":\"" + brand +                                  "\",\"date\":\"" + formatedDate + "\"}");  }

Conclusion: We took a look at several methods to configure the JSON serialization options when using Spring Boot. Here we saw two different approaches:configuring the default options or overriding the default configuration.


Next Article
Spring Boot - Customize the Jackson ObjectMapper

A

akashpandit1103
Improve
Article Tags :
  • Misc
  • Java
  • Java-Spring-Boot
Practice Tags :
  • Java
  • Misc

Similar Reads

    Spring Boot - REST Example
    In modern web development, most applications follow the Client-Server Architecture. The Client (frontend) interacts with the server (backend) to fetch or save data. This communication happens using the HTTP protocol. On the server, we expose a bunch of services that are accessible via the HTTP proto
    4 min read
    How to Change the Default Port in Spring Boot?
    Spring Boot framework provides a default embedded server i.e. the Tomcat server for many configuration properties to run the Spring Boot application. The application runs on the default port which is 8080. As per the application need, we can also change this default port for the embedded server. In
    4 min read
    Spring Boot - Hello World
    Spring Boot is built on top of the Spring Framework and contains all the features of Spring. It has become a favorite of developers these days because of its rapid production-ready environment, which enables the developers to directly focus on the logic instead of struggling with the configuration a
    4 min read
    What is Command Line Runner Interface in Spring Boot?
    Spring Boot CLI (Command Line Interface) is a command line software or tool. This tool is provided by the Spring framework for quickly developing and testing Spring Boot applications from the command prompt. In this article, we will discuss the command line runner interface in the spring boot. Sprin
    3 min read
    How to Make a Simple RestController in Spring Boot?
    A RestController in Spring Boot is a specialized controller that is used to develop RESTful web services. It is marked with the @RestController annotation, which combines @Controller and @ResponseBody. This ensures that the response is automatically converted into JSON or XML, eliminating the need f
    2 min read
    How to Implement Simple Authentication in Spring Boot?
    In this article, we will learn how to set up and configure Basic Authentication with Spring. Authentication is one of the major steps in any kind of security. Spring provides dependencies i.e. Spring Security that helps to establish the Authentication on the API. There are so many ways to add Authen
    4 min read
    What is PathVariable in the Spring Boot?
    Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
    3 min read
    How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA?
    Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using Java is that it tries to connect every concep
    3 min read
    How to Get the Body of Request in Spring Boot?
    Java language is one of the most popular languages among all programming languages. There are several advantages of using the Java programming language, whether for security purposes or building large distribution projects. One of the advantages of using Java is that Java tries to connect every conc
    4 min read
    How to Make Put Request in Spring Boot?
    Java language is one of the most popular languages among all programming languages. There are several advantages of using the Java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences