我有一个相当有趣的问题,试图让Jackson在自定义序列化程序类创建时,从生成的JSON中正确删除空字段。我已经彻底搜索了有关Serializer和SerializationInclusion配置的信息,但我还没有发现任何似乎可以解释我所看到的内容。
我有一个Jackson对象映射器,通过Spring配置并自动装配。对象映射器配置和POJO(为简洁起见编辑)看起来或多或少类似于下面的代码。
出于某种原因,当我调用我们的REST端点来获取包含上述示例值的Bar对象时,我看到以下行为:
我的想法是,在Jackson已经从JSON中删除了所有空值和空值之后调用了Serializer逻辑,因此“foo”属性被正确设置为null,但由于包含逻辑已经删除,因此未被删除已经执行了。
有没有人对这里发生的事情有任何想法?这是在版本2.2.2中如何实现Jackson-databind库的一个怪癖吗?
Jackson Config -
@Bean
public JacksonObjectMapper jacksonMapper() {
final JacksonObjectMapper mapper = new JacksonObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
mapper.registerModule(agJacksonModule());
return mapper;
}
@Bean
public SimpleModule agJacksonModule() {
final SimpleModule module = new SimpleModule();
module.addSerializer(Foo.class, new FooSerializer());
return module;
}
自定义序列化程序 -
public class FooSerializer extends JsonSerializer<Foo> {
@Override
public void serialize(Sponsor sponsor, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
// write null value for sponsor json property, if sponsor object has all empty or null fields
if(sponsor == null || isObjectEmpty(sponsor)) {
jsonGenerator.writeNull();
return;
}
// write out object
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("imgUrl", sponsor.getImgUrl());
jsonGenerator.writeStringField("clickUrl", sponsor.getClickUrl());
jsonGenerator.writeStringField("sponsorName", sponsor.getSponsorName());
jsonGenerator.writeStringField("sponsorText", sponsor.getSponsorText());
jsonGenerator.writeEndObject();
}
private boolean isObjectEmpty(Sponsor sponsor) {
return Strings.isNullOrEmpty(sponsor.getClickUrl())
&& Strings.isNullOrEmpty(sponsor.getImgUrl())
&& Strings.isNullOrEmpty(sponsor.getSponsorName())
&& Strings.isNullOrEmpty(sponsor.getSponsorText());
}
}
对象模型看起来像这样(为简洁起见,再次编辑,样本值在类成员上设置为示例数据):
Bar POJO -
public abstract class Bar {
protected Foo foo = aFoo;
protected String name = "";
protected ArrayList aList = Lists.newArrayList();
protected String objId = null;
// some getters and setters for the above properties
}
Foo POJO -
public abstract class Foo {
protected String aString = "";
protected String bString = "";
protected String cString = "";
protected String dString = "";
// some getters and setters for the above properties
}
答案 0 :(得分:0)
覆盖并实现JsonSerializer的isEmpty方法以实现您想要的效果。
对于什么是emptymeans的自定义定义,您的JsonSerializer实现需要覆盖此方法:
public boolean isEmpty(SerializerProvider provider, T value);
请注意,调用者在写入字段名称时必须处理过滤;只有在需要实际序列化时才会调用序列化程序。