List<map>转List<bean>

/**
     * 将 Map对象转化为JavaBean
     * @return Object对象
     */
    public static <T> T convertMap2Bean(Map map, Class T) throws Exception {
        if(map==null || map.size()==0){
            return null;
        }
        BeanInfo beanInfo = Introspector.getBeanInfo(T);
        T bean = (T)T.newInstance();
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0, n = propertyDescriptors.length; i <n ; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (map.containsKey(propertyName)) {
                Object value = map.get(propertyName);
                BeanUtils.copyProperty(bean, propertyName, value);
                
            }
        }
        return bean;
    }
 /**
     * 将 List<Map>对象转化为List<JavaBean>
     * @return Object对象
     */
    public static <T> List<T> convertListMap2ListBean(List<Map<String,Object>> listMap, Class T) throws Exception {
        List<T> beanList = new ArrayList<T>();
        for(int i=0, n=listMap.size(); i<n; i++){
            Map<String,Object> map = listMap.get(i);
            T bean = convertMap2Bean(map,T);
            beanList.add(bean);
        }
        return beanList;
    }


注意:实体字段类型为date时,会报类型转换的错误,解决方法搜:beanutil date 就有,因为我也没去试,所以就不贴代码了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
list<bean>是指一个对象列表,每个对象中有多个属性。list<map>是指一个Map列表,每个Map中可以存储多个key-value键值对。 在Java中,将list<bean>换为list<map>可以采用以下方法: 1. 遍历list<bean>列表,依次将每个对象换为Map对象。 2. 在换过程中,利用反射机制获取每个对象的属性名和属性值,并将其存储为Map中的键值对。 3. 将每个Map对象添加到list<map>列表中,以实现整个列表的换。 示例代码如下: ```java List<Bean> beanList = new ArrayList<>(); List<Map<String, Object>> mapList = new ArrayList<>(); // 添加对象到beanListbeanList.add(new Bean("张三", 18)); beanList.add(new Bean("李四", 20)); beanList.add(new Bean("王五", 22)); // 遍历beanList,将每个对象换为Map对象 for (Bean bean : beanList) { Field[] fields = bean.getClass().getDeclaredFields(); // 获取对象的所有属性 Map<String, Object> map = new HashMap<>(); try { for (Field field : fields) { field.setAccessible(true); Object value = field.get(bean); // 获取属性值 map.put(field.getName(), value); } } catch (IllegalAccessException e) { e.printStackTrace(); } mapList.add(map); // 将换后的Map添加到列表中 } // 输出换结果 for (Map<String, Object> map : mapList) { System.out.println(map); } ``` 上述代码中,我们定义了一个Bean对象,并创建了一个含有多个对象的列表beanList。通过遍历beanList,我们将每个对象换为Map对象,并且添加到了另一个列表mapList中。 最后,输出换结果,可以看到我们成功将list<bean>换为了list<map>。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值