如果字段的值为空,那么如何将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;
}
当前回答
这个问题我们有很多答案。这个答案在某些情况下可能有用如果要忽略空值,可以在类级别使用NOT_null。如下所示
@JsonInclude(Include.NON_NULL)
class Foo
{
String bar;
}
有时您可能需要忽略空值,例如您可能已经初始化了arrayList,但该列表中没有元素
@JsonInclude(Include.NON_EMPTY)
class Foo
{
String bar;
}
其他回答
如果您试图序列化一个对象列表,其中一个对象为空,那么即使使用
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
如果在Spring Boot中,您可以直接通过属性文件自定义jackson ObjectMapper。
示例application.yml:
spring:
jackson:
default-property-inclusion: non_null # only include props if non-null
可能的值包括:
always|non_null|non_absent|non_default|non_empty
更多信息:https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-自定义jackson对象映射器
您可以设置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.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
从2.5开始,您可以使用:
mapper.setSerializationInclusion(Include.NON_NULL);
这个问题我们有很多答案。这个答案在某些情况下可能有用如果要忽略空值,可以在类级别使用NOT_null。如下所示
@JsonInclude(Include.NON_NULL)
class Foo
{
String bar;
}
有时您可能需要忽略空值,例如您可能已经初始化了arrayList,但该列表中没有元素
@JsonInclude(Include.NON_EMPTY)
class Foo
{
String bar;
}