杰克逊 - 序列化日期对象

3

我正在使用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中是否有一种禁用时间偏移的方法?还是我只需要指定自定义日期格式?


另请参见:https://dev59.com/t6Pia4cB1Zd3GeqP2rIN - Christophe Roussy
1个回答

4

我认为你最好在序列化时传入一个新的日期格式。例如:

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

根据GitHub上的JavaDocs,可以了解到日期格式是如何确定的。如果没有指定自己的格式,我认为您只能使用数字时间戳或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),

我很担心这将是我的唯一选择,但我只是想确认一下,因为我对Jackson不是很熟悉。 - user972276

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接