![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ]
Advertisements