jackSon中@JsonInclude注解详解
原文: https://blog.csdn.net/weixin_44130081/article/details/89678450
前言
比如说我有个场景,返回前端的实体类中如果某个字段为空的话那么就不返回这个字段了,如果我们平时遇到这个问题,那么真的该脑壳疼了。幸亏有我们今天的主角,这个注解就是用来在实体类序列化成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;
}
测试代码
public static void main(String[] args) throws IOException {
User user = new User();
ObjectMapper objectMapper = new ObjectMapper();
String value = objectMapper.writeValueAsString(user);
System.out.println(value);
}
结果
{"password":null,"age":null}
可以看出我们在username上面加了这儿注解并且指定为null的时候不序列化,结果里面没有序列化username这个属性。password和age字段没有加属性,正常序列化成功。