gpt4 book ai didi

date - Jackson - 序列化日期对象

转载 作者:行者123 更新时间:2023-12-02 12:57:17 33 4
gpt4 key购买 nike

我正在使用 Jackson 将 POJO 序列化为 JSON,但在格式化日期时遇到困难。我在 jackson 的网站上发现了这个维基:http://wiki.fasterxml.com/JacksonFAQDateHandling

通过这篇文章,我做了以下事情:

objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);

这会以 ISO-8601 格式打印日期对象,这正是我想要的。 “+0000”除外。根据 ISO-8601 格式,+hhmm 是相对于 UTC 的时间偏移。 jackson 有没有办法禁用时间偏移?或者我只需要指定自定义日期格式?

最佳答案

我认为最好的选择是在序列化时传递新的日期格式。例如:

final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm"));

基于JavaDocs on github这让我们深入了解如何确定日期格式,如果不指定您自己的格式,我认为您只能使用数字时间戳或 Jackson 定义的内置 ISO 格式。引用文档:

/**
* Feature that determines whether Date (and date/time) values
* (and Date-based things like {@link java.util.Calendar}s) are to be
* serialized as numeric timestamps (true; the default),
* or as something else (usually textual representation).
* If textual representation is used, the actual format is
* one returned by a call to
* {@link com.fasterxml.jackson.databind.SerializationConfig#getDateFormat}:
* the default setting being {@link com.fasterxml.jackson.databind.util.StdDateFormat},
* which corresponds to format String of "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
* (see {@link java.text.DateFormat} for details of format Strings).
*<p>
* Note: whether this feature affects handling of other date-related
* types depend on handlers of those types, although ideally they
* should use this feature
*<p>
* Note: whether {@link java.util.Map} keys are serialized as Strings
* or not is controlled using {@link #WRITE_DATE_KEYS_AS_TIMESTAMPS}.
*<p>
* Feature is enabled by default, so that date/time are by default
* serialized as timestamps.
*/
WRITE_DATES_AS_TIMESTAMPS(true),

关于date - Jackson - 序列化日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33652414/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com