Search

Suggested keywords:
  • Java
  • Docker
  • Git
  • React
  • NextJs
  • Spring boot
  • Laravel

Jackson Annotations with Examples

  • Share this:

post-title

Jackson is most widely used JSON parsing library in Java. It is used in most of the frameworks. It has various annotations to serialize and deserialize JSON data. This will help to customize the behaviour. In this article we will explore few important annotations like JsonProperty, JsonFormat, JsonIgnore, JsonIgnoreProperties, JsonPropertyOrder, JsonRawValue, JsonCreator, JsonRootName, JsonValue, JsonAnyGetter, JsonSetter, JsonGetter.

To learn basics of Jackson and how to serialize and deserialize POJO, refer to our previous article Understanding Basics of Jackson JSON Parser

 

JsonPropery

If we want to change the property name while serializing data then we used use this annotation.

public class Person {
    
	@JsonProperty("full_name")
	private String name;

	private String password;
	private Date birthDate;
	private int age;
}

When we serialize instead of name, full_name property will be used.  To test, use the function test_serialize_person defined below.

 

JsonIgnore

Sometimes we want to ignore few properties while serializing data. JsonIgnore annotation helps to ignore the property from being serialized.

public class Person {
    
	@JsonProperty("full_name")
	private String name;

    @JsonIgnore
	private String password;
	private Date birthDate;
	private int age;
}

To test, use the function test_serialize_person defined below.

 

JsonFormat

If we want to change the way the object 's value to be serialized then JsonFormat annotation has to be used. Best example is with Date, if we don't use this annotation, it might serialize to time in milliseconds. Below sample code prints the date in ISO 8601 format.

public class Person {
    
	@JsonProperty("full_name")
	private String name;

    @JsonIgnore
	private String password;

   @JsonFormat(pattern = "yyyy-MM-dd'T'HH:MM")
	private Date birthDate;
	private int age;
}

To test, use the function test_serialize_person defined below.

 

Test function

public static void test_serialize_person() throws JsonProcessingException {
    	
	// Create a Person object
	Person person = new Person();
	person.setName("Jane Smith");
	person.setPassword("password");
	person.setBirthDate(Date.from(Instant.now()));
	person.setAge(28);

        // Create ObjectMapper instance
	ObjectMapper objectMapper = new ObjectMapper();

	// Convert Person object to JSON
	String json = objectMapper.writeValueAsString(person);
	System.out.println("JSON: " + json);
    	
}

public static void test_deserialize_person() throws JsonMappingException, JsonProcessingException {
    	
    	  // Create ObjectMapper instance
        ObjectMapper objectMapper = new ObjectMapper();

        // JSON to Java
        String json = "{\"full_name\":\"Jane Smith\",\"age\":28, \"birthDate\":\"2024-04-25T10:04\"}";
        Person person = objectMapper.readValue(json, Person.class);

        // Print Java object
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());
        System.out.println("Date: " + person.getBirthDate());
    }

 

The above function will print the output as below

//Serialize
JSON: {"birthDate":"2024-05-02T07:05","age":28,"full_name":"Jane Smith"}

//deserialize
Name: Jane Smith
Age: 28
Date: Thu Apr 25 15:30:00 IST 2024

 

JsonIgnoreProperties

This is similar to JsonIgnore annotation but it can ignore multiple properties.

@JsonIgnoreProperties({"id", "email"})
public class User {
	
	private String id;
	private String name;
	private String lastName;
	private int    age;
	private String email;
}

When we serialize user, id and email field will be ignored and the rest will be serialized.

 

JsonPropertyOrder

Usually when we serialize, JSON string will be generated using the same order as we listed in the class definition. If we want to change the order then we need to use JsonPropertyOrder annotation.

@JsonPropertyOrder({"lastName", "name", "age"})
public class User {
	
	private String id;
	private String name;
	private String lastName;
	private int    age;
	private String email;
}

In the below sample, lastName will be printed first and followed by name and age

 

JsonRawValue

If we already have JSON value and we just want to print the same in the JSON output then we have to use JsonRawValue annotation.

@JsonIgnoreProperties({"id", "email"})
@JsonPropertyOrder({"lastName", "name", "age"})
public class User {
	
	private String id;
	private String name;
	private String lastName;
	private int    age;
	private String email;
	
	@JsonRawValue
	private String certificate;
}

 

Let's test the function

public static void test_serialize_user() throws JsonProcessingException {
		
	String cert = "{\"course\":\"Spring Boot Advanced\",\"score\":76, \"completedDate\":\"2024-04-25 10:04\"}";

	// Create ObjectMapper instance
	ObjectMapper objectMapper = new ObjectMapper();

	// Create a User object
	User user = new User();
	user.setId("1");
	user.setName("Jai");
	user.setLastName("Gates");
	user.setEmail("jai@exmaple.com");
	user.setAge(25);
	user.setCertificate(cert);

	// Convert Person object to JSON
	String json = objectMapper.writeValueAsString(user);
	System.out.println("JSON: " + json);
    	
}

 

The above function will print the output as below

JSON: {"lastName":"Gates","name":"Jai","age":25,
           "certificate":{"course":"Spring Boot Advanced","score":76, "completedDate":"2024-04-25 10:04"}}

 

JsonAnyGetter

Consider we have a map of properties which we want to include in the root JSON as fields instead of nested object. This map field will not have getter and setter functions defined. Use JsonAnyGetter annotation to output the property values of the map in the root JSON.

public class EmployeeNameMap {

	public String orgName;

	@JsonAnyGetter
	private Map<String, String> employeePropMap;

	public EmployeeNameMap(String orgName, Map<String, String> employeePropMap) {
		super();
		this.orgName = orgName;
		this.employeePropMap = employeePropMap;
	}
	public String getOrgName() {
		return orgName;
	}
	public void setOrgName(String orgName) {
		this.orgName = orgName;
	}
    
}

Let's test this function.

public static void test_employee_map() throws JsonProcessingException {
		
	Map<String, String> employeePropMap = new HashMap<>();
	employeePropMap.put("name",    "Jai");
	employeePropMap.put("country", "India");

	EmployeeNameMap nameMap = new EmployeeNameMap("MyOrg", employeePropMap);

	// Convert Person object to JSON
	ObjectMapper objectMapper = new ObjectMapper();
	String json = objectMapper.writeValueAsString(nameMap);
	System.out.println("JSON: " + json);
    	
}

 

The above function will print the output as below

JSON: {"EmployeeNameMap":{"orgName":"MyOrg","country":"India","name":"Jai"}}

 

JsonRootName

If we want to change the root JSON name to be different then we need to use this annotation. To use this annotation, we need to enable the feature in ObjectMapper instance objectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE); 

@JsonRootName("user")
public class UserRecord {
	
	private String id;
	private String name;
	private String email;

}

 

JsonValue

If we want to serialize the object using its value perferably toString(), in this case we need to use JsonValue annotation.

@JsonRootName("user")
public class UserRecord {
	
	private String id;
	private String name;
	private String email;
	
	@JsonValue
	public String toString() {
		return id + "-" + name + "-" + email;
	}
}

 

JsonCreator

In order to deserialize the JSON to POJO, If we want to use specific creator function instead of standard constructor then JsonCreator annotation has to be used.

@JsonRootName("user")
public class UserRecord {
	
	private String id;
	private String name;
	private String email;
		
	public UserRecord(String id, String name, String email) {
		super();
		this.id = id;
		this.name = name;
		this.email = email;
	}
	
	@JsonCreator
	public UserRecord(@JsonProperty("user") String user) {
		String val[] = user.split("-");
		id = val[0];
		name = val[1];
		email = val[2];
	}
	
	@JsonValue
	public String toString() {
		return id + "-" + name + "-" + email;
	}
}

 

Let's test this annotation.

public static void test_user_record() throws JsonProcessingException {
	
	UserRecord val = new UserRecord("1", "Jai", "jai.gates@example.com");
	System.out.println("val: " + val.toString());

	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
	String json = objectMapper.writeValueAsString(val);
	System.out.println("JSON: " + json);

	UserRecord val2 = objectMapper.readValue(json, UserRecord.class);
	System.out.println("val: " + val2.toString());
	
}

 

The above function will print the output as below

val: 1-Jai-jai.gates@example.com

JSON: {"user":"1-Jai-jai.gates@example.com"}

val: 1-Jai-jai.gates@example.com

 

JsonGetter and JsonSetter

If we want to use different function for property name then we need to JsonGetter and JsonSetter annotation.

package com.blackslate.jackson;

import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonSetter;

public class Employee {
	
	String name;
	String birthDate;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@JsonSetter("birthDate")
	public void setDateOfBirth(String birthDate) {
        this.birthDate = birthDate;
    }

	@JsonGetter("birthDate")
	public String getDateOfBirth() {
        return birthDate;
    }
	
	public String toString() {
		return name + " " + birthDate;
	}
}

 

Let's test this function and see how it works.

public static void test_getter_setter() throws JsonProcessingException {
		
	Employee emp = new Employee();
	emp.setName("Jai");
	emp.setDateOfBirth("1980-01-01");

	// Convert Person object to JSON
	ObjectMapper objectMapper = new ObjectMapper();
	String json = objectMapper.writeValueAsString(emp);
	System.out.println("JSON: " + json);
	
	Employee emp2 = objectMapper.readValue(json, Employee.class);
	System.out.println("val: " + emp2.toString());    	
}

 

The above function will print the output as below

JSON: {"name":"Jai","birthDate":"1980-01-01"}
val: Jai 1980-01-01

 

Source code available in Github

Conclusion

In this article, we explored most frequently used Jackson annotation.

Happy Coding !

 

Editorial Team

About author
This article is published by our editorial team.