If you're using Spring Boot and Jackson to develop an API that returns objects with date properties, you probably want to format the date before sending back the response.

That's especially the case if you store the date as a Java Date object.

Otherwise, Jackson will send back the Date object as a number representing the number of milliseconds since 1970 began.

But many clients calling your API don't want to see a number. They want to see a date in mm/dd/yyyy or some other readable format.

Fortunately, Jackson makes it easy for you to accommodate them.

An Example

Let's say you're developing an HR app and you've got this simple Employee class:

public class Employee {

    private String id;    
    private String lastName;
    private String firstName;
    private Date dateStarted;

...

}

As you can see, it's got relevant info about the employee, including the start date.

Now serialize an instance of that object like this:

ObjectMapper mapper = new ObjectMapper();            

Employee employee = new Employee();
employee.setId("A17");
employee.setFirstName("Frank");
employee.setLastName("Smith");
employee.setDateStarted(new Date());

System.err.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee));

And you'll get this output:

{
  "id" : "A17",
  "lastName" : "Smith",
  "firstName" : "Frank",
  "dateStarted" : 1622403999467
}

Well, that sucks.

You're getting the number of milliseconds since the current epoch began.

Some client applications might find that useful, but many won't.

So let's look at a fix.

With @JsonFormat

Apply an annotation called @JsonFormat to tell Jackson how to handle that Date object.

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MM/dd/yyyy")
    private Date dateStarted;

Pay attention to the stuff that's in parentheses.

First, you need to tell Jackson the "shape" of the output.

With the Date object, you have two "shape" options: STRING and NUMBER. In this case you want to output the date as a String so you'd go with JsonFormat.Shape.STRING.

But you also need to give Jackson a pattern. After all, there are countless ways to output a date in String format.

That's what the pattern property is for.

Here, the pattern is MM/dd/yyyy and yes the case is important.  You can learn more about the SimpleDateFormat pattern by checking the JavaDocs.

Once you've added that annotation and rerun the code, you'll see this output:

{
  "id" : "A17",
  "lastName" : "Smith",
  "firstName" : "Frank",
  "dateStarted" : "05/30/2021"
}

And that's what you're looking for. It's the formatted date.

By the way: the JsonFormat.Shape.NUMBER format is the default option. So you don't even need to specify it if you're going that route.

Wrapping It Up

And there you have it. An easy way to present Date objects with Jackson in your JSON responses.

Now it's up to you to take what you've learned here and apply it to your own development efforts.

Have fun!

Photo by Khoa Võ from Pexels