如何删除由杰克逊自定义序列化器生成的空值? [英] How to remove null values generated by a jackson custom serializer?
问题描述
提供以下课程:
@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
.
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
.
一切正常,但计算出的值有时可以为null,这是正常的,而我最终得到一个像这样的json:
Everything works as expected BUT the computed value can sometimes be null, which is normal, and I end up with a json like this:
{
[... All properties],
"activeContract": null
}
问题是我不希望将空属性包含在返回的json中,当自定义时,忽略 @JsonInclude(JsonInclude.Include.NON_EMPTY)
序列化程序是在属性上设置的.
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.
深入研究后,我发现自定义序列化程序由 BeanPropertyWriter.serializeAsField()
调用,其中包含:
After digging a bit, I found out that the custom serializer is called by BeanPropertyWriter.serializeAsField()
that contains:
if (value == null) {
if (_nullSerializer != null) {
gen.writeFieldName(_name);
_nullSerializer.serialize(null, gen, prov);
}
return;
}
因此,在实际调用自定义序列化程序之前,该字段的名称是由 gen.writeFieldName(_name);
编写的,我没有找到防止这种行为或删除该行为的正确方法自定义序列化程序生成的null属性.
So the name of the field is written by 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.
是否有适当的方法来实现这样的结果?任何建议都将非常受欢迎:D
Is there a proper way to achieve such a result ? Any advice would be very welcome :D
感谢< 3
推荐答案
如果您已经以全局或现场方式指定了 Include.NON_EMPTY
,则还必须覆盖 com.fasterxml.jackson.databind.JsonSerializer#isEmpty(com.fasterxml.jackson.databind.SerializerProvider,T)
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)
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;
}
}
这篇关于如何删除由杰克逊自定义序列化器生成的空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!