自定义注解拷贝对象属性值,把string类型转成JSONOBject类型

1.创建自定义注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author 50649
 *自定义注解
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyJSONField {
}

2.创建支持注解的拷贝工具类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.botanee.medical.annotations.LocalJSONField;
import org.springframework.beans.BeanUtils;
import java.lang.reflect.Field;

/**
 * @author 
 * 支持注解的拷贝工具
 */
public class AnnotationBeanUtil {

    /**
     * 拷贝属性并自动将带有@JSONField注解的字段转换为JSONObject
     * @param source 源对象
     * @param targetClass 目标类
     * @return 目标对象实例
     */
    public static <T> T copyPropertiesWithJSONAnnotation(Object source, Class<T> targetClass) {
        try {
            // 创建目标对象
            T target = targetClass.getDeclaredConstructor().newInstance();
            // 拷贝基本属性
            BeanUtils.copyProperties(source, target);
            // 处理带有@JSONField注解的字段
            for (Field targetField : targetClass.getDeclaredFields()) {
                if (targetField.isAnnotationPresent(LocalJSONField.class) &&
                        targetField.getType().equals(JSONObject.class)) {

                    try {
                        // 获取源字段值
                        Field sourceField = source.getClass().getDeclaredField(targetField.getName());
                        sourceField.setAccessible(true);
                        Object value = sourceField.get(source);

                        if (value instanceof String) {
                            // 将字符串转换为JSONObject
                            JSONObject jsonValue =  JSON.parseObject(String.valueOf(value));
                            targetField.setAccessible(true);
                            targetField.set(target, jsonValue);
                        }
                    } catch (NoSuchFieldException e) {
                        // 源对象中没有对应字段,跳过
                        System.out.println("源对象中没有字段 " + targetField.getName() + ",跳过转换");
                    }
                }
            }

            return target;
        } catch (Exception e) {
            throw new RuntimeException("属性拷贝失败", e);
        }
    }
}

在实体类中添加该注解(被重新赋值对象)

public class CaseModelRespVO {
    private Long id;
    private String name;
    
    @MyJSONField
    private JSONObject data; // 这个字段需要从字符串转换为JSONObject
    
    // 构造函数、getter和setter方法
    public CaseModelRespVO() {}
    
    // 省略getter和setter方法
}

 

posted @ 2025-08-22 10:38  红尘沙漏  阅读(6)  评论(0)    收藏  举报