Search code examples
javajsonjava-11jsonserializer

@JsonInclude(Include.NON_EMPTY) is not working while using CUSTOM SERIALIZER


It seems like when I use custom serializers then @JsonInclude(Include.NON_NULL) is ignored completely.

My requirement is to not serialize keys for which values are null. I also want to format the string by adding space separators for a multivalued SortedSet (that's why I created a custom serializer)

Example of current output without any null values

{
  "age": "10",
  "fullName": "John Doe"
  "email":"doe@john.com john@doe.com test@gmail.com"
}

Example of current output with the null value

{
  "age": "10",
  "fullName": "John Doe"
  "email":null
}

Expected output when email is null:

{
  "age": "10",
  "fullName": "John Doe"
}

DTO

@AllArgsConstructor
@Builder
@Data
@NoArgsConstructor
@ToString
@SuppressWarnings("PMD.TooManyFields")
public class User {
    @JsonProperty("age")
    private String age;

    @JsonProperty("firstName")
    private String name;

    @JsonProperty("email")
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @JsonSerialize(using = MultiValuedCollectionSerializer.class)
    private SortedSet<String> email;
}

Custom Serializer

public class MultiValuedCollectionSerializer extends JsonSerializer<Collection> {

    @Override
    public void serialize(final Collection inputCollection, 
                          final JsonGenerator jsonGenerator, 
                          final SerializerProvider serializers) throws IOException {

        jsonGenerator.writeObject(Optional.ofNullable(inputCollection)
                .filter(input -> !input.isEmpty())
                .map(collection -> String.join(" ", collection))
                .orElse(null));
    }

}

Solution

  • Solved:

    I had to Override isEmpty method in my Custom Serializer

    @Override
    public boolean isEmpty(SerializerProvider provider, Collection value) {
        return (value == null || value.size() == 0);
    }