[英]How to remove null values generated by a jackson custom serializer?
Given the following 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;
}
Basically the property activeContract
is null, and its value is evaluated only when the correct @JsonView is provided, the value is computed by a Spring Spel expression, everything is done in a custom Serializer JacksonSpringSpelSerializer
.基本上,属性
activeContract
为空,并且仅在提供正确的 @JsonView 时才评估其值,该值由 Spring Spel 表达式计算,一切都在自定义 Serializer JacksonSpringSpelSerializer
。
Everything works as expected BUT the computed value can sometimes be null, which is normal, and I end up with a json like this:一切都按预期工作,但计算值有时可能为空,这是正常的,我最终得到这样的 json:
{
[... All properties],
"activeContract": null
}
The issue is that I don't want null properties to be in the returned json , the @JsonInclude(JsonInclude.Include.NON_EMPTY)
is ignored when a custom serializer is set on a property.问题是我不希望返回的 json 中包含 null 属性,当在属性上设置自定义序列化程序时,会忽略
@JsonInclude(JsonInclude.Include.NON_EMPTY)
。
After digging a bit, I found out that the custom serializer is called by BeanPropertyWriter.serializeAsField()
that contains:经过一番挖掘,我发现自定义序列化程序由
BeanPropertyWriter.serializeAsField()
调用,其中包含:
if (value == null) {
if (_nullSerializer != null) {
gen.writeFieldName(_name);
_nullSerializer.serialize(null, gen, prov);
}
return;
}
So the name of the field is written by gen.writeFieldName(_name);
所以字段名写成
gen.writeFieldName(_name);
before the custom serializer is actually called, and I didn't find a proper way to prevent this behavior or to remove the null properties generated by the custom Serializer.在实际调用自定义序列化程序之前,我没有找到防止这种行为或删除自定义序列化程序生成的空属性的正确方法。
Is there a proper way to achieve such a result ?有没有合适的方法来达到这样的结果? Any advice would be very welcome :D
非常欢迎任何建议:D
Thanks <3谢谢 <3
你可以尝试使用JsonInclude.Include.NON_NULL
,就像下面的代码
@JsonInclude(JsonInclude.Include.NON_NULL)
If you already specified Include.NON_EMPTY
in some way either globally or on the field, you have to also override com.fasterxml.jackson.databind.JsonSerializer#isEmpty(com.fasterxml.jackson.databind.SerializerProvider, T)
如果您已经在全局或现场以某种方式指定了
Include.NON_EMPTY
,您还必须覆盖com.fasterxml.jackson.databind.JsonSerializer#isEmpty(com.fasterxml.jackson.databind.SerializerProvider, T)
static class Serializer extends JsonSerializer<Foo> {
@Override
public void serialize(Foo value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
// serialize
}
@Override
public boolean isEmpty(SerializerProvider provider, Foo value) {
// this will be called for Include.NON_EMPTY
boolean isItEmpty = // get it somehow
return isItEmpty;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.