Posted In: Jackson 2X, JSON

How to map date format using Jackson Mapper

Use Case – I want to map particular date format 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

ObjectMapper .. mapper.setDateFormat(SimpleDateFormat);

package com.example.json;

import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.databind.ObjectMapper;

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

	public static void main(String[] args) throws Exception {
		JacksonDateformat jacksonDateformat = new JacksonDateformat();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		mapper.setDateFormat(df);
		jacksonDateformat.dateformat();
	}

	public void dateformat() throws Exception {
		String json = "{\"birthDate\":\"1976-09-08\"}";
		Reader reader = new StringReader(json);
		Employee2 employee = mapper.readValue(reader, Employee2.class);
		System.out.println(employee);
	}
}

class Employee2 implements Serializable {
	private Date birthDate;

	public Date getBirthDate() {
		return birthDate;
	}

	public void setBirthDate(Date birthDate) {
		this.birthDate = birthDate;
	}

	@Override
	public String toString() {
		return "Employee2 [birthDate=" + birthDate + "]";
	}
}

Tags:

by , on November 26th, 2018