复杂对象集合与map之间的相互转换

一、泛型是map的list集合转换成对象集合

/**
 * 转换复杂的对象集合
 *
 * @param listMap
 * @param T
 * @param <T>
 * @return
 */
public static <T> List<T> castComplexObjectList(List<Map<String, Object>> listMap, Class T) {
    List<T> beanList = new ArrayList();
    int i = 0;

    if (listMapIsNotEmpty(listMap)) {
        for (int n = listMap.size(); i < n; ++i) {
            Map<String, Object> o = listMap.get(i);
            Object bean = castComplexObject(o, T);
            beanList.add((T) bean);
        }
    }
    return beanList;
}
/**
 * 转换复杂对象
 *
 * @param map
 * @param T
 * @param <T>
 * @return
 */
public static <T> T castComplexObject(Map<String, Object> map, Class T) {
    if (!StringUtil.isNotEmpty(map)) {
        return (T) T;
    }
    ObjectMapper objectMapper = new ObjectMapper();
    return (T) objectMapper.convertValue(map, T);
}

二、复杂对象集合转换成泛型是map的list集合

/**
 * 集合的类型转换(可以处理多重复杂参数的转换)
 *
 * @param list       数据集合(支持map)
 * @param collection 转换后的结果集
 * @param tClass     转换后结果集合的泛型类型
 * @param level      针对目标实体类中的复杂参数类型做递归赋值的层级 默认:0
 * @param <T>        结果集泛型
 * @param <E>        源数据集泛型
 */
public static <T, E> void listMap2Object(Collection<E> list, Collection collection, Class<T> tClass, Integer... level) {
    try {
        if (CollectionUtil.isNotEmpty(list)) {

            Integer newLevel = 0;
            //判断是否为空或者非数字型数据
            if (level.length > 0 && StringUtil.isInteger(level[0])) {
                newLevel = level[0];
            }

            Iterator<E> iterator = list.iterator();
            while (iterator.hasNext()) {
                E e = iterator.next();
                if (Map.class.isInstance(e)) {
                    Map next = (Map) e;
                    collection.add(map2Object(next, tClass, newLevel));
                } else {
                    T t = tClass.newInstance();
                    BeanUtils.copyProperties(e, t);
                    collection.add(t);
                }
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage());
    }
}
/**
     * 反射实现map转实体类
     *
     * @param map   源map
     * @param clazz 目标实体类class
     * @param level 针对目标实体类中的复杂参数类型做递归赋值的层级 默认 0
     * @return 返回目标实体类实例
     */
    public static <T> T map2Object(Map<String, Object> map, Class<T> clazz, Integer... level) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (null == map) {
            return null;
        }

        Integer newLevel = 0;
        //判断是否为空或者非数字型数据
        if (level.length > 0 && StringUtil.isInteger(level[0])) {
            newLevel = level[0];
        }

        T obj = null;
        try {
            // 使用newInstance来创建对象
            obj = clazz.newInstance();
            List<Field> fields = new ArrayList<>();
            Class<? super T> superclass = clazz.getSuperclass();
            // 获取类中的所有字段
            Field[] fields1 = obj.getClass().getDeclaredFields();
            Field[] fields2 = superclass.getDeclaredFields();
            fields.addAll(Arrays.asList(fields1));
            fields.addAll(Arrays.asList(fields2));
            for (Field field : fields) {
                int mod = field.getModifiers();
                // 判断是拥有某个修饰符,static和final关键字修饰的属性不处理
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                // 当字段使用private修饰时,需要加上
                field.setAccessible(true);
                // 获取参数类型名字
                Class<?> type = field.getType();
                String filedTypeName = field.getType().getName();
                Type genericType = field.getGenericType();
                // 获取obj的属性值
                Object o = map.get(field.getName());
                //当值为空时不处理
                if (o != null && !"".equals(o)) {
                    // 判断是否为时间类型,使用equalsIgnoreCase比较字符串,不区分大小写
                    if (filedTypeName.equalsIgnoreCase("java.util.date") && o instanceof String) {//时间类型
                        if ("null".equalsIgnoreCase((String) o)) {
                            field.set(obj, null);
                        } else {
                            field.set(obj, sdf.parse((String) o));
                        }
                        //基本数据类型及其包装类、String
                    } else if (isPrimitive(type) || type.equals(BigDecimal.class) || type.equals(String.class)) {
                        field.set(obj, o);
//                        field.set(obj, convert(o, type));
                        //当处理等级大于0时,才处理复杂参数类型
                    } else if (newLevel > 0) {
                        //type.isInstance(List.class),这种方式还有些问题,后续处理
                        //ParameterizedType判断有具体泛型类型的集合,主要包括(List、Map)
                        if (genericType instanceof ParameterizedType) {
                            //泛型参数数组,目前的处理逻辑是,当参数个数为1时,默认为List集合;为2时默认为Map集合
                            Type[] typeArguments = ((ParameterizedType) genericType).getActualTypeArguments();
                            if (typeArguments.length > 0 && typeArguments.length == 2) {
                                //Map类型的数据
                                field.set(obj, map2Object((Map) o, type, newLevel));
                            } else if (typeArguments.length > 0 && typeArguments.length == 1) {
                                Class c = (Class) typeArguments[0];
                                //调用 集合的map转实体方法
                                Collection o1 = (Collection) type.newInstance();
                                listMap2Object((Collection) o, o1, c, newLevel);
                            } else {
                                log.error(field.getName() + "复杂参数目前只支持List、Map和实体类型,其他的无法处理,请重新构思处理逻辑");
                            }
                            //暂时认为可以处理实体类型
                        } else if (o instanceof Map) {
                            field.set(obj, map2Object((Map) o, type, newLevel));
                        } else {
                            log.error(field.getName() + "复杂参数目前只支持List、Map和实体类型,其他的无法处理,请重新构思处理逻辑");
                        }
                    } else {
                        log.error(field.getName() + "复杂参数无法处理,请提升处理等级level");
                    }
                }
            }
        } catch (Exception e) {
            log.error(obj.getClass().getName() + "转化为map失败" + e);
            e.printStackTrace();
        } finally {
            //层级参数必须做修改
            newLevel--;
        }
        return obj;
    }

版权声明:本文为YRn_V原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。