Home  >  Jackson API

Jackson @JsonFormat Example

By Arvind Rai, June 11, 2018
On this page we will provide Jackson @JsonFormat example. @JsonFormat is used to decide how values of properties to be serialized. We can use @JsonFormat with Date properties to decide if date should be serialized in number or string format. Using @JsonFormat, timezone of date property can also be changed in serialization. @JsonFormat is also used to format Enum, Collection and Number in serialization. Here on this page we will provide @JsonFormat examples with Date properties and Java enum in serialization.

Technologies Used

Find the technologies being used in our example.
1. Java 9
2. Jackson 2.9.5
3. Gradle 4.3.1

@JsonFormat

@JsonFormat handles the serialization of Date, Enum, Collection and Number. @JsonFormat decides how values of properties to be serialized. Find some of the attributes of @JsonFormat annotation.
shape: Defines the structure to use for serialization, for example JsonFormat.Shape.NUMBER and JsonFormat.Shape.STRING.
pattern: Pattern used in serialization and deserializations. For date, pattern contains SimpleDateFormat compatible definition.
locale: Locale used in serialization. Default is system default locale.
timezone: TimeZone used in serialization. Default is system default timezone.
lenient: Useful in deserializations. It decides if lenient handling should be enabled or disabled.

JsonFormat.Shape.STRING

When we assign JsonFormat.Shape.STRING to shape attribute in @JsonFormat for a property, suppose Date type, then in serialization JSON will be string type in given pattern for that property.
public class Writer {
   @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MMM-dd HH:mm:ss z")
   @JsonProperty("pubDate")
   private Date recentBookPubDate;

} 
Output will be as following.
{
  "pubDate" : "2018-Jun-11 07:41:23 UTC"
} 

JsonFormat.Shape.NUMBER

When we assign JsonFormat.Shape.NUMBER to shape attribute in @JsonFormat for a property, suppose Date type, then in serialization JSON will be number type for that property.
public class Writer {
   @JsonFormat(shape=JsonFormat.Shape.NUMBER)
   @JsonProperty("bdate")
   private Date birthDate;
} 
Output will be as following.
{
  "bdate" : 1528702883858
} 

@JsonFormat with Enum

@JsonFormat can be used with Java enum in serialization to change between index (number) and textual name (string). @JsonFormat is used at enum level and not at property level. By default enum properties are serialized with its textual name as string. We can change it to property index (starting from 0) using JsonFormat.Shape.NUMBER. Find the sample example.
package com.concretepage;
import com.fasterxml.jackson.annotation.JsonFormat;

@JsonFormat(shape=JsonFormat.Shape.NUMBER)
enum Code {
    BLOCKING,
    CRITICAL,
    MEDIUM,
    LOW;
} 
We are serializing enum here using ObjectMapper as following.
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(Code.BLOCKING));
System.out.println(mapper.writeValueAsString(Code.CRITICAL)); 
Find the output.
0
1 
Now if we use JsonFormat.Shape.STRING as following.
@JsonFormat(shape=JsonFormat.Shape.STRING)
enum Code {
  ------
} 
Then output will be textual name.
"BLOCKING"
"CRITICAL" 

Time Zone

timezone attribute of @JsonFormat annotation specify TimeZone for example IST, EST, PST etc. timezone is useful in serialization. Find the example.
public class Writer {
   @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MMM-dd HH:mm:ss z", timezone="EST")
   @JsonProperty("pubDate")
   private Date recentBookPubDate;	
} 
Output will be as follows.
{
  "pubDate" : "2018-Jun-11 08:17:37 EST"
} 

Complete Example

build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'concretepage'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.5'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.5'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.9.5'
} 
Writer.java
package com.concretepage;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Writer {
	@JsonProperty("writerName")
	private String name;
	
	@JsonFormat(shape=JsonFormat.Shape.NUMBER)
	@JsonProperty("bdate")
	private Date birthDate;
	
	@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MMM-dd HH:mm:ss z", timezone="EST")
	@JsonProperty("pubDate")
	private Date recentBookPubDate;	
	
	public Writer() {}
	public Writer(String name, Date birthDate, Date recentBookPubDate) {
		this.name = name;
		this.birthDate = birthDate;
		this.recentBookPubDate = recentBookPubDate;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getBirthDate() {
		return birthDate;
	}
	public void setBirthDate(Date birthDate) {
		this.birthDate = birthDate;
	}
	public Date getRecentBookPubDate() {
		return recentBookPubDate;
	}
	public void setRecentBookPubDate(Date recentBookPubDate) {
		this.recentBookPubDate = recentBookPubDate;
	}
} 
ObjectToJSON.java
package com.concretepage;
import java.util.Date;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ObjectToJSON {
  public static void main(String[] args) throws JsonProcessingException {
     Writer writer = new Writer("Mohit", new Date(), new Date());   
     ObjectMapper mapper = new ObjectMapper();     
     String jsonData = mapper.writerWithDefaultPrettyPrinter()
		 .writeValueAsString(writer);
     System.out.println(jsonData);
  }
} 
Output
{
  "writerName" : "Mohit",
  "bdate" : 1528726220972,
  "pubDate" : "2018-Jun-11 09:10:20 EST"
} 
JSONToObject.java
package com.concretepage;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONToObject {
	public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
		 String jsonData = 
		    "{"
			  +"\"writerName\" : \"Mahesh\","
			  +"\"bdate\" : 1528703231286,"
			  +"\"pubDate\" : \"2018-Jun-11 07:00:46 EST\""	
		   +"}";
		 ObjectMapper mapper = new ObjectMapper();
		 Writer writer = mapper.readValue(jsonData, Writer.class);
		 System.out.println(writer.getName());
		 System.out.println(writer.getBirthDate()+" | "+ writer.getRecentBookPubDate());
	}
} 
Output
Mahesh
Mon Jun 11 13:17:11 IST 2018 | Mon Jun 11 17:30:46 IST 2018 

Reference

Annotation Type JsonFormat

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us