如果字段的值为空,那么如何将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.6+中的所有模型,请使用:

mapper.setSerializationInclusion(JsonInclude.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;
    }

}

就我而言

@JsonInclude(Include.NON_EMPTY)

让它发挥作用。

这已经困扰了我一段时间,我终于找到了问题所在。问题是由于错误的导入。早些时候我一直在使用

com.fasterxml.jackson.databind.annotation.JsonSerialize

已被弃用。只需将导入替换为

import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

并将其用作

@JsonSerialize(include=Inclusion.NON_NULL)

如果在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对象映射器

Jackson 2.x+使用

mapper.getSerializationConfig().withSerializationInclusion(JsonInclude.Include.NON_NULL);