原文链接:Jackson Date
1. Overview 概述
In this tutorial, we'll serialize dates with Jackson. We'll start by serializing a simple java.util.Date, then Joda-Time, and finally, the Java 8 DateTime.
在这篇,来看看Jackson库是如何序列化日期的。先来处理 java.util.Date ,接着是 Joda-Time ,最后是 Java8 的日期时间。
2. Serialize Date to Timestamp 默认的把java.util.Date序列化为Timestamp,即从1970年1月1日到现在的毫秒值
First, let's see how to serialize a simple java.util.Date with Jackson.
先来学习下Jackson如何序列化 java.util.Date
In the following example, we'll serialize an instance of “Event,” which has the Date field “eventDate“:
在正面的示例中,把包含有一个Date类型的属性的Event类序列化为JSON数据
@Test
public void whenSerializingDateWithJackson_thenSerializedToTimestamp()
throws JsonProcessingException, ParseException {
// 设置日期时间
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse("01-01-1970 01:00");
// 构造一个Event对象,也是即将要序列化为JSON的元素
Event event = new Event("party", date);
// 序列化Java对象为JSON数据
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(event);
}
It's important to note that Jackson will serialize the Date to a timestamp format by default (number of milliseconds since January 1st, 1970, UTC).
一个很重要的点就是 Jackson 把 Date 序列化为 Timestamp 时间戳格式,就是1970年1月1日到现在的毫秒值
The actual output of the “event” serialization is:
上面的示例会输出如下内容:
{
"name":"party",
"eventDate":3600000
}
3. Serialize Date to ISO-8601 日期显示为ISO-8601格式字符串
Serializing to this terse timestamp format is not optimal. Instead, let's serialize the Date to the ISO-8601 format:
把日期显示为时间戳是不好的,而是应该显示可读性高的模式,例如,序列化显示为ISO-8601格式的字符串,示例如下:
@Test
public void whenSerializingDateToISO8601_thenSerializedToText()
throws JsonProcessingException, ParseException {
// 日期对象
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
String toParse = "01-01-1970 02:30";
Date date = df.parse(toParse);
// 要处理的Java数据对象
Event event = new Event("party", date);
ObjectMapper mapper = new ObjectMapper();
// 禁上把日期显示为时间戳
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// 设置日期格式为 StdDateFormat
// StdDateFormat is ISO8601 since jackson 2.9
mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));
// 获得JSON数据并验证
String result = mapper.writeValueAsString(event);
assertThat(result, containsString("1970-01-01T02:30:00.000+00:00"));
}
We can see that the representation of the date is now much more readable.
显而易见的就能看出,这个格式的日期易读性特别高。
4. Configure ObjectMapper DateFormat 使用DateFormat格式化显示日期
The previous solutions still lack the full flexibility of choosing the exact format to represent the java.util.Date instances.
上面的例子仍然缺少灵活性,没办法自由的选择要输出的日期格式字符串。
Conversely, let's take a look at a configuration that will allow us to set our formats for representing dates:
所以呢,来学习下Jackson的配置,让开发人员可以自由设定显示的日期格式,示例如下:
@Test
public void whenSettingObjectMapperDateFormat_thenCorrect()
throws JsonProcessingException, ParseException {
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");
String toParse = "20-12-2014 02:30";
Date date = df.parse(toParse);
Event event = new Event("party", date);
ObjectMapper mapper = new ObjectMapper();
// 关键代码,设置日期格式为 参数 对就的模式
mapper.setDateFormat(df);
String result = mapper.writeValueAsString(event);
assertThat(result, containsString(toParse));
}
Note that, even though we're now more flexible regarding the date format, we're still using a global configuration at the level of the entire ObjectMapper.
注意,尽管现在的灵活性更高了,但是我们使用的全局的日期格式化显示,作用在整个ObjectMapper对象上的。
5. Use @JsonFormat to Format Date 使用@JsonFormat注解来格式化日期显示字符串
Next let's take a look at the @JsonFormat annotation to control the date format on individual classes, instead of globally, for the entire application:
下面来看看如何使用 @JsonFormat 注解来对某个类的日期属性实现格式化显示的吧,而不是使用全局能用的格式,示例如下:
public class Event {
public String name;
// 使用@JsonFormat注解格式化日期
@JsonFormat
(sha