如果字段的值为空,那么如何将Jackson配置为在序列化期间忽略该字段值。

例如:

public class SomeClass {
   // what jackson annotation causes jackson to skip over this value if it is null but will 
   // serialize it otherwise 
   private String someValue; 
}

当前回答

要使用Jackson>2.0禁止使用空值序列化财产,可以直接配置ObjectMapper,或使用@JsonInclude注释:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

或者,您可以在getter中使用@JsonInclude,这样,如果值不为空,将显示属性。

在我对如何防止Map中的空值和bean中的空字段通过Jackson序列化的回答中,提供了一个更完整的示例。

其他回答

要使用Jackson>2.0禁止使用空值序列化财产,可以直接配置ObjectMapper,或使用@JsonInclude注释:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

或者,您可以在getter中使用@JsonInclude,这样,如果值不为空,将显示属性。

在我对如何防止Map中的空值和bean中的空字段通过Jackson序列化的回答中,提供了一个更完整的示例。

如果使用Spring,则为全局配置

@Configuration
public class JsonConfigurations {

    @Bean
    public Jackson2ObjectMapperBuilder objectMapperBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);
        builder.failOnUnknownProperties(false);
        return builder;
    }

}

这个问题我们有很多答案。这个答案在某些情况下可能有用如果要忽略空值,可以在类级别使用NOT_null。如下所示

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

有时您可能需要忽略空值,例如您可能已经初始化了arrayList,但该列表中没有元素

@JsonInclude(Include.NON_EMPTY)
class Foo
{
  String bar;
}

您可以使用以下映射器配置:

mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);

从2.5开始,您可以使用:

mapper.setSerializationInclusion(Include.NON_NULL);

对于Jackson>1.9.11和<2.x,请使用@JsonSerialize注释来实现:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)