Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
987 views
in Technique[技术] by (71.8m points)

json - Jackson SerializationFeature.WRITE_DATES_AS_TIMESTAMPS not turning off timestamps in spring

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 !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...