gpt4 book ai didi

java - 使用 CUSTOM SERIALIZER 时 @JsonInclude(Ininclude.NON_EMPTY) 不起作用

转载 作者:行者123 更新时间:2023-11-30 01:54:29 26 4
gpt4 key购买 nike

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

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

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

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

关于java - 使用 CUSTOM SERIALIZER 时 @JsonInclude(Ininclude.NON_EMPTY) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54933963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com