Java JSON时间处理 Jackson 的时间操作 时间序列化 Jackson Date

原文链接: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
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Jackson 是一个流行的 Java 序列/反序列库,它可以轻松地将 Java 对象转换成 JSON 或 XML 格式,同时也支持将 JSON 或 XML 格式的数据反序列Java 对象。如果你想使用 Jackson 反序列一个包含日期时间JSON 字符串,可以按照以下步骤进行: 1. 在 Java 类中定义一个包含日期时间字段的 POJO(Plain Old Java Object)。例如: ```java public class MyObject { private String name; private Date createTime; // 省略 getter 和 setter 方法 } ``` 2. 在 JSON 字符串中,将日期时间字段的值以字符串形式表示,并使用指定的日期时间格式。例如: ```json { "name": "my object", "createTime": "2022-09-01 11:22:33" } ``` 3. 使用 Jackson 的 ObjectMapper 对象进行反序列。例如: ```java ObjectMapper mapper = new ObjectMapper(); MyObject obj = mapper.readValue(jsonString, MyObject.class); ``` 在这个例子中,jsonString 是包含日期时间字段的 JSON 字符串,MyObject.class 是要转换成的目标 Java 类型。在反序列过程中,Jackson 会自动将字符串形式的日期时间值转换成 Date 对象,并赋值给 Java 对象的对应字段。 如果 JSON 字符串中的日期时间格式不是标准格式,你可以使用 Jackson 提供的 @JsonFormat 注解来指定日期时间格式。例如: ```java public class MyObject { private String name; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; // 省略 getter 和 setter 方法 } ``` 在这个例子中,@JsonFormat 注解指定了 createTime 字段的日期时间格式。这样,在反序列过程中,Jackson 就会根据指定的日期时间格式来解析字符串值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值