Java 自动读取json文件转化为实体类

思路:

1 创建一个辅助类,与json文件和转化实体类分别建立对应关系

2 创建辅助类的注解属性与json文件属性对应

3 辅助类字段属性与实体类相同

具体需求

json文件

{"Main": {"TestNo": "30103182222","appliName": "大小"},
"other":{}}

保存类

public class Obj {
    private String voteName;
    private String DanNo;
   
}

将json文件读取后保存到实体类Obj

具体实现

1 创建注解类,type与json对象对应,string,查询对应的属性名

@Documented
@Inherited
@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ParseJsonField {
    public String type() default "";
    public String value() default "";
}

2创建辅助类

public class ParseObj {
    @ParseJsonField(type="Main",value="appliName")
    private String voteName;
    @ParseJsonField(type="Main",value="TestNo")
    private String DanNo;
   
}

2  利用反射从json文件中的json对象读取相应属性值赋值给辅助类

    //从jsonObject读取值到object.
    public static <T> void readJson(JSONObject jsonObject, T toObj, String type) {
        //读取辅助类所有字段名
        Field[] f2 = toObj.getClass().getDeclaredFields();
        //循环遍历所有字段
        for (Field field : f2) {
            //禁用安全检查
            field.setAccessible(true);
            try {
                //检查是否有注解
                if (field.isAnnotationPresent(ParseJsonField.class)) {
                    //读取当前注解
                    ParseJsonField JsonField = field.getAnnotation(ParseJsonField.class);
                    //匹配当前json对象
                    if (type.equals(JsonField.type())) {
                        //读取json对象属性值
                        Object valueObject = jsonObject.get(JsonField.value());
                        // 获取属性的类型
                        String Attrtype = field.getGenericType().toString();
                        String valueObject_str=String.valueOf(valueObject);
                        if (valueObject != null&&valueObject_str.length()>0) {
                            if (Attrtype.equals("class java.sql.Timestamp")) {
                                    if (valueObject_str.length() <= 10) {
                                        valueObject_str = valueObject_str + " 00:00:00";
                                    }
                                field.set(toObj, Timestamp.valueOf(valueObject_str));
                            } else if (Attrtype.equals("class java.lang.String")) {
                                field.set(toObj, String.valueOf(valueObject));
                            } else if (Attrtype.equals("class java.lang.Integer")) {
                                    field.set(toObj, Integer.parseInt(valueObject_str));//
                            } else if (Attrtype.equals("class java.math.BigDecimal")) {
                                    field.set(toObj,new BigDecimal(valueObject_str));//
                            } else {
                                field.set(toObj, valueObject);
                            }
                        }
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.print(toObj);
            }
        }
    }

3 利用反射将辅助类的值保存进保存类

    //读取辅助类数据到保存类 toObj 辅助类  fromObj 保存类
    public static <T1, T2> void tryUpdate(T1 formObj, T2 toObj) {
        // TODO Auto-generated method stub
        //读取辅助类所有字段名
        Field[] f2 = toObj.getClass().getDeclaredFields();
        //循环遍历所有字段
        for (Field field : f2) {
            //禁用安全检查
            field.setAccessible(true);
            try {
                //读取辅助类对象属性值
                Object valueObject = field.get(toObj);
                if (valueObject != null) {
                    //获取保存类字段对象
                    Field formField = formObj.getClass().getDeclaredField(field.getName());
                    //禁用安全检查
                    formField.setAccessible(true);
                    //保存类的值
                    formField.set(formObj, valueObject);
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

4 实际使用

JSONObject JsonData= data.getJSONObject(JsonStr);
ParseObj parseObj = new ParseObj();
readJson(JsonData, parseObj, "Main");
tryUpdate(Obj, parseObj);

猜你喜欢

转载自blog.csdn.net/qq_25744257/article/details/84520383