The Jackson @JsonInclude annotation can be used to exclude the properties or fields of a class under certain conditions and it can be defined using the JsonInclude.Include enum. The JsonInclude.Include enum contains few constants like "ALWAYS", "NON_DEFAULT", "NON_EMPTY" and "NON_NULL" to determine whether to exclude the property(field) or not.
Syntax
public static enum JsonInclude.Include extends Enum<JSonInclude.Include>
Example
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import java.io.*;
public class JsonIncludeTest {
public static void main(String args[]) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Employee emp = new Employee();
String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
System.out.println(jsonString);
}
}
// Employee class
@JsonInclude(JsonInclude.Include.NON_EMPTY)
class Employee {
public int empId = 115;
public String empName = null;
@Override
public String toString() {
return "Employee{" +
"empId=" + empId +
", empName='" + empName + '\'' +
'}';
}
}Output
{
"empId" : 115
}