杰克逊序列化配置

编程入门 行业动态 更新时间:2024-10-28 14:22:45
本文介绍了杰克逊序列化配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在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.

更多推荐

杰克逊序列化配置

本文发布于:2023-08-01 12:22:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1268278.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:杰克逊   序列化

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!