Jackson @JsonIgnore, @JsonIgnoreProperties and @JsonIgnoreType (2024)

Written by: Arvind Rai,
Last updated:
March 16, 2018

Jackson @JsonIgnore, @JsonIgnoreProperties and @JsonIgnoreType (1)Jackson @JsonIgnore, @JsonIgnoreProperties and @JsonIgnoreType (2) Jackson @JsonIgnore, @JsonIgnoreProperties and @JsonIgnoreType (3)

Jackson API

This page will walk through Jackson @JsonIgnore, @JsonIgnoreProperties and @JsonIgnoreType annotations example. These annotations are used to ignore logical properties in JSON serialization and deserialization. @JsonIgnore is annotated at a class property level to ignore it. @JsonIgnoreProperties is annotated at class level and we need to specify the logical properties of that class to ignore them. @JsonIgnoreType is annotated at class level and it ignores the complete class. @JsonIgnore and @JsonIgnoreType has an element value which accepts Boolean values to make it active and inactive. @JsonIgnoreProperties has elements that are allowGetters, allowSetters, ignoreUnknown and value. The element value in @JsonIgnoreProperties specifies the names of properties to ignore. On this page we will provide complete example to use @JsonIgnore, @JsonIgnoreProperties and @JsonIgnoreType in JSON serialization and deserialization step by step.

Contents
  • 1. Technologies Used
  • 2. @JsonIgnore
  • 3. @JsonIgnoreProperties
    • 3.1. @JsonIgnoreProperties allowGetters
    • 3.2. @JsonIgnoreProperties allowSetters
    • 3.3. @JsonIgnoreProperties ignoreUnknown
  • 4. @JsonIgnoreType
  • 5. Complete Example
  • 6. References
  • 7. Download Source Code

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. @JsonIgnore

@JsonIgnore is used to ignore the logical property used in serialization and deserialization. @JsonIgnore can be used at setter, getter or field. It is used as following.
Using field:

@JsonIgnoreprivate String category; 

Using getter method:

@JsonIgnorepublic String getCategory() { return category;}

Using setter method:

@JsonIgnorepublic void setCategory(String category) { this.category = category;} 

In all the above cases the logical property is category. In deserialization, application will throw exception as Unrecognized field "category". In serialization there will be no category field in JSON output. @JsonIgnore can be used with @JsonProperty as given below.

@JsonIgnore@JsonProperty("bookCategory")private String category; 

In the above code snippet, logical property is bookCategory. As we are using @JsonIgnore, so during JSON serialization and deserialization the logical property bookCategory will not be available.

@JsonIgnore has element value which is optional. Using Boolean we can make it active and inactive. We can use it as following.

@JsonIgnore(false)private String category; 

In the above code we have made @JsonIgnore inactive by passing false value. Now the logical property category will be available in JSON serialization and deserialization.

3. @JsonIgnoreProperties

@JsonIgnoreProperties ignores the specified logical properties in JSON serialization and deserialization. It is annotated at class level. Find the code snippet.

@JsonIgnoreProperties({ "bookName", "bookCategory" })public class Book { @JsonProperty("bookId") private String id; @JsonProperty("bookName") private String name; @JsonProperty("bookCategory") private String category; ------} 

The logical properties bookName and bookCategory has been specified in @JsonIgnoreProperties annotation. So these logical properties will not take part in JSON serialization and deserialization. If other logical properties such as bookId has been annotated with @JsonIgnore then all these logical properties will be ignored in JSON serialization and deserialization. It means the union of logical properties ignored by @JsonIgnore and @JsonIgnoreProperties are considered to be ignored in JSON serialization and deserialization.

@JsonIgnoreProperties has elements that are allowGetters, allowSetters, ignoreUnknown and value. The element value specifies name of properties to ignore.

3.1. @JsonIgnoreProperties allowGetters

When we pass true to allowGetters element, the getters will be allowed for the specified logical properties. It means the specified logical properties in @JsonIgnoreProperties will take part in JSON serialization but not in deserialization.

@JsonIgnoreProperties(value={ "bookName", "bookCategory" }, allowGetters= true)public class Book {------} 

In the above code, the logical properties bookName and bookCategory will take part in JSON serialization but not in deserialization.

3.2. @JsonIgnoreProperties allowSetters

When we pass true to allowSetters element, the setters will be allowed for the specified logical properties. It means the specified logical properties in @JsonIgnoreProperties will take part in JSON deserialization but not in serialization.

@JsonIgnoreProperties(value={ "bookName", "bookCategory" }, allowSetters= true)public class Book {------} 

In the above code, the logical properties bookName and bookCategory will take part in JSON deserialization but not in serialization.

3.3. @JsonIgnoreProperties ignoreUnknown

When we pass true to ignoreUnknown element, then in deserialization if JSON data has a field for which there is no logical property then that JSON field will be ignored and no error will be thrown. It can be used as following.

@JsonIgnoreProperties(ignoreUnknown = true)public class Book {@JsonProperty("bookId")private String id;@JsonProperty("bookName")private String name;@JsonProperty("bookCategory")private String category; } 

In the above class we have bookId, bookName and bookCategory logical properties. Suppose we have a JSON data with some unknown fields.

{ "bookId" : "A101", "bookName" : "Learning Java", "bookCategory" : "Java", "pubYear" : "2018", "price" : "200",} 

In the above JSON fields, pubYear and price has no corresponding logical properties in Book class. In deserialization, we will not get exception because we are using ignoreUnknown = true in @JsonIgnoreProperties annotation.

4. @JsonIgnoreType

@JsonIgnoreType can be annotated at class level. It ignores all logical properties of annotated class in JSON serialization and deserialization. It is used as following.

@JsonIgnoreTypepublic class Address { @JsonProperty("city") private String city; @JsonProperty("country") private String country; ------} 

Now suppose Address is being used in Writer class.

public class Writer { ------ @JsonProperty("writerAddress") private Address address;} 

The logical property writerAddress will be ignored in serialization and deserialization of Writer class.

@JsonIgnoreType has element value which is optional. Using Boolean we can make it active and inactive. We can use it as following.

@JsonIgnoreType(false)public class Address {------} 

In the above code we have made @JsonIgnoreType inactive by passing false value. Now the Address class will be available in JSON serialization and deserialization.

5. 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'} 

Address.java

package com.concretepage;import com.fasterxml.jackson.annotation.JsonIgnoreType;import com.fasterxml.jackson.annotation.JsonProperty;@JsonIgnoreTypepublic class Address { @JsonProperty("city") private String city; @JsonProperty("country") private String country; public Address() {} public Address(String city, String country) {this.city = city;this.country = country; } public String getCity() {return city; } public void setCity(String city) {this.city = city; } public String getCountry() {return country; } public void setCountry(String country) {this.country = country; }} 

Book.java

package com.concretepage;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import com.fasterxml.jackson.annotation.JsonProperty;@JsonIgnoreProperties({"bookName", "bookCategory"})public class Book {@JsonProperty("bookId")private String id;@JsonProperty("bookName")private String name;@JsonProperty("bookCategory")private String category; public Book(){} public Book(String id, String name, String category) { this.id = id; this.name = name; this.category = category; }public String getId() {return id;}public void setId(String id) {this.id = id;}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.JsonIgnore;import com.fasterxml.jackson.annotation.JsonProperty;public class Writer {@JsonProperty("writerId")private Integer id; @JsonIgnore@JsonProperty("writerName")private String name;@JsonProperty("writerBook")private Book book;@JsonProperty("writerAddress")private Address address; public Writer(){} public Writer(Integer id, String name, Book book, Address address){ this.id = id; this.name = name; this.book = book; this.address = address; }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;}public Address getAddress() {return address;}public void setAddress(Address address) {this.address = address;}} 

Run the code for serialization.
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("A101", "Learning Java", "Java"); Address address = new Address("Noida", "India"); Writer writer = new Writer(110, "Mohit", book, address); String jsonWriter = mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(writer); System.out.println(jsonWriter); }} 

Output

{ "name" : "Mohit", "writerId" : 110, "writerBook" : { "bookId" : "A101" }} 

If we use neither @JsonIgnore nor @JsonIgnoreProperties nor @JsonIgnoreType in the above example then the output will be as given below.

{ "writerId" : 110, "writerName" : "Mohit", "writerBook" : { "bookId" : "A101", "bookName" : "Learning Java", "bookCategory" : "Java" }, "writerAddress" : { "city" : "Noida", "country" : "India" }} 

Now run the code for deserialization.
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," // +"\"writerName\" : \"Mahesh\"," +"\"writerBook\" : {" +"\"bookId\" : \"A101\"" // +"\"bookName\" : \"Learning Spring\"," // +"\"bookCategory\" : \"Spring\"" +"}" // +"\"writerAddress\" : {" // +"\"city\" : \"Noida\"," // +"\"country\" : \"India\"" // +"}" +"}"; ObjectMapper mapper = new ObjectMapper(); Writer writer = mapper.readValue(jsonData, Writer.class); System.out.println(writer.getId()); //System.out.println(writer.getName()); Book book = writer.getBook(); System.out.println(book.getId()); //System.out.println(book.getName()+", "+ book.getCategory()); //System.out.println(book.getName()+", "+ book.getCategory()); // Address address = writer.getAddress(); // System.out.println(address.getCity()+", "+ address.getCountry());}} 

Output

111A101 

6. References

Annotation Type JsonIgnore
Annotation Type JsonIgnoreProperties
Annotation Type JsonIgnoreType

7. Download Source Code

jackson-jsonignore-jsonignoreproperties-and-jsonignoretype.zip

Jackson @JsonIgnore, @JsonIgnoreProperties and @JsonIgnoreType (2024)

FAQs

Jackson @JsonIgnore, @JsonIgnoreProperties and @JsonIgnoreType? ›

In Jackson, we can use @JsonIgnore to ignore a single field, @JsonIgnoreProperties to ignore multiple fields and @JsonIgnoreType to ignore a specified type during JSON serialization and deserialization.

What does @JsonIgnoreProperties do? ›

Annotation that can be used to either suppress serialization of properties (during serialization), or ignore processing of JSON properties read (during deserialization). Annotation can be applied both to classes and to properties.

What is the difference between @JsonIgnore and @JsonIgnoreProperties? ›

@JsonIgnore is to ignore fields used at field level. while, @JsonIgnoreProperties is used at class level, used for ignoring a list of fields. Annotation can be applied both to classes and to properties.

What is @JsonProperty used for? ›

@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.

How to use @JsonIgnore annotation? ›

We use the @JsonIgnore annotation to specify a method or field that should be ignored during serialization and deserialization processes. This marker annotation belongs to the Jackson library. We often apply this annotation to exclude fields that may not be relevant or could contain sensitive information.

Can we use @JsonProperty at class level? ›

@JsonProperty annotation is useful for defining the logical property for the field used during serialization and deserialization. Primarily used in the Model Class, when the response from the API is different from the model class.

How to ignore JSON property based on condition in Java? ›

You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored. If no Condition is specified, this option is assumed.

What is the difference between @JsonIgnore and transient? ›

⚙️ Background: @JsonIgnore is often used to exclude fields from being serialized to JSON, while @Transient is used to mark fields as non-persistent and should not be serialized. However, the interaction between these two annotations in Jackson 2.15 might not behave as expected.

What is the difference between XmlTransient and JsonIgnore? ›

@XmlTransient is a JAXB annotation that signals marshallers to ignore a field/property. @JsonIgnore is a proprietary Jackson annotation that signals Jackson to ignore a field/property.

What is the difference between @PATH and @pathvariable? ›

@PathParam: it is used to inject the value of named URI path parameters that were defined in @Path expression. @Pathvariable: This annotation is used to handle template variables in the request URI mapping ,and used them as method parameters.

What is the difference between DataMember and JsonProperty? ›

Json.NET is the one who reads the DataMember and JsonProperty attributes. JsonProperty is from Json.NET and its purpose is to control how the field or property is serialized. While DataMember, which is from Microsoft, is read by Json.NET for convenience. JsonProperty provides more configuration options than DataMember.

What is the use of JsonProperty in C#? ›

JsonProperty is an attribute in C# (and other programming languages) that allows developers to control the mapping between property names and JSON keys when serializing or deserializing objects. It is often used in conjunction with JSON frameworks such as Newtonsoft. Json.

What are Jackson annotations? ›

Jackson Annotations - @JacksonInject

@JacksonInject is used when a property value is to be injected instead of being parsed from Json input. In the example below, we are inserting a value into object instead of parsing from the Json.

What does @JsonIgnoreProperties ignoreUnknown true mean? ›

@JsonIgnoreProperties: This annotation is used on the target class level and allows you to specify which properties (fields) to ignore during serialization and deserialization. The special value "ignoreUnknown" can be set to true to indicate that all unknown fields should be ignored.

What is @transient in JPA? ›

@Transient Annotation vs.

The transient keyword is primarily meant for ignoring fields during Java object serialization, but it also prevents these fields from being persisted when using a JPA framework. In other words, the transient keyword has the same effect as the @Transient annotation when saving to a database.

What is @JsonInclude annotation? ›

@JsonInclude is used at exclude properties having null/empty or default values.

What is JsonIgnoreProperties({ hibernateLazyInitializer handler })? ›

@JsonIgnoreProperties ({ "hibernateLazyInitializer" , "handler" }) public class BusinessEntity { ... @JsonIgnoreProperties({“hibernateLazyInitializer”, “handler”}) allows Jackson to ignore the garbage created by Hibernate, so it can manage lazy loading of data as referred before.

What is the use of @transient annotation? ›

@Transient Annotation

It is simply used to mark a field as transient. In this example, the User class represents a table in a database. The @Entity annotation is applied to the class to indicate that it should be mapped to a database table.

References

Top Articles
Q1 2025 EPS Estimates for Lithia Motors, Inc. (NYSE:LAD) Lowered by Analyst
Lithia Motors : Statement of Changes in Beneficial Ownership - Form 4
Mansfield Shower Surround
Target Dummies 101 - The Dummy Research/Tutorial Thread
Dr. Hannah Straight Website
Meet Scores Online 2022
Honda Odyssey Questions - P0303 3 cyclinder misfire
Pobierz Papa's Mocharia To Go! na PC za pomocą MEmu
Steve Wallis Wife Age
UK HealthCare EpicCare Link
Feliz Domingo Bendiciones, Mensajes cristianos para compartir | Todo imágenes
Hallmark White Coat Ceremony Cards
Ups Store Fax Cost
Strange World Showtimes Near Harkins Metrocenter 12
’Vought Rising’: What To Know About The Boys Prequel, A Season 5 Link
Configuring Fail2ban with Traefik
‘An affront to the memories of British sailors’: the lies that sank Hollywood’s sub thriller U-571
Dupage County Fcrc
Epay. Medstarhealth.org
Four-Legged Friday: Meet Tuscaloosa's Adoptable All-Stars Cub & Pickle
Kroger Liquor Hours
Bannerlord How To Get Your Wife Pregnant
Xxc Renegade 1000 Xxc Price In India Price
H. P. Lovecraft - Deutsche Lovecraft Gesellschaft
7 Little Johnstons Alex Died Full Episode
Appraisalport Com Dashboard /# Orders
Rugged Gentleman Barber Shop Martinsburg Wv
Atlanticbb Message Center
Dayinew
Sharkbrew
Nsa Panama City Mwr
Ktbs Payroll Login
Skyward Login Wylie Isd
Owyhee County Extension Office
Marissa.munoz17
Crazy 8S Cool Math
TWENTY/20 TAPHOUSE, Somerset - Menu, Prices & Restaurant Reviews - Order Online Food Delivery - Tripadvisor
Mission Impossible 7 Showtimes Near Regal Bridgeport Village
Directions To 401 East Chestnut Street Louisville Kentucky
Harpel Hamper
Armored Beacon Feh
When His Eyes Opened Chapter 3021
Craigslist Farm And Garden Reading Pa
Crossword Answers, Crossword Solver
Watermelon Cucumber Basil Lemonade - Wine a Little, Cook a Lot
Jersey Mike's Subs: 16 Facts About The Sandwich Chain - The Daily Meal
SF bay area cars & trucks "chevrolet 50" - craigslist
Live TV | Halifax | CBC Gem
Gunsmoke Noonday Devil Cast
Wayfair Outlet Dayton Ohio
Mileage To Walmart
Auctionzipauctions
Latest Posts
Article information

Author: Kareem Mueller DO

Last Updated:

Views: 6474

Rating: 4.6 / 5 (46 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Kareem Mueller DO

Birthday: 1997-01-04

Address: Apt. 156 12935 Runolfsdottir Mission, Greenfort, MN 74384-6749

Phone: +16704982844747

Job: Corporate Administration Planner

Hobby: Mountain biking, Jewelry making, Stone skipping, Lacemaking, Knife making, Scrapbooking, Letterboxing

Introduction: My name is Kareem Mueller DO, I am a vivacious, super, thoughtful, excited, handsome, beautiful, combative person who loves writing and wants to share my knowledge and understanding with you.