Ignore Null Fields with Jackson

1. Overview

This quick tutorial is going to cover how to set up Jackson to ignore null fields when serializing a java class.

If we want to dig deeper and learn other cool things to do with the Jackson 2, we can head on over to the main Jackson tutorial.

2. Ignore Null Fields on the Class

Jackson allow us to control this behavior at either the class level:

@JsonInclude(Include.NON_NULL)
public class MyDto { ... }

Or with more granularity at the field level:

public class MyDto {

    @JsonInclude(Include.NON_NULL)
    private String stringValue;

    private int intValue;

    // standard getters and setters
}

Now we should be able to test that null values are indeed not part of the final JSON output:

@Test
public void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored()
  throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    MyDto dtoObject = new MyDto();

    String dtoAsString = mapper.writeValueAsString(dtoObject);

    assertThat(dtoAsString, containsString("intValue"));
    assertThat(dtoAsString, not(containsString("stringValue")));
}

3. Ignore Null Fields Globally

Jackson also allows us to configure this behavior globally on the ObjectMapper:

mapper.setSerializationInclusion(Include.NON_NULL);

Now any null field in any class serialized through this mapper is going to be ignored:

@Test
public void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored() 
  throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    MyDto dtoObject = new MyDto();

    String dtoAsString = mapper.writeValueAsString(dtoObject);

    assertThat(dtoAsString, containsString("intValue"));
    assertThat(dtoAsString, containsString("booleanValue"));
    assertThat(dtoAsString, not(containsString("stringValue")));
}

4. Conclusion

Ignoring null fields is such a common Jackson configuration because it’s often the case that we need to have better control over the JSON output. This article demonstrates how to do that for classes. There are, however, more advanced use cases, such as ignoring null values when serializing a Map.

The implementation of all of these examples and code snippets can be found in the Github project.

Related posts:

Beans and Dependency Injection
Kiểu dữ liệu Ngày Giờ (Date Time) trong java
Introduction to Spring Data MongoDB
Java Program to Implement Gale Shapley Algorithm
Split a String in Java
Connect through a Proxy
Ép kiểu trong Java (Type casting)
Spring Webflux and CORS
Rest Web service: Filter và Interceptor với Jersey 2.x (P1)
Java Program to Implement Ternary Search Tree
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular
Java InputStream to Byte Array and ByteBuffer
Composition, Aggregation, and Association in Java
Spring Cloud – Tracing Services with Zipkin
Java Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity
Java Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
Tổng quan về ngôn ngữ lập trình java
Phương thức forEach() trong java 8
Java Program to Implement LinkedBlockingQueue API
Spring Boot: Customize the Jackson ObjectMapper
Java Program to Implement Bresenham Line Algorithm
JUnit5 Programmatic Extension Registration with @RegisterExtension
Java Program to Check whether Graph is a Bipartite using BFS
Java Program to Convert a Decimal Number to Binary Number using Stacks
Java Program to Perform Searching in a 2-Dimension K-D Tree
Introduction to Using Thymeleaf in Spring
Java Byte Array to InputStream
HttpClient with SSL
Java Program to Perform Naive String Matching
Java Program to Delete a Particular Node in a Tree Without Using Recursion
Spring Security Custom AuthenticationFailureHandler
Java Program to Implement WeakHashMap API