我正在使用Jackson将POJO序列化为JSON,但是日期格式化有困难。我在杰克逊的网站上遇到过这个维基:http://wiki.fasterxml.com/JacksonFAQDateHandling
通过这篇文章,我做了以下事情:
objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
以ISO-8601格式打印Date对象,这就是我想要的。除了" + 0000"。根据ISO-8601格式,+ hhmm是与UTC的时间偏移。杰克逊有没有办法禁用时间偏移?或者我只需要指定自定义日期格式吗?
答案 0 :(得分:4)
我认为最好的办法是在序列化时传递新的日期格式。例如:
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),