I'm having a class that has a default value which is true
and I want to ignore the default in serialization. It works when the default is false
, but not when the default is true
:
public static final class TestBooleanDefaultTrue {
@JsonInclude(Include.NON_DEFAULT)
@JsonProperty(value="display")
public Boolean display = Boolean.TRUE;
public String s = "test";
public TestBooleanDefaultTrue() {}
}
public static final class TestBooleanDefaultFalse {
@JsonInclude(Include.NON_DEFAULT)
@JsonProperty(value="display")
public Boolean display = Boolean.FALSE;
public String s = "test";
public TestBooleanDefaultFalse() {}
}
@Test
public void readBVMTest() throws JsonGenerationException, JsonMappingException, IOException {
testom.writeValue(System.out, new TestBooleanDefaultTrue());
testom.writeValue(System.out, new TestBooleanDefaultFalse());
}
which outputs (after cheating a bit):
{"s":"test","display":true}
{"s":"test"}
How can I ignore the default value when it is true
?
You can use a custom filter, because the NON_DEFAULT
does not consider what you assign, but the default value of the wrapper type.
public static final class MyFilter {
@Override
public boolean equals(final Object obj) {
if (obj == null || !(obj instanceof Boolean)) {
return false;
}
// date should be in the past
final Boolean v = (Boolean) obj;
return Boolean.TRUE.equals(v);
}
}
public static final class TestBooleanDefaultTrue {
@JsonInclude(value = Include.CUSTOM, valueFilter = MyFilter.class)
@JsonProperty(value = "display")
public Boolean display = Boolean.TRUE;
public String s = "test";
public TestBooleanDefaultTrue() {
}
}
public static final class TestBooleanDefaultFalse {
@JsonInclude(Include.NON_DEFAULT)
@JsonProperty(value = "display")
public Boolean display = Boolean.FALSE;
public String s = "test";
public TestBooleanDefaultFalse() {
}
}
@Test
public void readBVMTest() throws JsonGenerationException, JsonMappingException, IOException {
assertEquals(getOM().writeValueAsString(new TestBooleanDefaultTrue()), "{\"s\":\"test\"}");
assertEquals(getOM().writeValueAsString(new TestBooleanDefaultFalse()), "{\"s\":\"test\"}");
}
EDIT for completeness from the javadoc of JsonInclude.Include.NON_DEFAULT
, emphasis mine:
When NOT used for a POJO (that is, as a global default, or as property override), definition is such that: All values considered "empty" (as per NON_EMPTY) are excluded, Primitive/wrapper default values are excluded, Date/time values that have timestamp (
long
value of milliseconds since epoch, see Date) of0L
are excluded