Close

Jackson JSON - @JsonInclude NON_EMPTY Example

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

@JsonInclude(NON_EMPTY) can be used to exclude values that are empty. Following values are considered to be empty:

  • Null values as defined by JsonInclude.Include NON_NULL (tutorial).
  • 'Absent' values as defined by JsonInclude.Include NON_ABSENT (tutorial).
  • For Collections and Maps, if method isEmpty() returns true.
  • For Java arrays, if length=0.
  • For String if Strings.length() returns 0.

Example

Java Object

package com.logicbig.example;

import com.fasterxml.jackson.annotation.JsonInclude;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Employee {
  private String name;
  private String dept;
  private String address;
  private List<String> phones;
  private AtomicReference<BigDecimal> salary;
    .............
}

Main class

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      Employee employee = new Employee();
      employee.setName("Trish");
      employee.setDept("");
      employee.setAddress(null);
      employee.setPhones(new ArrayList<>());
      employee.setSalary(new AtomicReference<>());

      ObjectMapper om = new ObjectMapper();
      String jsonString = om.writeValueAsString(employee);
      System.out.println(jsonString);
  }
}
{"name":"Trish"}

Without NON_EMPTY

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

{"name":"Trish","dept":"","address":null,"phones":[],"salary":null}

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

{"name":"Trish","dept":"","phones":[],"salary":null}

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

{"name":"Trish","dept":"","phones":[]}

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_EMPTY Example Select All Download
  • jackson-json-include-non-empty
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Employee.java

    See Also