2

I am converting my app to get rid of spring-boot, it now uses only Spring (5.3).

I've added the @EnableWebMvc configuration and I have my endpoints working properly for the most part - they return the data I want as JSON.

Previously, I customised the date format with the spring-boot property: spring.jackson.date-format=yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

In the new pure-spring app though, it's regressed back serializing to a long value.

I've tried the following, but it doesn't seem to even use these beans at all:

  @Bean
  public ObjectMapper objectMapper() {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    ObjectMapper dateFormatMapper = new ObjectMapper();
    dateFormatMapper.setDateFormat(dateFormat);
    return dateFormatMapper;
  }

  @Bean 
  public MappingJackson2HttpMessageConverter mappingJackson2JsonView(){
    var converter = new MappingJackson2HttpMessageConverter();
    converter.getObjectMapper().setDateFormat(
      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") );
    return converter;    
  }

I'm looking to customise the format globally, not on a per-field basis.

What would be the equivalent of spring.jackson.date-format for pure Spring @EnableWebMvc setup?

1 Answer 1

2

You can customize MappingJackson2HttpMessageConverter by using WebMvcConfigurer with @EnableWebMvc.

For example:

@Configuration
@EnableWebMvc
public class YourConfiguration implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
                .indentOutput(true)
                .dateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    }
}


For more information, please see 1.11.7. Message Converters - Web on Servlet Stack - docs.spring.io.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.