假设我有以下 POJO
public class Pojo {
private Set<String> stringSet = new HashSet<>();
}
当我将其序列化为 json 时,我得到以下输出
{"stringSet":[]}
但是,根据要求,我需要以下内容:
{"stringSet":null}
我尝试实现自定义 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();
}
}
}
但是它的输出如下
{"stringSet":}
如何在 json 中写入 null 值?
最佳答案
不久前我也有同样的需求。
你得到一个 [] stringSet 的原因是因为在声明本身期间你正在做 new HashSet<>();
我很确定在你的 setter 方法中你可能只是在做
public void setStringSet(Set<String> stringSet){
this.stringSet = stringSet;
}
相反,你可以这样做
public void setStringSet(Set<String> stringSet){
if(stringSet.isEmpty()){
this.stringSet.clear();
} else{
this.stringSet = stringSet;
}
}
这对我来说效果很好。
关于java - Jackson - 在序列化为 json 期间将空集合视为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40773265/