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

问题描述 投票:1回答:1

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

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

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

{
  "age": "10",
  "fullName": "John Doe"
  "email":"[email protected] [email protected] [email protected]"
}

具有空值的当前输出示例

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

}
java json java-11 jsonserializer
1个回答
2
投票

解决了:

我不得不在自定义序列化器中覆盖isEmpty方法

@Override
public boolean isEmpty(SerializerProvider provider, Collection value) {
    return (value == null || value.size() == 0);
}
© www.soinside.com 2019 - 2024. All rights reserved.