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

How can Jackson be configured to ignore a field value during serialization if that field's value is null.

For example:

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; 
}

To suppress serializing properties with null values using Jackson >2.0, you can configure the ObjectMapper directly, or make use of the @JsonInclude annotation:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

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

Alternatively, you could use @JsonInclude in a getter so that the attribute would be shown if the value is not null.

A more complete example is available in my answer to How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson.


随着杰克逊> 1.9.11和<2.x使用@JsonSerialize注释来做到这一点:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)


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 ommitted from json if it is null. fieldTwo will always be included 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 ommitted from 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;
}

UPDATED to use Jackson 2 - for earlier versions of Jackson 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 this newer annotation long before this update!

链接地址: http://www.djcxy.com/p/37868.html

上一篇: 泛型/ JSON JavaScriptSerializer C#

下一篇: 如果杰克逊在序列化过程中忽略某个字段的值是否为空,该如何告诉他?