Java JsonInclude-class And Method Code Example


Here is an example of using the JsonInclude annotation from the Apache Commons IO library to specify the conditions under which a field should be included in the serialization of an object to JSON:

import org.apache.commons.io.output.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

public class MyClass {
    @JsonInclude(Include.NON_NULL)
    private String field1;
    @JsonInclude(Include.NON_EMPTY)
    private String field2;
    private String field3;

    public MyClass(String field1, String field2, String field3) {
        this.field1 = field1;
        this.field2 = field2;
        this.field3 = field3;
    }
    
    public String getField1() {
        return field1;
    }
    
    public String getField2() {
        return field2;
    }
    
    public String getField3() {
        return field3;
    }
}

In this example, the field1 and field2 are annotated with @JsonInclude.

The field1 annotated with Include.NON_NULL will only be included in the serialization if its value is not null.

The field2 annotated with Include.NON_EMPTY will only be included in the serialization if its value is not empty(it's not null and it's length greater than 0).

The field3 will be included in the serialization always.

Make sure that you are using jackson as serializer.