如果字段的值为空,那么如何将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; 
}

当前回答

如果在Spring Boot中,您可以直接通过属性文件自定义jackson ObjectMapper。

示例application.yml:

spring:
  jackson:
    default-property-inclusion: non_null # only include props if non-null

可能的值包括:

always|non_null|non_absent|non_default|non_empty

更多信息:https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-自定义jackson对象映射器

其他回答

就我而言

@JsonInclude(Include.NON_EMPTY)

让它发挥作用。

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonInclude(JsonInclude.Include.NON_EMPTY)

应该起作用。

Include.NON_EMPTY表示如果属性的值不为null且不为空,则该属性将被序列化。Include.NON_NULL表示如果属性的值不为空,则该属性被序列化。

如果使用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;
}

案例一

@JsonInclude(JsonInclude.Include.NON_NULL)
private String someString;

案例二

@JsonInclude(JsonInclude.Include.NON_EMPTY)
private String someString;

如果someString为空,则在这两种情况下都将忽略它。如果someString为“”,则只能在第二种情况下忽略。

对于List=null或List.size()=0也是如此