您好,登錄后才能下訂單哦!
這篇文章主要介紹“基于序列化怎么實現jackson”,在日常操作中,相信很多人在基于序列化怎么實現jackson問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”基于序列化怎么實現jackson”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
基于序列化的實現
Fastjson實現
實現思路:
自定義注解,可讓用戶自定義脫敏方式,用于實體類的屬性
基于ValueFilter進行 屬性注解攔截,并多value進行替換脫敏
使用json序列化對象是指定自定義序列化Filter
核心代碼如下
自定義注解Desensitization
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Desensitization { /** * 脫敏規則 * * @return */ DesensitionEnum desensitionEnum(); }
脫敏方法
/** * 脫敏的函數接口 */ public interface Desensitizer extends Function<String, String> { } @Getter public enum DesensitionEnum { /** * 用戶名脫敏 */ USERNAME("userName", "用戶名",s -> s.replaceAll("(\\S)\\S(\\S*)", "$1*$2")), /** * 身份證號碼脫敏 */ ID_CARD("idCard", "15或者18身份證號",s -> s.replaceAll("(\\d{4})\\d{10}(\\w{4})", "$1****$2")), /** * 手機號脫敏 */ PHONE("phone", "手機號",s -> s.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2")), /** * 地址脫敏 */ ADDRESS("address", "地址脫敏",s -> s.replaceAll("(\\S{8})\\S{4}(\\S*)\\S{4}", "$1****$2****")); String fieldName; String fieldDescribe; private final Desensitizer desensitizer; DesensitionEnum(String fieldName, String fieldDescribe, Desensitizer desensitizer) { this.fieldName = fieldName; this.fieldDescribe = fieldDescribe; this.desensitizer = desensitizer; } }
具體攔截
public class FastjsonDesensitizeFilter implements ValueFilter { @Override public Object process(Object object, String name, Object value) { if (null == value || !(value instanceof String) || ((String) value).length() == 0) { return value; } try { Field field = object.getClass().getDeclaredField(name); Desensitization desensitization; if (String.class != field.getType() || (desensitization = field.getAnnotation(Desensitization.class)) == null) { return value; } return desensitization.desensitionEnum().getDesensitizer().apply((String) value); } catch (Exception e) { return value; } } }
Jackson實現
解釋:
獲取對象屬性上的注解,根據屬性得到相應的脫敏規則類型
按照規則類型進行value替換
自定義注解
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @JsonSerialize(using = JacksonDesensitize.class) @JacksonAnnotationsInside public @interface Desensitization { /** * 脫敏規則 * * @return */ DesensitionEnum desensitionEnum(); } package com.demo.desensitization; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.ContextualSerializer; import java.io.IOException; import java.util.Objects; public class JacksonDesensitize extends JsonSerializer<String> implements ContextualSerializer { private DesensitionEnum desensitionEnum; @Override public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeString(desensitionEnum.getDesensitizer().apply((String) value)); } @Override public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException { if (beanProperty != null) { // 非 String 直接跳過 if (Objects.equals(beanProperty.getType().getRawClass(), String.class)) { // 獲取注解信息 Desensitization annotation = beanProperty.getAnnotation(Desensitization.class); if (annotation == null) { annotation = beanProperty.getContextAnnotation(Desensitization.class); } if (annotation != null) { // 獲得注解上的值并賦值 this.desensitionEnum = annotation.desensitionEnum(); return this; } } return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty); } return serializerProvider.findNullValueSerializer(null); } }
執行結果
package com.demo.desensitization; import lombok.Data; import java.io.Serializable; @Data public class UserDTO implements Serializable { @Desensitization(desensitionEnum=DesensitionEnum.ID_CARD) private String idCard; @Desensitization(desensitionEnum=DesensitionEnum.USERNAME) private String username; @Desensitization(desensitionEnum=DesensitionEnum.PHONE) private String phone; @Desensitization(desensitionEnum=DesensitionEnum.ADDRESS) private String address; } public static void testFast(){ FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.DisableCircularReferenceDetect); fastJsonConfig.setSerializeFilters(new FastjsonDesensitizeFilter()); UserDTO userDTO=new UserDTO(); userDTO.setUsername("張三"); userDTO.setPhone("15669057552"); userDTO.setIdCard("370826198901133299"); userDTO.setAddress("浙江省杭州市江干區火車東站"); String s = JSON.toJSONString(userDTO,new FastjsonDesensitizeFilter()); System.out.println(s); } public static void testJackson() throws JsonProcessingException { UserDTO userDTO=new UserDTO(); userDTO.setUsername("張三"); userDTO.setPhone("15669057552"); userDTO.setIdCard("370826198901133299"); userDTO.setAddress("浙江省杭州市江干區火車東站"); ObjectMapper objectMapper = new ObjectMapper(); String value = objectMapper.writeValueAsString(userDTO); System.out.println(value); }
最終輸出結果
{"idCard":"3708****3299","username":"張*","phone":"156****7552","address":"浙江省杭州市江干區火車東站"}
到此,關于“基于序列化怎么實現jackson”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。