Exclude 0 from JSON response in Jackson Spring boot

I have a POJO like this.

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Test {

    private int a;

    private String b;
}

I want to exclude the property 'a' if it has 0 value. String b is excluded with

@JsonInclude(JsonInclude.Include.NON_NULL)

Only way I could thing of is convert the int data type to Integer Object and set the value to NULL in the setter explicitly if it is 0.

Any other suggestions or correct solution will be appreciated

Upvotes: 1

Views: 6018

Answers (1)

hjoeren
hjoeren

Reputation: 589

Option 1:

Do what you said: Change int to Integer and use @JsonInclude(Include.NON_NULL). Because primitive types have default values and their values cannot be compared to null you have to wrap the int to Integer. See Primitive Data Types. imho this is the cleaner way.

Option 2:

Use the way described in this answer and use @JsonInclude(Include.NON_DEFAULT) instead (see Jackson-annotations API), so that default values (and so also null values for objects) will be ignored.


Note:

If you only want to exclude the specific field (in your case the int/Integer - a - field) when it has a null-/default value and the other fields (in your case the String - b - field) should be included when they have null-/default values, put the annotation on field level.

Upvotes: 2

Related Questions