Jackson - Date Handling

Handling dates on Java platform is complex business. Jackson tries not to make it any harder than it has to be. Here‘s how.

All time objects that have associated TimeZone (java.util.Calendar etc) that Jackson constructs use the standard timezone (GMT), not the local time zone (whatever that might be). That is: Jackson defaults to using GMT for all processing unless specifically told otherwise.

Date Serialization

Why do Dates get written as numbers?

Default serializer for java.util.Date (and related, such as java.util.Calendar) serialize them using the most efficient accurate representation, so-called epoch timestamp (number of milliseconds since January 1st, 1970, UTC). Assumption is that if user does not care, we should use efficient and accurate representation to get job bdone.

One exception is java.sql.Date, which will always be represent in textual form (but note: use of java.sql.Date is strongly discouraged due to multiple issues, see below for more details)

But I don‘t like that, I prefer more readable notation

No problem. The simplest way to produce textual serialization is to use:

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

which disable use of timestamps (numbers), and instead use a [ISO-8601 ]-compliant notation, which gets output as something like: "1970-01-01T00:00:00.000+0000".

That format sucks, can I use my own?

If you must. You can configure formatting by passing a java.text.DateFormat instance like so:

objectMapper.setDateFormat(myDateFormat); // 1.8 and above
  objectMapper.getSerializationConfig().setDateFormat(myDateFormat); // for earlier versions (deprecated for 1.8+)

How come this time is off by 9 hours? (5 hours, 3 hours etc)

You may be thinking in terms of your local time zone. Remember that Jackson defaults to using GMT (Greenwich time, one hour behind central European timezone; multiple hours ahead of US time zones).

Can I configure it on per-property basis?

Yes, with Jackson 2.0 you can use the new @JsonFormat annotation:

public class DateStuff {
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH:00", timezone="CET")
    public Date creationTime;
}

Notes on java.sql.Date

(aka "Please do NOT use java.sql.Date, ever!")

Although Jackson supports java.sql.Date, there are known issues with respect to timezone handling, partly due to design of this class. It is recommended that this type is avoided, if possible, and regular java.util.Date (or java.util.Calendar) used instead. If this is not possible, it may be necessary for applications to convert these dates using java.util.Calendar and explicit timezone definition.

Date Deserialization

Which date formats are supported by default?

RFC-1123, ISO-8601 (or rather, commonly used subset). Also, numeric (integer) serializations are recognized, assumed to be in Unix timestamp notation (milliseconds since epoch, Jan 1st 1970 GMT)

Can this be configured?

Yes: similar to serialization configuration, you can call:

objectMapper.getDeserializationConfig().setDateFormat(myDateFormat);

Interoperability

Joda Time

Starting with version 1.4, Jackson offers some support for Joda Time data types: basically, its DateTime can be automatically serialized/deserialized similar to how java.util.Date is handled. More support can be added based on user requests.

With version 2.0, support for Joda date/time types was moved to a new module, Jackson-datatype-Joda, to reduce dependencies core databind has, as well as to make it easier to update Joda-specific functionality. To use the module, you will need to add the dependency (via Maven, or by including module jar), and register module; this will add full support similar to how Jackson 1.x works.

时间: 2024-10-07 07:42:25

Jackson - Date Handling的相关文章

在SpringMVC中使用Jackson并格式化时间

在spring MVC 3中,要实现REST风格的JSON服务,最简单的方式是使用 @ResponseBody 注解.该注解会自动把返回的对象,序列化为JSON. 来看一个最简单的例子.这个例子先使用Spring 3.0.5 + Jackson1.7.1.Jackson是Spring使用的JSON序列化/反序列化第三方库. pom.xml 的主要内容如下 <!-- Spring Framework Dependencies --> <dependency> <groupId&

CI基本配置

<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Base Site URL |-------------------------------------------------------------------------- */ $confi

[转]js add month 加n月

本文转自:http://stackoverflow.com/questions/5645058/how-to-add-months-to-a-date-in-javascript/5645126 I took a look at the datejs and stripped out the code necessary to add months to a date handling edge cases (leap year, shorter months, etc): Date.isLea

jackson/fastjson、mybatis、mysql date/datatime/timestamp、java Date/Timestamp关系详解

jackson/fastjson序列化/反序列化: 默认情况下,jackson/fastjson将java Date/Timestamp类型序列化为时间戳,也就是1970年1月1日0点以来的毫秒数.如果要显示为用户友好表示: Jackson 可以: SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); objectMapper.setDateFormat(sdf)或者:@JsonFormat(locale

Spring Mvc使用Jackson进行json转对象时,遇到的字符串转日期的异常处理(JSON parse error: Can not deserialize value of type java.util.Date from String)

1.问题排查 - 项目配置 springboot 2.1 maven配置jackson - 出现的场景: 服务端通过springmvc写了一个对外的接口,查询数据中的表,表中有一个字段属性是时间戳,返回一个json字符串,其中该json带有日期,格式为yyyy-MM-dd HH:mm:ss 客户端调用该http接口,指定返回值为一个Vo,Vo中日期的字段为Date类型 客户端调用该接口后抛异常了.报错信息如下: feign.codec.DecodeException: JSON parse er

jackson 中JsonFormat date类型字段的使用

为了便于date类型字段的序列化和反序列化,需要在数据结构的date类型的字段上用JsonFormat注解进行注解具体格式如下 @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", locale = "zh", timezone = "GMT+8") pattern 指定转化的格式,SSSZ(S指的是微秒,Z指时区)此处的pattern和java.text.SimpleDateFormat中的Ti

Jackson 概述

原文地址 本文内容 JSON 的三种方式 示例 Full Data Binding (POJO) 示例 "Raw" Data Binding 示例 用泛型数据绑定 Tree Model 示例 Streaming API 示例 Streaming API 示例 2: 数组 Next Steps Inspired by the quality and variety of XML tooling available for the Java platform (StAX, JAXB, et

Jackson - Quickstart

JSON Three Ways Jackson offers three alternative methods (one with two variants) for processing JSON: Streaming API (aka "Incremental parsing/generation") reads and writes JSON content as discrete events. org.codehaus.jackson.JsonParser reads, o

Jackson工具类使用及配置指南、高性能配置(转)

Jackson使用工具类 通常,我们对JSON格式的数据,只会进行解析和封装两种,也就是JSON字符串--->Java对象以及Java对象--->JSON字符串. public class JsonUtils { /** * Logger for this class */ private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class); private final static ObjectMappe