Jackson SerializationFeature.WRITE_DATES_AS_TIMESTAMPS在春天没有关闭时间戳 [英] Jackson SerializationFeature.WRITE_DATES_AS_TIMESTAMPS not turning off timestamps in spring

查看:2804
本文介绍了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 objet映射器的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.

但是当我在对http查询的响应中使用java.util.Date属性序列化bean时,我还有时间戳。

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

I我不确定是否有更简单的方法来访问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在春天没有关闭时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆