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

后端 未结 19 1183
情歌与酒
情歌与酒 2020-11-22 04:55

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

For example:

public class SomeClass {
            


        
19条回答
  •  广开言路
    2020-11-22 05:16

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

    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!

提交回复
热议问题