杰克逊序列化配置 [英] Jackson serializationConfig

查看:258
本文介绍了杰克逊序列化配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Spring 3 MVC应用程序中使用Jackson JSON。为了不序列化每个单独的Date字段,我创建了一个使用特定DateFormat的自定义objectmapper:

I am using Jackson JSON in a Spring 3 MVC app. To not serialize each and every single Date field, I created a custom objectmapper that uses a specific DateFormat:

@Component("jacksonObjectMapper")
public class CustomObjectMapper extends ObjectMapper
{
    Logger log = Logger.getLogger(CustomObjectMapper.class);

    @PostConstruct
    public void afterProps()
    {
        log.info("PostConstruct... RUNNING");
        //ISO 8601
        getSerializationConfig().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SZ"));


    }

    //constructors...

}

此自定义ObjectMapper被注入JsonConverter:

This custom ObjectMapper is injected into the JsonConverter:

<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json" />
    <property name="objectMapper" ref="jacksonObjectMapper" /> <!-- defined in CustomObjectMapper -->
</bean>

日志和序列化工作中没有例外,但它没有提取日期格式,它简单序列化为时间戳。 @PostConstruct注释有效,方法中的日志语句在日志中。

There is no exception in the logs and serialization works, but it is not picking up the dateformat, it simple serializes to a timestamp. The @PostConstruct annotation works, the log statement in the method is in the logs.

有谁知道为什么会失败?

Does anyone know why this fails?

推荐答案

你也可以需要通过执行以下操作来指定您想要文本日期序列化:

You may also need to specify that you want textual Date serialization, by doing:

configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);

(虽然我假设设置非空日期格式也可能触发它,但可能不会)

(although I was assuming setting non-null date format might also trigger it, but maybe not)

此外,您可以直接从构造函数(这是安全的)配置mapper。并不是说它应该改变行为,而是需要单独的配置方法。

Also, you can do configuration of mapper directly from constructor (which is safe). Not that it should change behavior, but would remove need for separate configuration method.

这篇关于杰克逊序列化配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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