Jackson and JSON in Java, finally learn with a coding-first approach:
>> Download the eBookMocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Overview
This tutorial will show how to ignore certain fields when serializing an object to JSON using Jackson 2.x.
This is very useful when the Jackson defaults arenβt enough and we need to control exactly what gets serialized to JSON β and there are several ways to ignore properties.
To dig deeper and learn other cool things we can do with Jackson, head on over to the main Jackson tutorial.
Further reading:
Intro to the Jackson ObjectMapper
Jackson Streaming API
Guide to @JsonFormat in Jackson
2. Ignore Fields at the Class Level
We can ignore specific fields at the class level, using the @JsonIgnoreProperties annotation and specifying the fields by name:
@JsonIgnoreProperties(value = { "intValue" })
public class MyDto {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDto() {
super();
}
// standard setters and getters are not shown
}
We can now test that, after the object is written to JSON, the field is indeed not part of the output:
@Test
public void givenFieldIsIgnoredByName_whenDtoIsSerialized_thenCorrect()
throws JsonParseException, IOException {
ObjectMapper mapper = new ObjectMapper();
MyDto dtoObject = new MyDto();
String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, not(containsString("intValue")));
}
3. Ignore Field at the Field Level
We can also ignore a field directly via the @JsonIgnore annotation directly on the field:
public class MyDto {
private String stringValue;
@JsonIgnore
private int intValue;
private boolean booleanValue;
public MyDto() {
super();
}
// standard setters and getters are not shown
}
We can now test that the intValue field is indeed not part of the serialized JSON output:
@Test
public void givenFieldIsIgnoredDirectly_whenDtoIsSerialized_thenCorrect()
throws JsonParseException, IOException {
ObjectMapper mapper = new ObjectMapper();
MyDto dtoObject = new MyDto();
String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, not(containsString("intValue")));
}
4. Ignore All Fields by Type
Finally, we can ignore all fields of a specified type, using the @JsonIgnoreType annotation. If we control the type, then we can annotate the class directly:
@JsonIgnoreType
public class SomeType { ... }
More often than not, however, we donβt have control of the class itself. In this case, we can make good use of Jackson mixins.
First, we define a MixIn for the type weβd like to ignore and annotate that with @JsonIgnoreType instead:
@JsonIgnoreType
public class MyMixInForIgnoreType {}
Then we register that mixin to replace (and ignore) all String[] types during marshalling:
mapper.addMixInAnnotations(String[].class, MyMixInForIgnoreType.class);
At this point, all String arrays will be ignored instead of marshalled to JSON:
@Test
public final void givenFieldTypeIsIgnored_whenDtoIsSerialized_thenCorrect()
throws JsonParseException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(String[].class, MyMixInForIgnoreType.class);
MyDtoWithSpecialField dtoObject = new MyDtoWithSpecialField();
dtoObject.setBooleanValue(true);
String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
}
And here is our DTO:
public class MyDtoWithSpecialField {
private String[] stringValue;
private int intValue;
private boolean booleanValue;
}
Note: Since version 2.5, it seems that we canβt use this method to ignore primitive data types, but we can use it for custom data types and arrays.
5. Ignore Fields Using Filters
Finally, we can also use filters to ignore specific fields in Jackson.
First, we need to define the filter on the Java object:
@JsonFilter("myFilter")
public class MyDtoWithFilter { ... }
Then we define a simple filter that will ignore the intValue field:
SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter
.serializeAllExcept("intValue");
FilterProvider filters = new SimpleFilterProvider()
.addFilter("myFilter", theFilter);
Now we can serialize the object and make sure that the intValue field is not present in the JSON output:
@Test
public final void givenTypeHasFilterThatIgnoresFieldByName_whenDtoIsSerialized_thenCorrect()
throws JsonParseException, IOException {
ObjectMapper mapper = new ObjectMapper();
SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter
.serializeAllExcept("intValue");
FilterProvider filters = new SimpleFilterProvider()
.addFilter("myFilter", theFilter);
MyDtoWithFilter dtoObject = new MyDtoWithFilter();
String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject);
assertThat(dtoAsString, not(containsString("intValue")));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, containsString("stringValue"));
System.out.println(dtoAsString);
}
6. Conclusion
This article illustrated how to ignore fields on serialization. We did this first by name and then directly, and finally, we ignored the entire java type with MixIns and used filters for more control of the output.
