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

后端 未结 19 1501
情歌与酒
情歌与酒 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:26

    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.

提交回复
热议问题