Java 如果字段的值为空,如何告诉Jackson在序列化过程中忽略该字段?

Java 如果字段的值为空,如何告诉Jackson在序列化过程中忽略该字段?,java,jackson,Java,Jackson,如果字段值为空,如何配置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>2.0禁止使用空值序列化属性,您可以或使用

如果字段值为空,如何配置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>2.0禁止使用空值序列化属性,您可以或使用注释:

mapper.setSerializationInclusion(Include.NON_NULL);
或:

或者,您可以在getter中使用
@JsonInclude
,以便在值不为null时显示属性


到中提供了更完整的示例。

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

mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
从2.5开始,您可以使用:

mapper.setSerializationInclusion(Include.NON_NULL);

对于Jackson>1.9.11和<2.x,请使用
@JsonSerialize
注释:


@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

仅对其他答案进行扩展-如果您需要在每个字段的基础上控制空值的省略,请注释相关字段(或者注释字段的“getter”)

示例-这里只有
fieldOne
会从json中输入,如果它为空<代码>字段二将始终包括在内,无论它是否为空

public class Foo {

    @JsonInclude(JsonInclude.Include.NON_NULL) 
    private String fieldOne;

    private String fieldTwo;
}
要将类中的所有空值作为默认值忽略,请对该类进行注释。如有必要,每个字段/getter注释仍可用于覆盖此默认值

示例-这里的
fieldOne
fieldTwo
如果分别为空,将从json中写入,因为这是类注释的默认设置<但是,由于字段上的注释,代码>字段三将覆盖默认值并始终包括在内

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Foo {

    private String fieldOne;

    private String fieldTwo;

    @JsonInclude(JsonInclude.Include.ALWAYS)
    private String fieldThree;
}

更新

以上内容适用于《杰克逊2》。对于早期版本的杰克逊,您需要使用:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) 
而不是

@JsonInclude(JsonInclude.Include.NON_NULL)
如果这个更新是有用的,请向上投票ZiglioUK下面的答案,它指出了更新的Jackson 2注释早在我更新我的答案使用它之前

在Jackson 2.x中,使用:

@JsonInclude(JsonInclude.Include.NON_NULL)
Jackson 2.x+使用

mapper.getSerializationConfig().withSerializationInclusion(JsonInclude.Include.NON_NULL);
就我而言

@JsonInclude(Include.NON_EMPTY)
使其工作。

对于Jackson 2.5使用:

@JsonInclude(content=Include.NON_NULL)

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

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
应该有用

Include.NON_EMPTY
表示如果属性的值不为null且不为空,则该属性将被序列化。
Include.NON_NULL
表示如果属性的值不为NULL,则该属性将被序列化。

这让我困扰了很长一段时间,我终于找到了问题所在。这个问题是由于错误的进口造成的。早些时候,我一直在使用

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)

您可以设置
应用程序属性

spring.jackson.default-property-inclusion=non_null
application.yaml

spring:
  jackson:
    default-property-inclusion: non_null

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

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!
        }
    });
mapper.getSerializerProvider().setNullValueSerializer(新的JsonSerializer()){
@凌驾
公共void序列化(对象obj、JsonGenerator jsonGen、SerializerProvider未使用)
抛出IOException
{
//忽略空值!
}
});

提示:如果您使用DropWizard,您可以使用
环境检索Jersey使用的
ObjectMapper
。getObjectMapper()
如果在Spring Boot中,您可以通过属性文件直接自定义jackson
ObjectMapper

示例
application.yml

spring:
  jackson:
    default-property-inclusion: non_null
spring:
杰克逊:
默认属性包含:非空#仅在非空时包含道具
可能的值为:

always|non_null|non_absent|non_default|non_empty

更多信息:

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

}

这将适用于Spring boot 2.0.3+和Jackson 2.0+

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiDTO
{
    // your class variable and 
    // methods
}

此外,在使用Map myVariable(如文档中所述)删除空值时,您必须更改方法:

From documentation:
com.fasterxml.jackson.annotation.JsonInclude

@JacksonAnnotation
@Target(value={ANNOTATION_TYPE, FIELD, METHOD, PARAMETER, TYPE})
@Retention(value=RUNTIME)
Annotation used to indicate when value of the annotated property (when used for a field, method or constructor parameter), or all properties of the annotated class, is to be serialized. Without annotation property values are always included, but by using this annotation one can specify simple exclusion rules to reduce amount of properties to write out.

*Note that the main inclusion criteria (one annotated with value) is checked on Java object level, for the annotated type, and NOT on JSON output -- so even with Include.NON_NULL it is possible that JSON null values are output, if object reference in question is not `null`. An example is java.util.concurrent.atomic.AtomicReference instance constructed to reference null value: such a value would be serialized as JSON null, and not filtered out.

To base inclusion on value of contained value(s), you will typically also need to specify content() annotation; for example, specifying only value as Include.NON_EMPTY for a {link java.util.Map} would exclude Maps with no values, but would include Maps with `null` values. To exclude Map with only `null` value, you would use both annotations like so:
public class Bean {
   @JsonInclude(value=Include.NON_EMPTY, content=Include.NON_NULL)
   public Map<String,String> entries;
}

Similarly you could Maps that only contain "empty" elements, or "non-default" values (see Include.NON_EMPTY and Include.NON_DEFAULT for more details).
In addition to `Map`s, `content` concept is also supported for referential types (like java.util.concurrent.atomic.AtomicReference). Note that `content` is NOT currently (as of Jackson 2.9) supported for arrays or java.util.Collections, but supported may be added in future versions.
Since:
2.0
来自文档:
com.fasterxml.jackson.annotation.JsonInclude
@杰克森注释
@目标(值={ANNOTATION_TYPE,FIELD,METHOD,PARAMETER,TYPE})
@保留期(值=运行时)
注释用于指示何时序列化带注释属性的值(用于字段、方法或构造函数参数时)或带注释类的所有属性。不带注释的属性值始终包含在内,但通过使用此注释,可以指定简单的排除规则以减少要写出的属性数量。
*请注意,主要的包含条件(一个带有值的注释)是在Java对象级别为注释类型检查的,而不是在JSON输出上检查的——因此,即使使用Include.NON_NULL,如果所讨论的对象引用不是“NULL”,JSON空值也可能被输出。例如,java.util.concurrent.AtomicReference实例构造为引用null值:这样的值将被序列化为JSON null,而不是过滤掉。
要基于包含的值包含,通常还需要指定content()注释;例如,为{link java.util.Map}仅将值指定为Include.NON_EMPTY将排除没有值的映射,但将包括具有“null”值的映射。要排除只有'null'值的映射,您可以使用两种注释,如下所示:
公共类Bean{
@JsonInclude(值=Include.NON_为空,内容=Include.NON_为空)
公共地图条目;
}
类似地,您可以只包含“空”元素或“非默认”值的映射(有关详细信息,请参见Include.non_empty和Include.non_default)。
除了“Map”之外,引用类型(如java.util.concurrent.AtomicReference)还支持“content”概念。请注意,数组或java.util.Collections目前不支持“content”(从Jackson 2.9开始),但在将来的版本中可能会添加支持。
自:
2

这个问题我们有很多答案。这个答案在某些情况下可能会有所帮助 如果你
From documentation:
com.fasterxml.jackson.annotation.JsonInclude

@JacksonAnnotation
@Target(value={ANNOTATION_TYPE, FIELD, METHOD, PARAMETER, TYPE})
@Retention(value=RUNTIME)
Annotation used to indicate when value of the annotated property (when used for a field, method or constructor parameter), or all properties of the annotated class, is to be serialized. Without annotation property values are always included, but by using this annotation one can specify simple exclusion rules to reduce amount of properties to write out.

*Note that the main inclusion criteria (one annotated with value) is checked on Java object level, for the annotated type, and NOT on JSON output -- so even with Include.NON_NULL it is possible that JSON null values are output, if object reference in question is not `null`. An example is java.util.concurrent.atomic.AtomicReference instance constructed to reference null value: such a value would be serialized as JSON null, and not filtered out.

To base inclusion on value of contained value(s), you will typically also need to specify content() annotation; for example, specifying only value as Include.NON_EMPTY for a {link java.util.Map} would exclude Maps with no values, but would include Maps with `null` values. To exclude Map with only `null` value, you would use both annotations like so:
public class Bean {
   @JsonInclude(value=Include.NON_EMPTY, content=Include.NON_NULL)
   public Map<String,String> entries;
}

Similarly you could Maps that only contain "empty" elements, or "non-default" values (see Include.NON_EMPTY and Include.NON_DEFAULT for more details).
In addition to `Map`s, `content` concept is also supported for referential types (like java.util.concurrent.atomic.AtomicReference). Note that `content` is NOT currently (as of Jackson 2.9) supported for arrays or java.util.Collections, but supported may be added in future versions.
Since:
2.0
@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}
@JsonInclude(Include.NON_EMPTY)
class Foo
{
  String bar;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
private String someString;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private String someString;