Spring Boot Change Date format in JSON Response object


By default, Spring Boot uses the ISO-8601 format for serializing java.time objects, including LocalDate. This format is a standard way of representing date and time information in JSON, and looks like this: "2023-05-01".

If you want to customize the date format used for JSON serialization of LocalDate objects in Spring Boot, you can do so by configuring a Jackson2ObjectMapperBuilder bean in your application configuration.

Here’s an example of how to customize the date format in Spring Boot using a Jackson2ObjectMapperBuilder:

import org.springframework.context.annotation.*;
import org.springframework.http.converter.*;
import org.springframework.http.converter.json.*;
import org.springframework.web.servlet.config.annotation.*;
import java.time.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.std.*;
import com.fasterxml.jackson.datatype.jsr310.*;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    }
}

In this example, we are configuring a custom Jackson2ObjectMapperBuilder bean that serializes LocalDate objects using a custom LocalDateSerializer that formats dates using the pattern “dd/MM/yyyy”. We then add this MappingJackson2HttpMessageConverter to the list of HTTP message converters used by Spring MVC.

Now, when Spring Boot serializes LocalDate objects to JSON, it will use the custom date format specified in the LocalDateSerializer.