Jackson JSON: difference between @JsonIgnore and @JsonIgnoreProperties annotations (2024)

Jackson has two different annotations to use when you want to exclude some class members from the JSON serialization and deserialization processes. These two annotations are @JsonIgnore and @JsonIgnoreProperties.
@JsonIgnoreProperties is an annotation at the class level and it expects that the properties to be excluded would be explicitly indicated in the form of a list of strings.
@JsonIgnore instead is a member-level or method-level annotation, which expects that the properties to be excluded are marked one by one. To completely exclude a member from the process of serialization and de-serialization it’s possibile to annotate the actual property or its setter or its getter. (This behavior is in force since version 1.9 of Jackson). It’s also possible to exclude properties in an asymmetrical way between serialization and deserialization, but we’ll see an example of this case in another post.

Now let’s see a concrete example of use of these annotations. We create a class MyTestClass with some properties and the related getters and setters and a simple test class in which we create an object of that class and then we perform its JSON serialization and deserialization.
We start with an example using the class as-is, without annotations which exclude certain properties.

import java.io.IOException;import com.fasterxml.jackson.core.JsonParseException;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.JsonMappingException;import com.fasterxml.jackson.databind.ObjectMapper;class MyTestClass { private long id; private String name; private String notInterstingMember; private int anotherMember; private int forgetThisField; public long getId() { return this.id; } public void setId(long id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getNotInterstingMember() { return this.notInterstingMember; } public void setNotInterstingMember(String notInterstingMember) { this.notInterstingMember = notInterstingMember; } public int getAnotherMember() { return this.anotherMember; } public void setAnotherMember(int anotherMember) { this.anotherMember = anotherMember; } public int getForgetThisField() { return this.forgetThisField; } public void setForgetThisField(int forgetThisField) { this.forgetThisField = forgetThisField; } @Override public String toString() { return "MyTestClass [" + this.id + " , " + this.name + ", " + this.notInterstingMember + ", " + this.anotherMember + ", " + this.forgetThisField + "]"; }}public class JSONIgnorePropTest { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper(); MyTestClass mtc = new MyTestClass(); mtc.setId(1); mtc.setName("Test program"); mtc.setNotInterstingMember("Don't care about this"); mtc.setAnotherMember(100); mtc.setForgetThisField(-1); String s = null; try { s = mapper.writeValueAsString(mtc); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(s); MyTestClass mtc2 = null; try { mtc2 = mapper.readValue(s, MyTestClass.class); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(mtc2.toString()); }}

The result of this first run is the following, in which all the fields and their values are serialized and then “reconstructed” during deserialization.

{"id":1,"name":"Test program","notInterstingMember":"Don't care about this","anotherMember":100,"forgetThisField":-1}MyTestClass [1 , Test program, Don't care about this, 100, -1]

Now suppose you want to exclude from the results of serialization and deserialization some of the class MyTestClass properties, for instance the “notInterstingMember” and “forgetThisField” properties. As first case we see how to achieve this with the @JsonIgnoreProperties annotation. To do that we have to change our MyTestClass class as follows:

@JsonIgnoreProperties({"notInterstingMember", "forgetThisField"})class MyTestClass { private long id; private String name; private String notInterstingMember; private int anotherMember; private int forgetThisField;// REST OF THE CODE...}

By running the program again, this time we get the following result:

{"id":1,"name":"Test program","anotherMember":100}MyTestClass [1 , Test program, null, 100, 0]

As we can see, in the string produced by the serialization process are not present the values of the properties that we have indicated to exclude through the annotation. After the deserialization therefore, these properties assume the default value provided by their type, then “null” for the String property and 0 for the int property.

The same result can also be obtained using the other annotation, @JsonIgnore which, as mentioned, is not a “class-level” annotation but a “member-level” or “method-level” one. Let’s change again our example class as follows:

class MyTestClass {private long id;private String name;@JsonIgnoreprivate String notInterstingMember;private int anotherMember;@JsonIgnoreprivate int forgetThisField;// REST OF THE CODE}

By running the program again we can see that the result is the same as in the previous case.

{"id":1,"name":"Test program","anotherMember":100}MyTestClass [1 , Test program, null, 100, 0]

As we said at the beginning of the post, to accomplish this result using the @JsonIgnore annotation, it can be put directly on the instance member or on its getter or its setter. The application of the annotation in any of these 3 points, leads to the total exclusion of the property from both the serialization and de-serialization processes (this applies starting from Jackson 1.9; the version used in these examples is Jackson 2.4.3).
It’s possible to change this behavior and make it asymmetric, for example to exclude a property only from the deserialization using the @JsonIgnore annotation together with another annotation called @JsonProperty.

In the following example we annotate with @JsonIgnore the getter of the “notInterstingMember” property and the setter of the “forgetThisField” property (without annotate the property itself). How can we see the result is once again equal to those from previous examples.

import java.io.IOException;import com.fasterxml.jackson.annotation.JsonIgnore;import com.fasterxml.jackson.core.JsonParseException;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.JsonMappingException;import com.fasterxml.jackson.databind.ObjectMapper;class MyTestClass { private long id; private String name; private String notInterstingMember; private int anotherMember; private int forgetThisField; public long getId() { return this.id; } public void setId(long id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } @JsonIgnore public String getNotInterstingMember() { return this.notInterstingMember; } public void setNotInterstingMember(String notInterstingMember) { this.notInterstingMember = notInterstingMember; } public int getAnotherMember() { return this.anotherMember; } public void setAnotherMember(int anotherMember) { this.anotherMember = anotherMember; } public int getForgetThisField() { return this.forgetThisField; } @JsonIgnore public void setForgetThisField(int forgetThisField) { this.forgetThisField = forgetThisField; } @Override public String toString() { return "MyTestClass [" + this.id + " , " + this.name + ", " + this.notInterstingMember + ", " + this.anotherMember + ", " + this.forgetThisField + "]"; }}
{"id":1,"name":"Test program","anotherMember":100}MyTestClass [1 , Test program, null, 100, 0]

See also:

  • Jackson: using @JsonSerialize (or @JsonDeserialize) annotation to register a custom serializer (or deserializer)
  • Jackson JSON: deserialize a list of objects of subclasses of an abstract class
  • Jackson:how to exclude null value properties from JSON serialization

The code of the 3 different examples described in the post can be downloaded here:

Jackson JSON: difference between @JsonIgnore and @JsonIgnoreProperties annotations (1)

Jackson JsonIgnore examples

1 file(s) 2.62 KB

Download

Jackson JSON: difference between @JsonIgnore and @JsonIgnoreProperties annotations (2024)

FAQs

Jackson JSON: difference between @JsonIgnore and @JsonIgnoreProperties annotations? ›

@JsonIgnore annotation is another property inclusion annotation used for marking property or list of properties to be ignored. The only difference between @JsonIgnoreProperties and @JsonIgnore is that @JsonIgnore is used at field level, whereas @JsonIgnoreProperties is used as class level.

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 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 does @JsonIgnore do in spring boot? ›

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.

What does @JsonInclude annotation do? ›

@JsonInclude

It is used at serialization time only. It says that if the value of a property (or all properties) in question is equal to a certain value ( null , empty - whatever that means, or a default value) this property is not serialized. Without this annotation, the property value is always serialized.

What does @JsonProperty do? ›

@JsonProperty: Marker annotation that can be used to define a non-static method as a "setter" or "getter" for a logical property (depending on its signature), or non-static object field to be used (serialized, deserialized) as a logical property.

Can we use @JsonProperty at class level? ›

Since @JsonIgnore is at property level, if we have multiple properties that need to be ignore, then we can implement at the class level using the annotation @JsonIgnoreProperties.

When to use @JsonCreator? ›

We can use the @JsonCreator annotation to tune the constructor/factory used in deserialization. It's very useful when we need to deserialize some JSON that doesn't exactly match the target entity we need to get.

How does Jackson ignore unknown properties annotation? ›

That's all about how to ignore unknown properties while parsing JSON in Java using Jackson API. You can do this either by using @JsonIgnoreProperties annotation or configuring ObjectMapper to not fail when encountering unknown properties during deserialization by disabling FAIL_ON_UNKNOWN_PROPERTIES.

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 use of @ConditionalOnProperty in Spring Boot? ›

Spring Boot provides an annotation for this purpose. @ConditionalOnProperty is the annotation which checks given property has specific value or not. If it has the specified value, then the annotated bean will be enabled else disabled. Consider a scenario wherein application connects to external https endpoint.

What is the difference between JsonIgnore and XML 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 @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 does @jsonignoreproperties ignoreunknown true do? ›

If true, all properties that are unrecognized -- that is, there are no setters or creators that accept them -- are ignored without warnings (although handlers for unknown properties, if any, will still be called) without exception.

What do @JsonSubTypes do? ›

The @JsonSubTypes approach offers explicit configuration by defining subtypes and their type names through annotations. This provides a centralized and clear hierarchy, ensuring compile-time safety.

What does @JsonUnwrapped do? ›

@JsonUnwrapped is used to unwrap values of objects during serialization or de-serialization.

What is the difference between JSON load and JSON dumps? ›

Comparison Between json.

loads() function is used to parse a JSON string and convert it into a Python object, while the json. dump() function is used to serialize a Python object into a JSON formatted string and write it to a file-like object. In other words, json. loads() is used for deserialization, and json.

What does JsonIgnoreProperties({ hibernateLazyInitializer handler }) do? ›

Using @JsonIgnoreProperties, there won't be any duplication anymore in the JSON response. Another thing you'll observe is that at the end of every object and field is added hibernateLazyInitializer”: {}.

What is the difference between JSON object and JSON map? ›

A JSONObject is an unordered collection of name/value pairs whereas Map is an object that maps keys to values. A Map cannot contain duplicate keys and each key can map to at most one value. We need to use the JSON-lib library for serializing and de-serializing a Map in JSON format.

References

Top Articles
How to Brine a Turkey - The Best Turkey Brine Recipe Ever
Crispy Baked Eggplant Recipe
$4,500,000 - 645 Matanzas CT, Fort Myers Beach, FL, 33931, William Raveis Real Estate, Mortgage, and Insurance
Edina Omni Portal
Weeminuche Smoke Signal
Mlifeinsider Okta
Joe Gorga Zodiac Sign
Fire Rescue 1 Login
Crusader Kings 3 Workshop
Hartland Liquidation Oconomowoc
735 Reeds Avenue 737 & 739 Reeds Ave., Red Bluff, CA 96080 - MLS# 20240686 | CENTURY 21
Cvb Location Code Lookup
Sky X App » downloaden & Vorteile entdecken | Sky X
Nutrislice Menus
Walmart stores in 6 states no longer provide single-use bags at checkout: Which states are next?
R Cwbt
Ms Rabbit 305
Uconn Health Outlook
Happy Life 365, Kelly Weekers | 9789021569444 | Boeken | bol
Doublelist Paducah Ky
Canvasdiscount Black Friday Deals
Nsa Panama City Mwr
Rubber Ducks Akron Score
Wics News Springfield Il
Sec Baseball Tournament Score
Nesb Routing Number
Suspiciouswetspot
Joann Fabrics Lexington Sc
Renfield Showtimes Near Marquee Cinemas - Wakefield 12
Metro By T Mobile Sign In
RFK Jr., in Glendale, says he's under investigation for 'collecting a whale specimen'
The Pretty Kitty Tanglewood
How to Play the G Chord on Guitar: A Comprehensive Guide - Breakthrough Guitar | Online Guitar Lessons
W B Crumel Funeral Home Obituaries
Covalen hiring Ai Annotator - Dutch , Finnish, Japanese , Polish , Swedish in Dublin, County Dublin, Ireland | LinkedIn
Agematch Com Member Login
Flashscore.com Live Football Scores Livescore
Chs.mywork
Jefferson Parish Dump Wall Blvd
Dying Light Nexus
Vision Source: Premier Network of Independent Optometrists
Legit Ticket Sites - Seatgeek vs Stubhub [Fees, Customer Service, Security]
How To Upgrade Stamina In Blox Fruits
VDJdb in 2019: database extension, new analysis infrastructure and a T-cell receptor motif compendium
What Is The Optavia Diet—And How Does It Work?
Mother Cabrini, the First American Saint of the Catholic Church
Costco The Dalles Or
Displacer Cub – 5th Edition SRD
Dobratz Hantge Funeral Chapel Obituaries
Every Type of Sentinel in the Marvel Universe
Autozone Battery Hold Down
De Donde Es El Area +63
Latest Posts
Article information

Author: Duane Harber

Last Updated:

Views: 6447

Rating: 4 / 5 (71 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Duane Harber

Birthday: 1999-10-17

Address: Apt. 404 9899 Magnolia Roads, Port Royceville, ID 78186

Phone: +186911129794335

Job: Human Hospitality Planner

Hobby: Listening to music, Orienteering, Knapping, Dance, Mountain biking, Fishing, Pottery

Introduction: My name is Duane Harber, I am a modern, clever, handsome, fair, agreeable, inexpensive, beautiful person who loves writing and wants to share my knowledge and understanding with you.