关于java:如果它的值为null,如何告诉Jackson在序列化期间忽略某个字段?

How to tell Jackson to ignore a field during serialization if its value is null?

如果字段的值为空,如何将Jackson配置为在序列化期间忽略字段值。

例如:

1
2
3
4
5
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禁止使用空值序列化属性,可以直接配置ObjectMapper,或使用@JsonInclude批注:

1
mapper.setSerializationInclusion(Include.NON_NULL);

或:

1
2
3
4
5
@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

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

关于如何防止映射中的空值和bean中的空字段通过Jackson序列化,我的答案中提供了一个更完整的示例。


当Jackson>1.9.11且<2.x时,使用@JsonSerialize注释来执行此操作:

江户十一〔四〕号


只需在其他答案上展开-如果需要控制每个字段上省略空值,请为相关字段添加注释(或者为字段的"getter"添加注释)。

示例-这里只有fieldOne在它为空时才会从json中被省略。无论是否为空,都将始终包括fieldTwo

1
2
3
4
5
6
7
public class Foo {

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

    private String fieldTwo;
}

要忽略类中的所有空值作为默认值,请为类添加注释。如果需要,仍然可以使用每个字段/getter注释来覆盖此默认值。

示例-这里,如果fieldOnefieldTwo分别为空,则会从JSON中发出committed,因为这是类注释设置的默认值。但是,由于字段上的注释,fieldThree将覆盖默认值并始终包括在内。

1
2
3
4
5
6
7
8
9
10
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Foo {

    private String fieldOne;

    private String fieldTwo;

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

更新

上面是杰克逊2号的。对于早期版本的杰克逊,您需要使用:

1
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

而不是

1
@JsonInclude(JsonInclude.Include.NON_NULL)

如果这个更新是有用的,请向上投票Zigliouk的答案下面,它指出了更新的杰克逊2注释早在我更新我的答案使用它之前!


在Jackson 2.x中,使用:

1
@JsonInclude(JsonInclude.Include.NON_NULL)


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

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

从2.5开始,您可以使用:

1
mapper.setSerializationInclusion(Include.NON_NULL);


您可以设置application.properties

1
spring.jackson.default-property-inclusion=non_null

application.yaml

1
2
3
spring:
  jackson:
    default-property-inclusion: non_null

http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html


就我而言

1
@JsonInclude(Include.NON_EMPTY)

成功了。


1
2
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonInclude(JsonInclude.Include.NON_EMPTY)

应该有效。

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


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

1
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);


如果在Spring引导中,您可以直接通过属性文件定制Jackson ObjectMapper

示例application.yml

1
2
3
spring:
  jackson:
    default-property-inclusion: non_null # only include props if non-null

可能的值是:

1
always|non_null|non_absent|non_default|non_empty

更多:https://docs.spring.io/spring boot/docs/current/reference/html/howto spring mvc.html如何自定义杰克逊对象映射器


这将在SpringBoot2.0.3+和Jackson2.0中工作+

1
2
3
4
5
6
7
8
import com.fasterxml.jackson.annotation.JsonInclude;

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


杰克逊2.5版使用:

1
@JsonInclude(content=Include.NON_NULL)


这个问题困扰了我很长一段时间,我终于发现了这个问题。问题是由于导入错误。我以前用过

1
com.fasterxml.jackson.databind.annotation.JsonSerialize

已经被否决了。只需将导入替换为

1
2
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

把它当作

1
@JsonSerialize(include=Inclusion.NON_NULL)


如果您试图序列化一个对象列表,而其中一个为空,则最终会在JSON中包含空项,即使使用

1
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

将导致:

[myObject,空]

要得到这个:

[MyObject]

你可以做如下的事情:

1
2
3
4
5
6
7
8
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使用的对象映射器。


使用Spring时的全局配置

1
2
3
4
5
6
7
8
9
10
11
12
13
@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;
    }

}


此外,当使用文档中描述的map myvariable删除空值时,必须更改方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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


杰克逊2.x+用法

1
mapper.getSerializationConfig().withSerializationInclusion(JsonInclude.Include.NON_NULL);