Guide to @JsonFormat in Jackson – Jackson中的@JsonFormat指南

最后修改: 2016年 12月 28日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we demonstrate how to use @JsonFormat in Jackson.

在本教程中,我们将演示如何在Jackson中使用@JsonFormat

@JsonFormat is a Jackson annotation that we use to specify how to format fields and/or properties for JSON output.

@JsonFormat是一个Jackson注解,我们用它来指定如何为JSON输出格式化字段和/或属性。

Specifically, this annotation allows us to specify how to format Date and Calendar values according to a SimpleDateFormat format.

具体来说,这个注解允许我们指定如何根据SimpleDateFormat格式来格式化DateCalendar值。

2. Maven Dependency

2.Maven的依赖性

@JsonFormat is defined in the jackson-databind package, so we need the following Maven Dependency:

@JsonFormatjackson-databind包中定义,因此我们需要以下Maven依赖。

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.3</version>
</dependency>

3. Getting Started

3.入门

3.1. Using the Default Format

3.1.使用默认格式

We’ll start by demonstrating the concepts of using the @JsonFormat annotation with a class representing a user.

我们将首先演示使用@JsonFormat注解的概念,该注解代表一个用户的类。

Since we want to explain the details of the annotation, the User object will be created on request (and not stored or loaded from a database) and serialized to JSON:

由于我们想解释注释的细节,User对象将在请求时被创建(而不是存储或从数据库加载),并被序列化为JSON。

public class User {
    private String firstName;
    private String lastName;
    private Date createdDate = new Date();

    // standard constructor, setters and getters
}

Building and running this code example returns the following output:

构建并运行该代码示例,返回以下输出。

{"firstName":"John","lastName":"Smith","createdDate":1482047026009}

As we can see, the createdDate field is shown as the number of milliseconds since epoch, which is the default format used for Date fields.

我们可以看到,createdDate字段被显示为自纪元以来的毫秒数,这是为Date字段使用的默认格式。

3.2. Using the Annotation on a Getter

3.2.在获取器上使用注释

We’ll now use @JsonFormat to specify the format to serialize the createdDate field.

我们现在将使用@JsonFormat来指定序列化createdDate字段的格式。

Let’s look at the User class updated for this change. We annotate the createdDate field as shown to specify the date format.

让我们看看为这个变化而更新的用户类。我们对createdDate字段进行注释,如图所示,以指定日期格式。

The data format used for the pattern argument is specified by SimpleDateFormat:

用于pattern参数的数据格式由SimpleDateFormat指定。

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
private Date createdDate;

With this change in place, we build the project again and run it.

有了这个变化,我们再次建立项目并运行它。

And this is the output:

这就是输出。

{"firstName":"John","lastName":"Smith","createdDate":"2016-12-18@07:53:34.740+0000"}

Here we’ve formatted the createdDate field using the specified SimpleDateFormat format using the @JsonFormat annotation.

在这里,我们使用@JsonFormat注解,使用指定的SimpleDateFormat格式来格式化createdDate字段。

The above example demonstrates using the annotation on a field. We can also use it in a getter method (a property).

上面的例子演示了在一个字段上使用注解。我们也可以在一个getter方法(一个属性)中使用它。

For instance, we may have a property that is being computed on invocation. We can use the annotation on the getter method in such a case.

例如,我们可能有一个在调用时被计算的属性。在这种情况下,我们可以在getter方法上使用注解。

Note that we’ve also changed the pattern to return just the date part of the instant:

注意,我们也改变了模式,只返回瞬间的日期部分。

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
public Date getCurrentDate() {
    return new Date();
}

And here’s the output:

下面是输出结果。

{ ... , "currentDate":"2016-12-18", ...}

3.3. Specifying the Locale

3.3.指定地区语言

In addition to specifying the date format, we can also specify the locale for serialization.

除了指定日期格式外,我们还可以指定用于序列化的地方语言。

Not specifying this parameter results in performing serialization with the default locale:

不指定这个参数的结果是用默认的locale执行序列化。

@JsonFormat(
  shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB")
public Date getCurrentDate() {
    return new Date();
}

3.4. Specifying the Shape

3.4.指定形状

Using @JsonFormat with shape set to JsonFormat.Shape.NUMBER results in the default output for Date types — as the number of milliseconds since the epoch.

使用@JsonFormat,并将shape设置为JsonFormat.Shape.NUMBER,会导致Date类型的默认输出 – 作为自纪元以来的毫秒数

The parameter pattern is not applicable to this case and is ignored:

参数pattern不适用于这种情况,被忽略。

@JsonFormat(shape = JsonFormat.Shape.NUMBER)
public Date getDateNum() {
    return new Date();
}

Let’s look at the output:

让我们看一下输出。

{ ..., "dateNum":1482054723876 }

4. Conclusion

4.结论

To sum up, we use @JsonFormat to control the output format of Date and Calendar types.

总而言之,我们使用@JsonFormat来控制DateCalendar类型的输出格式。

The sample code shown above is available over on GitHub.

上图所示的示例代码可在GitHub上获得