Search code examples
javajsonjavabeanspojo

Ignore a java bean field while converting into JSON Only if it's value hasn't been set


I have class ABCResponse and isActive is a member of the class. While converting the ABCResponse to JSON i wanna ignore the isActive field only if it's value hasn't been set explicitly. (isActive is boolean and i know by default its value will be false, but any possible way to ignore this if its value hasn't set explicitly?)

I can't use @JSONIgnore, coz it will ignore even it's value has been set.

public class ABCResponse {

private boolean isActive;
private int id;

@JsonProperty("isActive")
public boolean isActive() {
    return isActive;
}
public void setActive(boolean isActive) {
    this.isActive = isActive;
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}

}


Solution

  • Change it to the wrapper type Boolean so that it can be null, and use the following annotation at a class level: @JsonInclude(Include.NON_NULL) or @JsonInclude(JsonSerialize.Inclusion.NON_NULL) if you are using version 2.x+ of Jackson