[英]Jackson - treat empty collection as null during serialization to json
Suppose that I have the following POJO 假设我有以下POJO
public class Pojo {
private Set<String> stringSet = new HashSet<>();
}
When I do serialize it to the json, I've got the following output 当我将它序列化到json时,我得到了以下输出
{"stringSet":[]}
However, per requirements, I need the following: 但是,根据要求,我需要以下内容:
{"stringSet":null}
I have tried to implement the custom StdSerializer<Set>
我试图实现自定义StdSerializer<Set>
public class CustomStdSerializer extends StdSerializer<Set> {
protected CustomStdSerializer() {
super(Set.class);
}
@Override
public void serialize(Set set, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (set.size() == 0){
jsonGenerator.writeNull();
}
}
}
But the output of it is the following 但它的输出如下
{"stringSet":}
How can I write null value in json? 如何在json中写入null值?
I had the exact same requirement a while ago. 我刚才有完全相同的要求。
The reason why you get a [] stringSet is because during declaration itself you are doing new HashSet<>();
你得到一个[] stringSet的原因是因为在声明本身你正在做new HashSet<>();
and i am quite sure that in your setter method you might be simply doing 而且我很确定在你的setter方法中你可能只是在做
public void setStringSet(Set<String> stringSet){
this.stringSet = stringSet;
}
instead you could do 相反,你可以做到
public void setStringSet(Set<String> stringSet){
if(stringSet.isEmpty()){
this.stringSet.clear();
} else{
this.stringSet = stringSet;
}
}
and this just worked fine for me. 这对我来说很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.