给定以下类(class):
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Account {
[... A lot of serialized properties]
@JsonSerialize(nullsUsing = JacksonSpringSpelSerializer.class, using = JacksonSpringSpelSerializer.class)
@JsonView(View.Contract.class)
@Value("#{@contractService.getActiveContract(#this)}")
public Contract activeContract;
}
基本上是属性activeContract
为 null,仅当提供正确的 @JsonView 时才计算其值,该值由 Spring Spel 表达式计算,一切都在自定义序列化器中完成 JacksonSpringSpelSerializer
.
一切都按预期工作,但计算值有时可能为空,这是正常的,我最终得到一个像这样的 json:
{
[... All properties],
"activeContract": null
}
问题是我不希望返回的 json 中包含 null 属性,即 @JsonInclude(JsonInclude.Include.NON_EMPTY)
在属性上设置自定义序列化程序时将被忽略。
经过一番挖掘,我发现自定义序列化器是由 BeanPropertyWriter.serializeAsField()
调用的。其中包含:
if (value == null) {
if (_nullSerializer != null) {
gen.writeFieldName(_name);
_nullSerializer.serialize(null, gen, prov);
}
return;
}
所以字段名写为gen.writeFieldName(_name);
在实际调用自定义序列化程序之前,我没有找到适当的方法来防止这种行为或删除自定义序列化程序生成的 null 属性。
有没有正确的方法可以达到这样的结果?非常欢迎任何建议:D
谢谢<3
最佳答案
您可以尝试使用JsonInclude.Include.NON_NULL
,如以下代码
@JsonInclude(JsonInclude.Include.NON_NULL)
关于java - 如何删除 Jackson 自定义序列化程序生成的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60449681/