Guide to @JsonFormat in Jackson

1. Overview

In this article, we try to understand how to use @JsonFormat in Jackson. It is a Jackson annotation that is used to specify how to format fields and/or properties for JSON output.

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

2. Maven Dependency

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

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

3. Getting Started

3.1. Using the Default Format

To get started, we will demonstrate the concepts of using the @JsonFormat annotation with a class representing a user.

Since we are trying 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:

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 you can see, the createdDate field is shown as the number of seconds since epoch which is the default format used for Date fields.

3.2. Using the Annotation on a Getter

Let us now use @JsonFormat to specify the format that the createdDate field should be serialized. Here is the User class updated for this change. The createdDate field has been annotated as shown to specify the date format.

The data format used for the pattern argument is specified by 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. The output is shown below:

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

As you can see, the createdDate field has been formatted using the specified SimpleDateFormat format using the @JsonFormat annotation.

The above example demonstrates using the annotation on a field. It can also be used in a getter method (a property) as follows.

For instance, you may have a property which is being computed on invocation. You can use the annotation on the getter method in such a case. Note that the pattern has also been changed to return just the date part of the instant:

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

The resultant output is as follows:

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

3.3. Specifying the Locale

In addition to specifying the date format, you can also specify the locale to be used for serialization. Not specifying this parameter results in serialization being performed with the default 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

Using @JsonFormat with shape set to JsonFormat.Shape.NUMBER results in the default output for Date types — as the number of seconds since the epoch. The parameter pattern is not applicable to this case and is ignored:

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

The output is as shown below:

{ ..., "dateNum":1482054723876 }

4. Conclusion

In conclusion, @JsonFormat is used to control the output format of Date and Calendar types as demonstrated above.

The sample code shown above is available over on GitHub.

Related posts:

Java Program to Describe the Representation of Graph using Incidence Matrix
Custom Cascading in Spring Data MongoDB
Java – Byte Array to Reader
Using Java Assertions
Guide to WeakHashMap in Java
Giới thiệu Json Web Token (JWT)
Phương thức tham chiếu trong Java 8 – Method References
Hướng dẫn Java Design Pattern – MVC
Chuyển đổi giữa các kiểu dữ liệu trong Java
Java Program to Implement Dijkstra’s Algorithm using Set
Java Program to Implement Hash Tables Chaining with List Heads
Annotation trong Java 8
Giới thiệu luồng vào ra (I/O) trong Java
Map Serialization and Deserialization with Jackson
Các kiểu dữ liệu trong java
Java Program to Create a Minimal Set of All Edges Whose Addition will Convert it to a Strongly Conne...
Sử dụng JDBC API thực thi câu lệnh truy vấn dữ liệu
HashSet trong Java hoạt động như thế nào?
The Difference Between map() and flatMap()
Java Program to Check for balanced parenthesis by using Stacks
How to Delay Code Execution in Java
Guide to java.util.Formatter
Java Program to Repeatedly Search the Same Text (such as Bible by building a Data Structure)
Java Program to Perform Polygon Containment Test
Java Program to Implement Binomial Tree
Java Program to Implement Randomized Binary Search Tree
Java String to InputStream
OAuth2 for a Spring REST API – Handle the Refresh Token in AngularJS
Spring @RequestParam Annotation
Logging in Spring Boot
New Features in Java 15
Tiêu chuẩn coding trong Java (Coding Standards)