In REST API development, there will be cases in which we want to skip (ignore) certain fields in JSON response. In such cases, we can use the @JsonIgnore annotation if your project is using Java/Spring with FasterXML’s Jackson library. This annotation can be used at field level or method level.

Given the following entity/DTO class:

public class Location {

	private String code;
	
	@JsonProperty("region_name")
	private String regionName;
	
	@JsonProperty("country_code")
	private String countryCode;
	
	@JsonProperty("country_name")
	private String countryName;

	@JsonProperty("city_name")
	private String cityName;

	private boolean enabled;
	
	private boolean trashed;
	
	
	// getters and setters are not shown for brevity
	
}
An API call may produce the following JSON document in the response body:

{
  "code": "DN_VN",
  "enabled": true,
  "trashed": false,
  "region_name": "Da Nang",
  "country_code": "VN",
  "country_name": "Viet Nam",
  "city_name": "Da Nang"
}
Now, we want that the fields enabled and trashed should not be in the response. So we can use the @JsonIgnore annotation at field level as shown below:

public class Location {

	private String code;
	
	// other fields not shown

	@JsonIgnore
	private boolean enabled;

	@JsonIgnore	
	private boolean trashed;
	
	
	// getters and setters are not shown for brevity
	
}
Then the JSON in the response will be updated with those two fields ignored:

{
  "code": "DN_VN",
  "region_name": "Da Nang",
  "country_code": "VN",
  "country_name": "Viet Nam",
  "city_name": "Da Nang"
}
Note that you can also use the @JsonIgnore at method level - annotating getter or setter will both work. For example:

@JsonIgnore
public void setEnabled(boolean enabled) {
	this.enabled = enabled;
}

@JsonIgnore
public boolean isTrashed() {
	return trashed;
}
Also note that the @JsonIgnore annotation has an optional boolean argument that defines whether the annotation is activate or not (default is true). That means if you want to deactivate the annotation you can specify the argument false like this:

@JsonIgnore(false)
private boolean enabled;
This can be useful in case we want to disable the annotation temporarily and come back to use later.

Those are some examples of using @JsonIgnore annotation to skip/ignore fields in JSON response in Java/Spring project that uses Jackson library. I hope you find this short post helpful. You can also watch the following video to see how I use this annotation in a real life project:



 

Reference:

                Annotation type JsonIgnore

 

Related REST API Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.