如果字段的值为空,那么如何将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.x+使用

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

其他回答

您可以设置application.properties:

spring.jackson.default-property-inclusion=non_null

或application.yaml:

spring:
  jackson:
    default-property-inclusion: non_null

http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

这将适用于Spring boot 2.0.3+和Jackson 2.0+

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiDTO
{
    // your class variable and 
    // methods
}

如果在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.5使用:

@JsonInclude(content=Include.NON_NULL)

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

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)