Spring Boot JSON format date using JsonSerialize and JsonFormat

While providing JSON data through Spring Boot or Spring web services, we might have situation where the JSON data contains Date data. By default, the dates are not formatted in human readable format. However, there are ways to format the dates as we want. Here we will see use of two annotations:

  • JsonSerialize
  • JsonFormat

Let us see the source code how we can use these annotations.

1. build.gradle

The boilerplate build.gradle file to define all the dependencies required to build and run our Spring Boot application.

buildscript {
    ext {
        springBootVersion = '1.5.3.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

group 'com.firstfewlines'
version '1.0.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.springframework.boot:spring-boot-starter-web:$springBootVersion"
    compile "org.springframework.boot:spring-boot-devtools:$springBootVersion"
}


2. CustomerController.java

In this controller class, we are hard-coding the customer data in a List to avoid complexity of our sample. In production application the data typically fetched from database through Service layer or similar.

package com.firstfewlines.controller;

import com.firstfewlines.model.Customer;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

@RestController
@RequestMapping("/api")
class CustomerController {
    final static DateFormat df = new SimpleDateFormat("M-dd-yyyy");
    static {
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
    }

    List<Customer> customers = new ArrayList<>();

    public CustomerController() throws Exception {
        Customer customer1 = new Customer("Lisa Menon", df.parse("02-23-1976"), df.parse("07-16-2006") );
        Customer customer2 = new Customer("Samuel Geek", df.parse("04-04-1983"), df.parse("12-03-2013"));
        Customer customer3 = new Customer("Dipak Kumar", df.parse("08-10-1996"), null );
        customers.add(customer1);
        customers.add(customer2);
        customers.add(customer3);
    }

    @RequestMapping(value = "/customers", method = RequestMethod.GET)
    Iterable<Customer> getCustomers() {
        return customers;
    }
}


3. Customer.java

This is our sample model class: Customer, where we will use the two annotations: JsonSerialize and JsonFormat for formatting two Date fields respectively.

Note that, to use JsonSerialize annotation, we have to create a custom JsonSerializer class where we will do the necessary formatting. We created DateSerializer class for this purpose.

For using JsonFormat, we don’t have to create such extra class. We have to pass the desired format with the annotation.

package com.firstfewlines.model;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.firstfewlines.util.DateSerializer;

import java.util.Date;

public class Customer {
    String name;
    Date dateOfBirth;
    Date marriageAnniversary;

    public Customer(String name, Date dateOfBirth, Date marriageAnniversary) {
        this.name = name;
        this.dateOfBirth = dateOfBirth;
        this.marriageAnniversary = marriageAnniversary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @JsonSerialize(using = DateSerializer.class)
    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MMM", timezone = "UTC")
    public Date getMarriageAnniversary() {
        return marriageAnniversary;
    }

    public void setMarriageAnniversary(Date marriageAnniversary) {
        this.marriageAnniversary = marriageAnniversary;
    }
}


4. SpringBootJsonFormatExample.java
package com.firstfewlines;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootJsonFormatExample {
    public static void main(String [] argv){
        SpringApplication.run(SpringBootJsonFormatExample.class, argv);
    }
}


5. DateSerializer.java
package com.firstfewlines.util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DateSerializer extends JsonSerializer<Date> {

    final static DateFormat df = new SimpleDateFormat("M/dd/yyyy");
    static {
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
    }

    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        gen.writeString(df.format(value));
    }
}


Download complete source code:


How to run the application?

  • Make sure you have latest version of Gradle installed and PATH is configured.
  • Download the attached source code zip file and unzip it to your local folder.
  • Go to the directory where you unzipped the file i.e. where the build.gradle is there
  • Run gradle clean bootRun command
  • The web service should be up at http://localhost:8080/

Alternatively, you can use IntelliJ IDEa or Eclipse to import the Gradle project and run from there.


How to test:

To see the JSON format in action, we can use Postman apps from Google chrome or curl in linux shell.

Using Postman or curl, do a GET to http://localhost:8080/api/customers

This should give you JSON output like:

[
    {
        "name": "Lisa Menon",
        "dateOfBirth": "2/23/1976",
        "marriageAnniversary": "16-Jul"
    },
    {
        "name": "Samuel Geek",
        "dateOfBirth": "4/04/1983",
        "marriageAnniversary": "03-Dec"
    },
    {
        "name": "Dipak Kumar",
        "dateOfBirth": "8/10/1996",
        "marriageAnniversary": null
    }
]


References:


Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus