如果字段的值为空,那么如何将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配置为在序列化期间忽略该字段值。
例如:
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.x+使用
mapper.getSerializationConfig().withSerializationInclusion(JsonInclude.Include.NON_NULL);
对于Jackson>1.9.11和<2.x,请使用@JsonSerialize注释来实现:
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
案例一
@JsonInclude(JsonInclude.Include.NON_NULL)
private String someString;
案例二
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private String someString;
如果someString为空,则在这两种情况下都将忽略它。如果someString为“”,则只能在第二种情况下忽略。
对于List=null或List.size()=0也是如此
如果您试图序列化一个对象列表,其中一个对象为空,那么即使使用
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
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
应该起作用。
Include.NON_EMPTY表示如果属性的值不为null且不为空,则该属性将被序列化。Include.NON_NULL表示如果属性的值不为空,则该属性被序列化。