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

当前回答

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

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)

其他回答

如果您想将此规则添加到Jackson 2.6+中的所有模型,请使用:

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

要使用Jackson>2.0禁止使用空值序列化财产,可以直接配置ObjectMapper,或使用@JsonInclude注释:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

或者,您可以在getter中使用@JsonInclude,这样,如果值不为空,将显示属性。

在我对如何防止Map中的空值和bean中的空字段通过Jackson序列化的回答中,提供了一个更完整的示例。

试试这个-

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

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

@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)

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

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

您可以使用以下映射器配置:

mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);

从2.5开始,您可以使用:

mapper.setSerializationInclusion(Include.NON_NULL);