自定义注解实现加注解的字段不被序列化和序列化

        此方法并无实际作用,主要是为了加深对反射以及注解的理解,实现字段不被序列化的方法是获取添加注解的属性名称,然后使用正则替换。

实体类

@Data
public class User {
    private int id;
    @UnSerialize
    private String name;
    @UnSerialize
    //忽略序列化
    private Integer age;
    @UnSerialize
    private String sex;

    private String password;
}

自定义注解

@Target( ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UnSerialize{
    
}

工具类

public class Utils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将对象转化为json字符串
     * @param o
     * @return
     * @param <T>
     * @throws JsonProcessingException
     */
    public static <T> String objectToJsonStr(T o) throws JsonProcessingException {
        String jsonStr = objectMapper.writeValueAsString(o);
        Class<?> oClass = o.getClass();
        //获取所有属性
        Field[] fields = oClass.getDeclaredFields();
        int i = 1;
        for(Field field : fields){
            //获取属性上的所有注解
            Annotation[] annotations = field.getAnnotations();
            for (Annotation annotation : annotations) {
                //如果注解有取消序列化的注解,则移除属性
                if (annotation.annotationType()==UnSerialize.class) {
                    String regx = (i==1?"":",")+"\""+field.getName()+"\":.*?(?=}|,)";
               
                    Pattern pattern = Pattern.compile(regx);
                    Matcher matcher = pattern.matcher(jsonStr);
                    jsonStr = matcher.replaceAll("");

                }
            }
            i++;
        }
        if (jsonStr.charAt(1)==',') jsonStr = jsonStr.replaceFirst(",","");
       return jsonStr;
    }

    /**
     * 序列化对象,将普通对象转化为字符串
     * @param f  自定义序列化方法
     * @param o 对象
     * @return
     * @param <T>
     * @throws JsonProcessingException
     */
    public static <T> String objectToJsonStr(Function<T,String> f,T o) throws JsonProcessingException {
        if (f==null) return objectToJsonStr(o);
        return f.apply(o);
    }

    public static <T> T jsonStrToObject(String jsonStr,Class<T> Class) throws JsonProcessingException {

        Field[] fields = Class.getDeclaredFields();
        jsonStr = getString(jsonStr, fields);
        int i = 1;
        for(Field field : fields){
            //获取属性上的所有注解
            Annotation[] annotations = field.getAnnotations();
            for (Annotation annotation : annotations) {
                //如果注解有取消序列化的注解,则移除属性
                if (annotation.annotationType()== UnSerialize.class) {
                    String regx = (i==1?"":",")+"\""+field.getName()+"\":.*?(?=}|,)";
//                    System.out.println(regx);
                    Pattern pattern = Pattern.compile(regx);
                    Matcher matcher = pattern.matcher(jsonStr);
                    jsonStr = matcher.replaceAll("");

                }
            }
            i++;
        }
        if (jsonStr.charAt(1)==',') jsonStr = jsonStr.replaceFirst(",","");
        return objectMapper.readValue(jsonStr,Class);
    }

   
}

测试方法

public static void main(String[] args) throws JsonProcessingException {


        User user = new User();
        user.setName("张三");
        user.setAge(10);
        user.setSex("男");
        user.setId(10);
        user.setPassword("uihgsfui");
        String userJson = objectToJsonStr(user);
        System.out.println(userJson);

        User user1 = jsonStrToObject(userJson, User.class);
        System.out.println(user1);
        
    }

结果

实现的添加自定义注解@UnSerialize的属性不被序列化和反序列化,但本注解并无实际作用,可以使用jackson中的@JsonIgnore注解来实现此效果。

  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,针对您的问题,我可以给出以下实现步骤: 1. 定义注解类,用于标记需要序列化和反序列化字段。 2. 定义序列化器和反序列化器,使用反射获取被注解标记的字段,并将其转换为字符串或从字符串转换回来。 3. 在需要进行序列化和反序列化的类中使用注解标记需要进行操作的字段。 以下是一个简单的示例代码: ```java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @interface Serialize { } class Serializer { public static String serialize(Object obj) throws IllegalAccessException { StringBuilder sb = new StringBuilder(); for (Field field : obj.getClass().getDeclaredFields()) { if (field.isAnnotationPresent(Serialize.class)) { field.setAccessible(true); sb.append(field.getName()).append("=").append(field.get(obj)).append(";"); } } return sb.toString(); } } class Deserializer { public static void deserialize(Object obj, String str) throws NoSuchFieldException, IllegalAccessException { for (String fieldString : str.split(";")) { String[] parts = fieldString.split("="); Field field = obj.getClass().getDeclaredField(parts[0]); if (field.isAnnotationPresent(Serialize.class)) { field.setAccessible(true); if (field.getType() == int.class) { field.setInt(obj, Integer.parseInt(parts[1])); } else if (field.getType() == String.class) { field.set(obj, parts[1]); } } } } } class Person { @Serialize private String name; @Serialize private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String toString() { return "Person{name='" + name + "', age=" + age + "}"; } } public class Main { public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException { Person person = new Person("Alice", 30); String serialized = Serializer.serialize(person); System.out.println(serialized); Person deserialized = new Person("", 0); Deserializer.deserialize(deserialized, serialized); System.out.println(deserialized); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

财大彭于晏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值