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

当前回答

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

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

其他回答

对于Jackson 2.5使用:

@JsonInclude(content=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;
    }

}

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

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

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

试试这个-

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class XYZ {
    
    protected String field1;
    
    protected String field2;
 }

对于非空值(在getter/class级别)-

@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)