JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

How to handle date in Json using Jackson api in java?


This page gives an example on how to serialize date object in Jackson json APIs. Lets see how the date object will be displayed in default case.

Note: Refer How to convert Java object to JSON string? page for dependent libraries.

Here is a simple Employee pojo, we will convert this pojo object to json string.

package com.java2novice.json.models;

import java.util.Date;

import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonPropertyOrder({ "emp_id", "emp_name", "emp_designation", "department", "salary" })
public class Employee {

	@JsonProperty("emp_id")
	private int empId;
	
	@JsonProperty("emp_name")
	private String name;
	
	@JsonProperty("emp_designation")
	private String designation;
	
	private String department;
	
	private int salary;
	
	private Date doj;
	
	public String toString(){
		StringBuilder sb = new StringBuilder();
		sb.append("************************************");
		sb.append("\nempId: ").append(empId);
		sb.append("\nname: ").append(name);
		sb.append("\ndesignation: ").append(designation);
		sb.append("\n************************************");
		return sb.toString();
	}
	
	public int getEmpId() {
		return empId;
	}
	public void setEmpId(int empId) {
		this.empId = empId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDesignation() {
		return designation;
	}
	public void setDesignation(String designation) {
		this.designation = designation;
	}
	public String getDepartment() {
		return department;
	}
	public void setDepartment(String department) {
		this.department = department;
	}
	public int getSalary() {
		return salary;
	}
	public void setSalary(int salary) {
		this.salary = salary;
	}

	public Date getDoj() {
		return doj;
	}

	public void setDoj(Date doj) {
		this.doj = doj;
	}
}

A sample code which converts an object to json value:

package com.java2novice.json.examples;

import java.io.IOException;
import java.util.Date;

import org.codehaus.jackson.map.ObjectMapper;

import com.java2novice.json.models.Employee;

public class DateMapperExample {

	public static void main(String[] a){
		
		Employee emp = new Employee();
		emp.setEmpId(1016);
		emp.setName("Nataraj G");
		emp.setDepartment("Accounting");
		emp.setDesignation("Accountant");
		emp.setSalary(40000);
		emp.setDoj(new Date());
		
		ObjectMapper mapperObj = new ObjectMapper();
		
		try {
			// get Employee object as a json string
			String jsonStr = mapperObj.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
			System.out.println(jsonStr);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Output:
{
  "emp_id" : 1016,
  "emp_name" : "Nataraj G",
  "emp_designation" : "Accountant",
  "department" : "Accounting",
  "salary" : 40000,
  "doj" : 1434106944912
}

In the above json string the doj is displayed as number format 1434106944912 not as date format. To serialize date first you need to implement JsonSerializer as shown below:

package com.java2novice.json.util;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

public class DateSerializer extends JsonSerializer<Date>{

	public void serialize(Date dt, JsonGenerator jsonGen, SerializerProvider serProv) 
											throws IOException, JsonProcessingException {
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedDate = sdf.format(dt);
		jsonGen.writeString(formattedDate);
	}
}

Now annotate your doj member in Employee class as shown below: This will solve the problem, you will get the date formate as specified in the above DateSerializer class.

@JsonSerialize(using=DateSerializer.class)
	private Date doj;

Output:
{
  "emp_id" : 1016,
  "emp_name" : "Nataraj G",
  "emp_designation" : "Accountant",
  "department" : "Accounting",
  "salary" : 40000,
  "doj" : "2015-06-12 16:37:27"
}
<< Previous Program | Next Program >>

Jackson JSON examples

  1. How to convert Java object to JSON string?
  2. How to convert JSON string to Java object?
  3. How to convert JSON string to Map using Jackson API?
  4. How to convert Map to JSON string using Jackson API?
  5. Enable JSON pretty print using Jackson API
  6. How to rename JSON properties using Jackson annotations?
  7. How to ignore JSON property using Jackson annotations?
  8. How to order JSON elements using Jackson annotations?
  9. How to ignore json empty or null values using Jackson API in java?
  10. How to handle date in Json using Jackson api in java?
  11. How to read specific json node in Jackson api (tree model)?
  12. Jackson API client - how to read json from URL?
Knowledge Centre
Stream and types of Streams
A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are:

Byte Streams: Provide a convenient means for handling input and output of bytes. Byte Streams classes are defined by using two abstract classes, namely InputStream and OutputStream.

Character Streams: Provide a convenient means for handling input & output of characters. Character Streams classes are defined by using two abstract classes, namely Reader and Writer.
Famous Quotations
If you don’t make mistakes, you’re not working on hard enough problems. And that’s a big mistake.
-- Frank Wilczek

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.