如果字段的值为空,那么如何将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;
}
当前回答
您可以使用以下映射器配置:
mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
从2.5开始,您可以使用:
mapper.setSerializationInclusion(Include.NON_NULL);
其他回答
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
应该起作用。
Include.NON_EMPTY表示如果属性的值不为null且不为空,则该属性将被序列化。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)
案例一
@JsonInclude(JsonInclude.Include.NON_NULL)
private String someString;
案例二
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private String someString;
如果someString为空,则在这两种情况下都将忽略它。如果someString为“”,则只能在第二种情况下忽略。
对于List=null或List.size()=0也是如此
您可以使用以下映射器配置:
mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
从2.5开始,您可以使用:
mapper.setSerializationInclusion(Include.NON_NULL);