原文: 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字段沒有加屬性,正常序列化成功。