如何告诉Jackson在序列化期间忽略值为null的字段?

858

Jackson如何配置,以在序列化期间忽略某个字段的值,如果该字段的值为null。

例如:

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; 
}
22个回答

5
如果您想将此规则添加到所有Jackson 2.6+模型中,请使用以下内容:
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

4

对于Jackson 2.5,请使用:

@JsonInclude(content=Include.NON_NULL)

3

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

}

设置serializationInclusion不会叠加。应该使用包含范围更大的枚举值。例如, NON_ABSENT 包括 NON_NULL ,NON_EMPTY 包括两者。因此,应该只使用 builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);JacksonInclude文档 - Olgun Kaya

3
如果你试图序列化一个对象列表,并且其中一个对象为空,即使使用`null`,最终在JSON中也会包含这个空对象。
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

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)

1
尝试这个 -
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class XYZ {
    
    protected String field1;
    
    protected String field2;
 }

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

@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)

1
案例一
@JsonInclude(JsonInclude.Include.NON_NULL)
private String someString;

案例二
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private String someString;

如果someString为null,则在两种情况下都会被忽略。 如果someString为"",则仅在第二种情况下被忽略。
对于List = nullList.size() = 0也是一样。

1
我们对这个问题有很多答案。在某些情况下,以下回答可能会有所帮助:如果您想忽略空值,可以在类级别使用 NOT_NULL,如下所示。
@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

有时候您可能需要忽略空值,比如初始化了ArrayList但是列表中没有元素。这时可以使用NOT_EMPTY注释来忽略那些空值字段。
@JsonInclude(Include.NON_EMPTY)
class Foo
{
  String bar;
}

0
在Jackson 2.0或更高版本中,@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)属性已被弃用,我们需要使用以下替代方法:
@JsonInclude(Include.NON_NULL)
public class MyClass

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接