Nikitin
Nikitin

Reputation: 269

How to tell Jackson to ignore a Boolean if it is null/false?

I have class

@Data
public class MyClass {
  private Boolean flag;
}

And want to convert it to XML. However I need to ignore flag field during serialization if flag is not true.

So if flag=true, I want to get:

<MyClass><flag>true</flag></MyClass>

Otherwise(if flag==null or flag==false), I want to get:

<MyClass></MyClass>

How can I do it?

I tried @JsonInclude(JsonInclude.Include.NON_NULL), but it works only for null values.

Upvotes: 3

Views: 4821

Answers (1)

pirho
pirho

Reputation: 12245

A generic solution would be to use JsonInclude.Include.CUSTOM like:

@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = TrueFilter.class)
private Boolean flag;

where TrueFilter would be like:

public static class TrueFilter {
    @Override
    public boolean equals(Object value) {
        return !Boolean.valueOf(true).equals(value);
    }
}

Also not so generic solution but if you need only to handle field flag you could try to override the getter with NON_NULL so like:

@Data
public class MyClass {
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Boolean flag;

    public Boolean getFlag() {
        return (flag != null && flag) ? true : null;
    }
}

Upvotes: 2

Related Questions