Jackson Annotations - @JsonFormat



Overview

@JsonFormat annotation is used to specify format while serialization or de-serialization. It is mostly used with Date fields.

Example - Serialization without using @JsonFormat

JacksonTester.java

package com.tutorialspoint;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]) throws IOException, ParseException {
      ObjectMapper mapper = new ObjectMapper();
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
      Date date = simpleDateFormat.parse("20-12-1984");

      Student student = new Student(1, date);
      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(student);
      System.out.println(jsonString);
   }
}
class Student { 
   public int id;
   public Date birthDate;
   Student(int id, Date birthDate){
      this.id = id;
      this.birthDate = birthDate;
   } 
}

Output

Run the JacksonTester and verify the output −

{
  "id" : 1,
  "birthDate" : 472329000000
}

Example - Serialization with @JsonFormat

JacksonTester.java

package com.tutorialspoint;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]) throws IOException, ParseException {
      ObjectMapper mapper = new ObjectMapper();
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
      Date date = simpleDateFormat.parse("20-12-1984");

      Student student = new Student(1, date);
      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(student);
      System.out.println(jsonString);
   }
}
class Student { 
   public int id;
   @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
   public Date birthDate;
   Student(int id, Date birthDate){
      this.id = id;
      this.birthDate = birthDate;
   } 
}

Output

Run the JacksonTester and verify the output −

{
  "id" : 1,
  "birthDate" : "19-12-1984"
}

Here we can see, without using @JsonFormat, Jackson is serializing the date to timestamp whereas using @JsonFormat annotation, we're specifying the format in which date is to be serialized.

Advertisements