Posted In: Jackson 2X, JSON

How to map multiple date formats using Jackson Mapper?

Use Case – I want to map multiple date formats to ObjectMapper while converting date string to POJO

Maven – Jackson 2X

<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-core</artifactId>
	<version>2.9.7</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.9.7</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-annotations</artifactId>
	<version>2.9.7</version>
</dependency>

Solution – Use @JsonFormat

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = “yyyy-MM-dd”, timezone = “IST”)

package com.example.json;

import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonDateformat2 {
	final static ObjectMapper mapper = new ObjectMapper();

	public static void main(String[] args) throws Exception {
		JacksonDateformat2 jacksonDateformat = new JacksonDateformat2();
		jacksonDateformat.dateformat();
	}

	public void dateformat() throws Exception {
		String json = "{\"createDate\":\"1976-09-08\"," 
				+ "\"createDateGmt\":\"2015-10-1 3:00 PM GMT+1:00\"}";
		Reader reader = new StringReader(json);
		Employee3 employee = mapper.readValue(reader, Employee3.class);
		System.out.println(employee);
	}
}

class Employee3 implements Serializable {
	private static final long serialVersionUID = 5590115870809984678L;
	@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 "Employee3 [createDate=" + createDate + ", createDateGmt=" + createDateGmt + "]";
	}
}

Tags:

by , on November 27th, 2018