Home  >  Jackson API

Jackson @JsonProperty and @JsonAlias Example

By Arvind Rai, March 11, 2018
On this page we will provide Jackson @JsonProperty and @JsonAlias annotation example. @JsonProperty defines a logical property used in serialization and deserialization of JSON. When we set JSON data to Java Object, it is called JSON deserialization and when we get JSON data from Java Object, it is called JSON serialization. @JsonProperty can change the visibility of logical property using its access element during serialization and deserialization of JSON. @JsonAlias defines one or more alternative names for a property to be accepted during deserialization. At the time of serialization only actual logical property name is used and not alias. @JsonProperty can also be used with Enum. Here on this page we will provide complete example of @JsonProperty and @JsonAlias step by step.

1. Technologies Used

Find the technologies being used in our example.
1. Java 9
2. Jackson 2.9.4
3. Gradle 4.3.1
4. Eclipse Oxygen

2. @JsonProperty

@JsonProperty is a marker annotation to define logical property. @JsonProperty can be annotated at non-static setter or getter method or non-static object field. The logical property is used in serialization and de-serialization of JSON. @JsonProperty is annotated as following.
1. Using object field.
@JsonProperty("bookCategory")	
private String category; 
2. Using Getter method.
@JsonProperty("bookCategory")	
public String getCategory() {
   return category;
} 
3. Using Setter method.
@JsonProperty("bookCategory")		
public void setCategory(String category) {
    this.category = category;
} 
In all the above cases the logical property is bookCategory. If we do not assign any value to @JsonProperty, for example.
@JsonProperty
private String category;  
Then logical property name is actual property name. In the above code, the logical property will be category. If we are not providing any value, then annotating @JsonProperty to a property is optional.

3. @JsonProperty Elements

The elements of @JsonProperty are as follows.
value: Defines name of logical property.
access: Changes the visibility of logical property in serialization and deserialization.
defaultValue: It is used to document expected default value.
index: Defines numerical index of the property related to other properties specified by object.
required: Defines whether the value for the property is required or not during deserialization.

3.1. @JsonProperty value

value element defines the name of logical property.
@JsonProperty(value= "bookCategory")	
private String category; 
If we are using only value element, we can assign logical property as following.
@JsonProperty("bookCategory")	
private String category; 

3.2. @JsonProperty access

access element changes the visibility of logical property defined by getter or setter or object field. The values of access can be one of followings.
Access.WRITE_ONLY: The visibility of logical property will be only available when we set JSON data to Java object i.e. at the time of deserialization.
Access.READ_ONLY: The visibility of logical property will be only available when we get JSON data from Java object i.e. at the time of serialization.
Access.READ_WRITE: The visibility of logical property will be available at both the time serialization and deserialization.
Access.AUTO: The visibility of logical property will be determined automatically which is the default value of access element.

We can define it as follows.
@JsonProperty(value= "bookCategory", access=Access.WRITE_ONLY)	
private String category; 
In the above code, the logical property bookCategory will be only available at the time of deserialization and not for serialization.

4. @JsonProperty with Enum

Here we will use @JsonProperty with Enum. Suppose we have defined Enum as given below.
public enum Gender {
    @JsonProperty("male") GENDER_MALE,
    @JsonProperty("female") GENDER_FEMALE;
} 
Now when we serialize the above Enum using ObjectMapper as given below,
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(Gender.GENDER_FEMALE)); 
The output will be
 "female" 
And if we do not use @JsonProperty then output will be
"GENDER_FEMALE" 

5. @JsonAlias

@JsonAlias is introduced in Jackson 2.9 release. @JsonAlias defines one or more alternative names for a property to be accepted during deserialization i.e. setting JSON data to Java object. But at the time of serialization i.e. while getting JSON from Java object, only actual logical property name is used and not alias. @JsonAlias is defined as follows.
@JsonAlias({"bkcat", "mybkcat"})
private String category; 
In the above code, the actual logical property is category and alias is bkcat and mybkcat. Now the above property will set value from JSON for JSON field name bkcat, mybkcat and category. If we are defining logical property using @JsonProperty, both @JsonProperty and @JsonAlias can be used as following.
@JsonProperty("bookCategory")	
@JsonAlias({"bkcat", "mybkcat"})
private String category; 
In the above code, the actual logical property is bookCategory and alias is bkcat and mybkcat. At the time of deserialization either JSON is
{
    "bookCategory" : "Java"
} 
Or JSON is
{
    "bkcat" : "Java"
} 
Or JSON is
{
    "mybkcat" : "Java"
} 
All above will set value in object property category. But when we serialization, we will get JSON only with actual logical property name as given below.
{
    "bookCategory" : "Java"
} 

6. 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.4'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.4'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.9.4'
} 
Book.java
package com.concretepage;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Book {
	@JsonProperty("bookName")		
	private String name;
	
	@JsonProperty("bookCategory")	
	@JsonAlias({"bkcat", "mybkcat"})
	private String category;  
	
  	public Book(){}
  	public Book(String name, String category) {
  		this.name = name;
  		this.category = category;
  	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCategory() {
		return category;
	}
	public void setCategory(String category) {
		this.category = category;
	}
} 
Writer.java
package com.concretepage;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Writer {
	@JsonProperty("writerId")	
	private Integer id; 
	
	@JsonProperty("writerName")
	@JsonAlias({"wname", "mywname"})
	private String name;
	
	@JsonProperty("writerBook")	
	private Book book;

  	public Writer(){}
  	public Writer(Integer id, String name, Book book){
  		this.id = id;
  		this.name = name;
  		this.book = book;
  	}	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Book getBook() {
		return book;
	}
	public void setBook(Book book) {
		this.book = book;
	}
} 
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 = 
			    "{"
				  +"\"writerId\" : 111,"
				  +"\"mywname\" : \"Mahesh\","
				  +"\"writerBook\" : {"
				    +"\"bookName\" : \"Learning Spring\","
				    +"\"bkcat\" : \"Spring\""
				  +"}"
			   +"}";
		 ObjectMapper mapper = new ObjectMapper();
		 Writer writer = mapper.readValue(jsonData, Writer.class);
		 System.out.println(writer.getId()+", "+ writer.getName());
		 Book book = writer.getBook();
		 System.out.println(book.getName()+", "+ book.getCategory());
	}
} 
Output
111, Mahesh
Learning Spring, Spring 
ObjectToJSON.java
package com.concretepage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ObjectToJSON {
  public static void main(String[] args) throws JsonProcessingException {
     ObjectMapper mapper = new ObjectMapper();
     Book book = new Book("Learning Java", "Java");
     Writer writer = new Writer(110, "Mohit", book);
     String jsonWriter = mapper.writerWithDefaultPrettyPrinter()
		 .writeValueAsString(writer);
     System.out.println(jsonWriter);
     
  }
} 
Output
{
  "writerId" : 110,
  "writerName" : "Mohit",
  "writerBook" : {
    "bookName" : "Learning Java",
    "bookCategory" : "Java"
  }
} 

7. References

Annotation Type JsonProperty
Annotation Type JsonAlias

8. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us