自己写的json转java bean工具类

前言

  • 用json-lib自带的toBean感觉不太好用,对于复杂的嵌套会报错,会报错:MorphDynaBean cannot be cast to ** 故自己尝试写一下。

  • 记录

    • 对Date、short类型的转换存在问题,暂时不管了

    代码

public static  T json2Bean(JSONObject json, Class clazz) throws Exception {
        T t = clazz.newInstance();
        Method[] methods = clazz.getDeclaredMethods();
        if (methods == null || methods.length == 0)
            return null;

        for (Method method : methods) {
            String methodName = method.getName();
            if (methodName.startsWith("set")) {
                StringBuffer fieldName = new StringBuffer();

                // 形参类型:String long Product boolean double short int String List
                Class ParamClazz = method.getParameterTypes()[0];

                // 通过set的method拿到字段名称name time delFlag birth price price2 age
                fieldName.append(methodName.substring(3, 4).toLowerCase())// 字段首字母小写
                        .append(methodName.substring(4));

                if (!json.has(fieldName.toString())) {
                    continue;
                }

                // 常用基本类型 不含short,Date(支持String类型的 日期)
                if (ParamClazz == boolean.class || ParamClazz == Boolean.class) {
                    method.invoke(t, new Object[] { json.optBoolean(fieldName.toString(), false) });
                } else if (ParamClazz == int.class || ParamClazz == Integer.class) {
                    method.invoke(t, new Object[] { json.optInt(fieldName.toString(), 0) });
                } else if (ParamClazz == long.class || ParamClazz == Long.class) {
                    method.invoke(t, new Object[] { json.optLong(fieldName.toString(), 0) });
                } else if (ParamClazz == double.class || ParamClazz == Double.class) {
                    method.invoke(t, new Object[] { json.optDouble(fieldName.toString(), 0) });
                } else if (ParamClazz == String.class) {
                    method.invoke(t, new Object[] { json.optString(fieldName.toString(), "") });
                }else if(ParamClazz == Date.class){
                    method.invoke(t, new Object[] { json.optString(fieldName.toString(),"") });
                }else if (List.class.isAssignableFrom(ParamClazz)) {//解析jsonArray为list
                    JSONArray array = json.getJSONArray(fieldName.toString());
                    List list = new ArrayList<>();
                    for(int i =0;array!=null && i<array.size();i++){
                        JSONObject jsonobj = array.getJSONObject(i);

                        Class listType = (Class) ((ParameterizedType) clazz   // 获取List的泛型类型
                        .getDeclaredField(fieldName.toString()).getGenericType())
                        .getActualTypeArguments()[0];

                        Object obj = json2Bean(jsonobj, listType);
                        list.add(obj);
                    }
                    method.invoke(t,list);

                } else {//jsonObject和无法解析字段的判断
                    try{
                        JSONObject getjsonObj = json.getJSONObject(fieldName.toString());
                        Object obj = json2Bean(getjsonObj, ParamClazz);
                        method.invoke(t, obj);
                    }catch(JSONException e){
                        e.printStackTrace();
                        continue;
                    }
                }
            }
        }
        return t;
    }

你可能感兴趣的:(工具学习,自己造轮子-工具类)