Let's say I have an object:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Foods {
public Foods() {}
@Id
@JsonProperty
private String id;
@JsonProperty
private String name;
@JsonProperty
private Double calories;
@JsonProperty
private boolean sweet;
}
Now, in my Spring REST API call, I only populate the "name" field for the food and return it.
I get this as the return JSON:
{
"name": "Strawberry Pies",
"sweet": false
}
You can see that because the calories is not populated, the JSON doesn't return it. The "sweet" field I guess gets populated because the default value for boolean is false.
I do not however want the JSON string to return the "sweet" boolean of false if it was not populated in the first place. Is there a way to do this?
NON_NULLmeans, well, "Do not inludenullvalues". IfString-valued fields are not initialized, they will benulls. Butbooleanis primitive type, for which nulls are never used:falseis notnull. If you do want it to be excluded, you can make "sweet" to be of typeBoolean(that is,java.lang.Boolean), wrapper that does allownulls as well. Or, like another answer suggested, just useNON_DEFAULT.