Jackson忽略字段實現(xiàn)對字段進行序列化和反序列化
在使用 Jackson 進行序列化和反序列化時,有時候需要對某些字段進行過濾,以便在 JSON 數(shù)據(jù)中不包含某些敏感信息
@JsonInclude
可以標(biāo)記在字段上
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonIgnore {
boolean value() default true;
}
例如,以下代碼示例使用 @JsonIgnore 注解來隱藏敏感的密碼字段:
@Data
public class User {
private Integer id;
private String username;
@JsonIgnore // 隱藏了password字段
private String password;
}
@JsonIgnoreProperties
可以標(biāo)記在類上
@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonIgnoreProperties {
String[] value() default {};
}
@Data
@JsonIgnoreProperties({"username","password"})
public class User {
private Integer id;
private String username;
private String password;
}
@JsonIgnoreType
// 被該注解修飾的類,
// 作為其他類的成員變量時,不論是序列化還是反序列化都被忽略了;
@JsonIgnoreType
@JsonIgnoreType
public class TestChild {
private int value;
}
// Test類進行序列化和反序列時,
// 字段child被忽略
public class Test {
private String name;
private TestChild child;
}
JsonAutoDetect
// 根據(jù)訪問權(quán)限修飾符,對字段是否進行序列化和反序列化
@JsonAutoDetect
// 只對訪問權(quán)限修飾符為public的字段進行序列化和反序列化
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY)
public class College {
private String name;
private String city;
protected int age;
}
// fieldVisibility屬性有以下值可選 ANY // 所有 NON_PRIVATE // private之外的 PROTECTED_AND_PUBLIC // protected和public的(此時privte和默認的package access時不能被自動識別的) PUBLIC_ONLY // public的 NONE // 禁止自動識別 DEFAULT // 默認的,用于繼承父類的自動識別的范圍
參考鏈接
https://blog.csdn.net/weixin_45427648/article/details/129645380
到此這篇關(guān)于Jackson忽略字段實現(xiàn)對字段進行序列化和反序列化的文章就介紹到這了,更多相關(guān)Jackson忽略字段內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java POI 如何實現(xiàn)Excel單元格內(nèi)容換行
這篇文章主要介紹了java POI 如何實現(xiàn)Excel單元格內(nèi)容換行的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
Java數(shù)據(jù)結(jié)構(gòu)與算法之選擇排序(動力節(jié)點java學(xué)院整理)
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)與算法之選擇排序的相關(guān)資料,本文通過代碼講解,非常不錯,具有參考借鑒價值,需要的的朋友參考下2017-04-04
java動態(tài)添加外部jar包到classpath的實例詳解
這篇文章主要介紹了java動態(tài)添加外部jar包到classpath的實例詳解的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下2017-09-09

