Reputation: 7058
I want to exculde some default properties from serialization. I have the following class
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
@JsonInclude(Include.NON_DEFAULT)
@Builder
public class RunTime
{
@JsonProperty
@Builder.Default
private String mystring = "any";
@JsonProperty
@Builder.Default
private Boolean myboolean = true;
@JsonProperty
@JsonInclude(Include.ALWAYS)
@Builder.Default
private Boolean always = true;
}
Additionally I wrote this test:
@Test
public void test() throws JsonProcessingException
{
RunTime rac = RunTime.builder().build();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rac);
assertThat(json).doesNotContain("mystring");
assertThat(json).doesNotContain("myboolean");
assertThat(json).contains("always");
}
I only want to include the boolean always
property in the json string. Unfortunately, the test is failing as every property is included. However, I noticed all this is working fine when I remove the Lombok builder and instantiate the object by myself. How can I get this working with Lombok?
Upvotes: 4
Views: 5921
Reputation: 96
I am not sure if you found an answer for this but I have determined WHY it doesn't work.
If youre interested in the process I went ahead and delomboked the source with a builder and @Builder.Default.
java -jar lombok.jar delombok -p someFile.java
It seems that a field variable with a default setter
@Builder.Default String someValue = "defaultVar"
effectively turns into
String someValue;
@java.lang.SuppressWarnings("all")
private static Optional<String> $default$someValue() {
return "defaultVar";
}
Meaning Lombok is doing some hacky thing where it pulls the instantiation from the field variable itself into the build() call of the Builder. It does a check if the "staged" value in the builder is set and if not calls $default$someValue()
to get that default value.
This means the jackson serialization will fail to set your specified default properties. It should call the default constructor of your main class and effectively set those values to null.
A little unfortunate and I am hoping the lombok team is aware of this, but you will need to create your own AllArgsConstructor or your NoArgsConstructor that sets the default values explicitly.
Upvotes: 8