Jackson SerializationFeature.WRITE_DATES_AS_TIMESTAMPS not turning off timestamps in spring

Issue

After a lot of searching I tracked down how to stop java.util.Date fields from being serialised into timestamps when converting to JSON responses in my @RestController.

However I cannot get it to work. All the posts I found said to disable the SerializationFeature.WRITE_DATES_AS_TIMESTAMPS feature of the Jackson objet mapper. So I wrote the following code:

public class MVCConfig {

    @Autowired
    Jackson2ObjectMapperFactoryBean objectMapper;

    @PostConstruct
    public void postConstruct() {
        this.objectMapper.setFeaturesToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    }
}

As I understand it, a config is a bean as well so auto wiring in the object mapper to set additional properties should work. I’ve used break points and everything looks good with this setup.

However when I serialise a bean with a java.util.Date property in a response to a http query, I’m still getting a time stamp.

Does anyone know why this is not working? It’s got me stumped !

Solution

After lots of messing around I found that the following code fixed the problem:

public class MVCConfig extends WebMvcConfigurerAdapter {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { 
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                MappingJackson2HttpMessageConverter jsonMessageConverter = (MappingJackson2HttpMessageConverter) converter;
                ObjectMapper objectMapper = jsonMessageConverter.getObjectMapper();
                objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
                break;
            }
        }
    }
}

I’m not sure if there is an easier way to access the Jackson MVC message converter and configure it. But this is working for me.

Answered By – drekka

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published