Search code examples
javabuilderlombok

How can I exclude a property from a lombok builder only if the property is null


I have a user model class that looks like:

@JsonSerialize
@Getter
@Setter
@FieldDefaults(level = AccessLevel.PRIVATE)
@Builder
public class User {
    @Default
    String _dn = BASE_USER_DN;
    @Default
    String[] objectClass = {"top", "person", "organizationalPerson", "inetOrgPerson", "companyUser"};
    @Default
    String[] cn = {"user205"};
    @Default
    String[] sn = {"Dynamic2"};
    @Default
    String[] username = {"LindaDynamic2"};
}

Now I'd like to generate a user object that omits null fields so:

userBody = User.builder().cn(null).build();

would create an object without a cn property or if I added a field without a default and it wasn't set on the builder it would be omitted.

Is this possible?


Solution

  • Add following annotation if you want to exclude during serialization:

    @JsonInclude(Include.NON_NULL)