How can we map multiple date formats using Jackson in Java?


A Jackson is a Java-based library and it can be useful to convert Java objects to JSON and JSON to Java Object. We can map the multiple date formats in the Jackson library using @JsonFormat annotation, it is a general-purpose annotation used for configuring details of how values of properties are to be serialized. The @JsonFormat has three important fields: shape, pattern, and timezone. The shape field can define structure to use for serialization (JsonFormat.Shape.NUMBER and JsonFormat.Shape.STRING), the pattern field can be used in serialization and deserialization. For date, the pattern contains SimpleDateFormat compatible definition and finally, the timezone field can be used in serialization, default is system default timezone.

Syntax

@Target(value={ANNOTATION_TYPE,FIELD,METHOD,PARAMETER,TYPE})
@Retention(value=RUNTIME)
public @interface JsonFormat

Example

import java.io.*;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDateformatTest {
   final static ObjectMapper mapper = new ObjectMapper();
   public static void main(String[] args) throws Exception {
      JacksonDateformatTest jacksonDateformat = new JacksonDateformatTest();
      jacksonDateformat.dateformat();
   }
   public void dateformat() throws Exception {
      String json = "{\"createDate\":\"1980-12-08\"," + "\"createDateGmt\":\"1980-12-08 3:00 PM GMT+1:00\"}";
      Reader reader = new StringReader(json);
      Employee employee = mapper.readValue(reader, Employee.class);
      System.out.println(employee);
   }
}
// Employee class
class Employee implements Serializable {
   @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "IST")
   private Date createDate;
   @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z", timezone = "IST")
   private Date createDateGmt;
   public Date getCreateDate() {
      return createDate;
   }
   public void setCreateDate(Date createDate) {
      this.createDate = createDate;
   }
   public Date getCreateDateGmt() {
      return createDateGmt;
   }
   public void setCreateDateGmt(Date createDateGmt) {
      this.createDateGmt = createDateGmt;
   }
   @Override
   public String toString() {
      return "Employee [\ncreateDate=" + createDate + ", \ncreateDateGmt=" + createDateGmt + "\n]";
   }
}

Output

Employee [
 createDate=Mon Dec 08 00:00:00 IST 1980,
 createDateGmt=Mon Dec 08 07:30:00 IST 1980
]

Updated on: 06-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements