【问题标题】:Jackson - serializing date objects杰克逊 - 序列化日期对象
【发布时间】:2015-11-11 14:14:53
【问题描述】:

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

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

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

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

【问题讨论】:

标签: date serialization formatting jackson date-formatting


【解决方案1】:

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

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

基于JavaDocs on github,它提供了一些关于如何确定日期格式的见解,无需指定您自己的,我认为您只能使用数字时间戳或杰克逊定义的内置 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),

【讨论】:

  • 我担心这是我唯一的选择,但我只是想确定一下,因为我对杰克逊不是很熟悉。
猜你喜欢
  • 1970-01-01
  • 2017-04-25
  • 2019-08-04
  • 2012-03-14
  • 2018-04-19
  • 1970-01-01
  • 2016-01-14
  • 2014-10-10
  • 2016-12-07
相关资源
最近更新 更多