776

如果该字段的值为空,如何将 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; 
}
4

20 回答 20

1212

要使用 Jackson >2.0 禁止序列化具有空值的属性,您可以直接配置ObjectMapper,或使用@JsonInclude注释:

mapper.setSerializationInclusion(Include.NON_NULL);

或者:

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

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

我对如何防止 Map 中的空值和 bean 中的空字段通过 Jackson 序列化的回答中提供了一个更完整的示例。

于 2012-08-01T14:57:34.390 回答
150

Just to expand on the other answers - if you need to control the omission of null values on a per-field basis, annotate the field in question (or alternatively annotate the field's 'getter').

example - here only fieldOne will be omitted from the JSON if it is null. fieldTwo will always be included in the JSON regardless of if it is null.

public class Foo {

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

    private String fieldTwo;
}

To omit all null values in the class as a default, annotate the class. Per-field/getter annotations can still be used to override this default if necessary.

example - here fieldOne and fieldTwo will be omitted from the JSON if they are null, respectively, because this is the default set by the class annotation. fieldThree however will override the default and will always be included, because of the annotation on the field.

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

    private String fieldOne;

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

UPDATE

The above is for Jackson 2. For earlier versions of Jackson you need to use:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) 

instead of

@JsonInclude(JsonInclude.Include.NON_NULL)

If this update is useful, please upvote ZiglioUK's answer below, it pointed out the newer Jackson 2 annotation long before I updated my answer to use it!

于 2013-07-29T13:46:01.080 回答
135

With Jackson > 1.9.11 and < 2.x use @JsonSerialize annotation to do that:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

于 2013-06-27T07:39:33.660 回答
66

In Jackson 2.x, use:

@JsonInclude(JsonInclude.Include.NON_NULL)
于 2014-01-20T02:28:43.873 回答
45

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

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

从 2.5 开始,您可以使用:

mapper.setSerializationInclusion(Include.NON_NULL);
于 2013-04-01T14:47:29.460 回答
39

You can set application.properties:

spring.jackson.default-property-inclusion=non_null

or application.yaml:

spring:
  jackson:
    default-property-inclusion: non_null

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

于 2016-11-16T08:04:58.680 回答
12

in my case

@JsonInclude(Include.NON_EMPTY)

made it work.

于 2015-04-24T19:07:07.790 回答
8
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonInclude(JsonInclude.Include.NON_EMPTY)

should work.

Include.NON_EMPTY indicates that property is serialized if its value is not null and not empty. Include.NON_NULL indicates that property is serialized if its value is not null.

于 2016-05-02T15:44:15.607 回答
6

This Will work in Spring boot 2.0.3+ and Jackson 2.0+

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiDTO
{
    // your class variable and 
    // methods
}
于 2018-11-22T06:21:23.090 回答
5

If you want to add this rule to all models in Jackson 2.6+ use:

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
于 2016-04-27T21:52:09.667 回答
5

If in Spring Boot, you can customize the jackson ObjectMapper directly through property files.

Example application.yml:

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

Possible values are:

always|non_null|non_absent|non_default|non_empty

More: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper

于 2017-11-28T20:56:03.750 回答
3

For Jackson 2.5 use :

@JsonInclude(content=Include.NON_NULL)
于 2015-07-19T21:14:05.710 回答
3

If you're trying to serialize a list of object and one of them is null you'll end up including the null item in the JSON even with

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

will result in:

[{myObject},null]

to get this:

[{myObject}]

one can do something like:

mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
        @Override
        public void serialize(Object obj, JsonGenerator jsonGen, SerializerProvider unused)
                throws IOException
        {
            //IGNORES NULL VALUES!
        }
    });

TIP: If you're using DropWizard you can retrieve the ObjectMapper being used by Jersey using environment.getObjectMapper()

于 2017-11-23T06:42:35.297 回答
2

This has been troubling me for quite some time and I finally found the issue. The issue was due to a wrong import. Earlier I had been using

com.fasterxml.jackson.databind.annotation.JsonSerialize

Which had been deprecated. Just replace the import by

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

and use it as

@JsonSerialize(include=Inclusion.NON_NULL)
于 2016-10-24T07:13:37.250 回答
2

Global configuration if you use 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;
    }

}
于 2018-01-22T20:57:34.823 回答
1

We have lot of answers to this question. This answer may be helpful in some scenarios If you want to ignore the null values you can use the NOT_NULL in class level. as below

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

Some times you may need to ignore the empty values such as you may have initialized the arrayList but there is no elements in that list.In that time using NOT_EMPTY annotation to ignore those empty value fields

@JsonInclude(Include.NON_EMPTY)
class Foo
{
  String bar;
}
于 2019-12-12T13:05:14.413 回答
1

Case one

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

Case two

@JsonInclude(JsonInclude.Include.NON_EMPTY)
private String someString;

If someString is null, it will be ignored on both of cases. If someString is "" it just only be ignored on case two.

The same for List = null or List.size() = 0

于 2020-05-26T19:43:32.030 回答
0

Jackson 2.x+ use

mapper.getSerializationConfig().withSerializationInclusion(JsonInclude.Include.NON_NULL);
于 2014-09-26T20:12:06.077 回答
0

Also, you have to change your approach when using Map myVariable as described in the documentation to eleminate nulls:

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
于 2019-05-16T22:56:45.967 回答
0

Try this -

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class XYZ {
    
    protected String field1;
    
    protected String field2;
 }

And for non-null values (On getters/class level) -

@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)
于 2021-08-02T07:11:18.777 回答