Close

Jackson JSON - @JsonInclude NON_ABSENT Example

[Updated: Jun 29, 2018, Created: Jun 29, 2018]

@JsonInclude(NON_ABSENT) can be used to exclude null values and values that are "absent". Here absent value means a non-null referential type value (e.g. java.utl.concurrent.atomic.AtomicReference) that references a null value.

Example

Java Object

@JsonInclude(JsonInclude.Include.NON_ABSENT)
public class Employee {
  private String name;
  private String dept;
  private AtomicReference<String> address;
    .............
}

Main class

package com.logicbig.example;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      Employee employee = Employee.of("Trish", null, new AtomicReference<>());
      ObjectMapper om = new ObjectMapper();
      String jsonString = om.writeValueAsString(employee);
      System.out.println(jsonString);
  }
}
{"name":"Trish"}

Without NON_ABSENT

If we don't use @JsonInclude at all then output of the above example will be:

{"name":"Trish","dept":null,"address":null}

If we use @JsonInclude(JsonInclude.Include.NON_NULL) then output will be:

{"name":"Trish","address":null}

Example Project

Dependencies and Technologies Used:

  • jackson-databind 2.9.6: General data-binding functionality for Jackson: works on core streaming API.
  • JDK 10
  • Maven 3.5.4

@JsonInclude NON_ABSENT Example Select All Download
  • jackson-json-include-non-absent
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Employee.java

    See Also