本文介绍了Jackson SerializationFeature.WRITE_DATES_AS_TIMESTAMPS 在春季不关闭时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过大量搜索,我找到了在@RestController 中转换为 JSON 响应时如何阻止 java.util.Date 字段被序列化为时间戳的方法.

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.

但是我无法让它工作.我发现的所有帖子都说禁用了 Jackson 对象映射器的 SerializationFeature.WRITE_DATES_AS_TIMESTAMPS 功能.于是我写了下面的代码:

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);
    }
}

据我所知,配置也是一个 bean,因此对象映射器中的自动连接以设置其他属性应该可以工作.我使用了断点,这个设置看起来一切都很好.

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.

然而,当我使用 java.util.Date 属性序列化一个 bean 以响应 http 查询时,我仍然得到一个时间戳.

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 !

推荐答案

经过一番折腾,我发现下面的代码解决了这个问题:

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;
            }
        }
    }
}

我不确定是否有更简单的方法来访问 Jackson MVC 消息转换器并对其进行配置.但这对我有用.

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.

这篇关于Jackson SerializationFeature.WRITE_DATES_AS_TIMESTAMPS 在春季不关闭时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 03:54