jackSon中@JsonInclude注解详解

前言
比如说我有个场景,返回前端的实体类中如果某个字段为空的话那么就不返回这个字段了,如果我们平时遇到这个问题,那么真的该脑壳疼了。幸亏有我们今天的主角,这个注解就是用来在实体类序列化成json的时候在某些策略下,加了该注解的字段不去序列化该字段。

@JsonInclude用法
JsonJsonInclude.Include.ALWAYS 这个是默认策略,任何情况下都序列化该字段,和不写这个注解是一样的效果。
JsonJsonInclude.Include.NON_NULL这个最常用,即如果加该注解的字段为null,那么就不序列化这个字段了。
JsonJsonInclude.Include.NON_ABSENT这个包含NON_NULL,即为null的时候不序列化,第二种情况是下面的英文,我也没看懂,有兴趣的朋友可以研究下给我留言。
“absent” value of a referential type (like Java 8 Optional, or {link java.utl.concurrent.atomic.AtomicReference}); that is, something that would not deference to a non-null value.
This option is mostly used to work with "Optional"s (Java 8, Guava)
JsonJsonInclude.Include.NON_EMPTY 这个属性包含NON_NULL,NON_ABSENT之后还包含如果字段为空也不序列化。这个也比较常用
JsonJsonInclude.Include.NON_DEFAULT这个也好理解,如果字段是默认值的话就不序列化。
JsonJsonInclude.Include.CUSTOM奉上英文解释,我还没研究懂
Value that indicates that separate filter Object (specified by valueFilter for value itself, and/or contentFilter for contents of structured types) is to be used for determining inclusion criteria. Filter object’s equals() method is called with value to serialize; if it returns true value is excluded (that is, filtered out); if false value is included.
JsonJsonInclude.Include.USE_DEFAULTS同上暂时没研究懂
Pseudo-value used to indicate that the higher-level defaults make sense, to avoid overriding inclusion value. For example, if returned for a property this would use defaults for the class that contains property, if any defined; and if none defined for that, then global serialization inclusion details.
这里我们以如果为null则不序列化举例说明

public class User {
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String username;
    private String password;
    private Integer age;
}

  或者加到类上

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class MenuVo {

    private String name;

    private String path;

    private Boolean hidden;

    private String redirect;

    private String component;

    private Boolean alwaysShow;

    private MenuMetaVo meta;

    private List<MenuVo> children;
}

参数为null时,传给前端的数据里,序列化是就会把该参数去掉

————————————————
powerd by :https://blog.csdn.net/weixin_44130081/java/article/details/89678450

原文地址:https://www.cnblogs.com/mafy/p/12810178.html