@JsonInclude(Include.NON_EMPTY) 在使用 CUSTOM SERIALIZER 时不起作用

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

似乎当我使用自定义序列化程序时 @JsonInclude(Include.NON_NULL) 被完全忽略了。

我的要求是不序列化值为空的键。我还想通过为多值 SortedSet 添加 space 分隔符来格式化字符串(这就是我创建自定义序列化程序的原因)

没有任何空值的当前输出示例

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

具有空值的当前输出示例

{
  "age": "10",
  "fullName": "John Doe"
  "email":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;
}

自定义序列化程序

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));
    }

}

已解决:

我不得不在自定义序列化程序中重写 isEmpty 方法

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