如果字段的值为空,那么如何将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>1.9.11和<2.x,请使用@JsonSerialize注释来实现:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

其他回答

如果您试图序列化一个对象列表,其中一个对象为空,那么即使使用

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

将导致:

[{myObject},null]

要获取此信息:

[{myObject}]

可以执行以下操作:

mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
        @Override
        public void serialize(Object obj, JsonGenerator jsonGen, SerializerProvider unused)
                throws IOException
        {
            //IGNORES NULL VALUES!
        }
    });

提示:如果您使用的是DropWizard,则可以使用environment.getObjectMapper()检索Jersey正在使用的ObjectMapper

这将适用于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
}

您可以设置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

只是为了扩展其他答案-如果您需要控制每个字段中空值的省略,请注释有问题的字段(或者注释字段的“getter”)。

示例-这里只有fieldOne如果为空,将从JSON中省略。fieldTwo将始终包含在JSON中,无论它是否为空。

public class Foo {

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

    private String fieldTwo;
}

要忽略类中的所有空值作为默认值,请注释该类。如果需要,Per-field/getter注释仍然可以用于覆盖此默认值。

示例-如果fieldOne和fieldTwo分别为空,则它们将从JSON中省略,因为这是类注释的默认设置。然而,fieldThree将覆盖默认值,并将始终包含在内,因为字段上有注释。

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Foo {

    private String fieldOne;

    private String fieldTwo;
    
    @JsonInclude(JsonInclude.Include.ALWAYS)
    private String fieldThree;
}

更新

以上是《杰克逊2》。对于早期版本的Jackson,您需要使用:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) 

而不是

@JsonInclude(JsonInclude.Include.NON_NULL)

如果这个更新有用,请在下面投票支持ZiglioUK的答案,它早在我更新答案使用它之前就指出了更新的Jackson 2注释!

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

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)