Close

Jackson JSON - @JsonInclude USE_DEFAULTS Example

[Last Updated: Aug 11, 2020]

USE_DEFAULTS of JsonInclude.Include#value is specified so that the higher-level defaults can be used. If this option is used on property, @JsonInclude settings of the class, if exits, will be used, otherwise, global serialization inclusion rules (set with ObjectMapper) will be used.

Example

Java Object

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Employee {
  private String name;
  private String dept;
  private Integer salary;
  private boolean fullTime;
  @JsonInclude(JsonInclude.Include.NON_NULL)
  private List<String> phones;
  private Date dateOfBirth;
  ....

  @JsonInclude(JsonInclude.Include.USE_DEFAULTS)
  public List<String> getPhones() {
      return phones;
  }
  ....
}

Main class

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      Employee employee = new Employee();
      employee.setName("Trish");
      employee.setFullTime(false);
      employee.setPhones(new ArrayList<>());
      employee.setSalary(Integer.valueOf(2000));
      employee.setDateOfBirth(null);

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

As in above output 'phones' was not serialized, NON_NULL (on the field level) was ignored and class level NON_EMPTY option was used. Let's remove @JsonInclude on the phones' getter method:

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Employee {
  private String name;
  private String dept;
  private Integer salary;
  private boolean fullTime;
  @JsonInclude(JsonInclude.Include.NON_NULL)
  private List<String> phones;
  private Date dateOfBirth;
  ....
  
  public List<String> getPhones() {
      return phones;
  }
  ....
}

And run the main class:

{"name":"Trish","salary":2000,"fullTime":false,"phones":[]}

This time 'phones' was included because it is non-null. The setting @JsonInclude(JsonInclude.Include.USE_DEFAULTS) on 'phones' property in the second last example works as expected.

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

    See Also