java对象和map互相转换

第一种方式

 /**
     * @apiNote 将对象装换为map 
     * @author yepk
     * @date 2019/8/15 9:34
     * @param bean 对象
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }

    /**
     * @apiNote 将map装换为java对象 1
     * @author yepk
     * @date 2019/8/15 9:34
     * @param map 集合
     * @param bean 对象类型
     * @return T
     */
    public static <T> T mapToBean(Map<String, Object> map, T bean) {
        BeanMap beanMap = BeanMap.create(bean); 这种写法会有数据类型的问题 
        beanMap.putAll(map);
        return bean;
    }
    //上面map转对象有个问题 不同类型同属性的 转换会报错 所以我用fastjson转一样 
    public static <T> T mapToBean(Map<String, Object> map, Class<T> bean) {
        return JSON.parseObject(JSON.toJSONString(map)).toJavaObject(bean);
    }

第二种

//Apache BeanUtils将Bean转Map
User user = new User();
Map<String,String> map = BeanUtils.describe(user);
//Apache BeanUtils将Map转Bean
Map<String,String> map = new HashMap<>();
User user = new User();
BeanUtils.populate(user,map);
# java   code  

评论

企鹅群:39438021

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×