首页
 

通知公告

常用的map转bean互转方法

来源:欧亿体育点击:时间:2024-01-31 01:03

常用的map转bean互转方法

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

一、hutool工具类

这个很常用,还支持将蛇形转成驼,如:apply_time 会赋值到applyTime上


        LTDemo ltDemo = BeanUtil.mapToBean(map, LTDemo.class, true, CopyOptions.create());
        Map<String, Object> demoMap = BeanUtil.beanToMap(ltDemo);
        
        System.out.println("输出map -> bean: " + ltDemo.toString());
        System.out.println("输出bean -> map : " + demoMap);
        System.out.println(ltDemo.getApplyTime());
        System.out.println(ltDemo.getChildren());
        ltDemo.getChildren().forEach(children -> System.out.println(children.toString()));
        ltDemo.getChildren().forEach(children -> System.out.println(children.getAddress()));

输出原生map: {address=上海市, children=[{address=上海市, name=小张, apply_time=Fri Mar 03 17:21:01 CST 2023, age=2}], name=张三, apply_time=Fri Mar 03 17:21:01 CST 2023, age=20}
输出map -> bean: LTDemo(name=张三, age=20, address=上海市, applyTime=Fri Mar 03 17:21:01 CST 2023, children=[LTDemo(name=小张, age=2, address=上海市, applyTime=Fri Mar 03 17:21:01 CST 2023, children=[])])
输出bean -> map : {name=张三, age=20, address=上海市, applyTime=Fri Mar 03 17:21:01 CST 2023, children=[LTDemo(name=小张, age=2, address=上海市, applyTime=Fri Mar 03 17:21:01 CST 2023, children=[])]}
Fri Mar 03 17:21:01 CST 2023
[LTDemo(name=小张, age=2, address=上海市, applyTime=Fri Mar 03 17:21:01 CST 2023, children=[])]
LTDemo(name=小张, age=2, address=上海市, applyTime=Fri Mar 03 17:21:01 CST 2023, children=[])
上海市


二、fastjson工具类

这个也很常用,也支持将蛇型转成驼峰,
如:apply_time 会赋值到applyTime


        LTDemo ltDemo = JSONObject.parseObject(JSONObject.toJSONString(map), LTDemo.class);
        Map demoMap = JSONObject.parseObject(JSONObject.toJSONString(ltDemo), Map.class);
        
        System.out.println("输出map -> bean: " + ltDemo.toString());
        System.out.println("输出bean -> map : " + demoMap);
        System.out.println(ltDemo.getApplyTime());
        System.out.println(ltDemo.getChildren());
        ltDemo.getChildren().forEach(children -> System.out.println(children.toString()));
        ltDemo.getChildren().forEach(children -> System.out.println(children.getAddress()));


输出原生map: {address=上海市, children=[{address=上海市, name=小张, apply_time=Fri Mar 03 17:21:59 CST 2023, age=2}], name=张三, apply_time=Fri Mar 03 17:21:59 CST 2023, age=20}
输出map -> bean: LTDemo(name=张三, age=20, address=上海市, applyTime=Fri Mar 03 17:21:59 CST 2023, children=[LTDemo(name=小张, age=2, address=上海市, applyTime=Fri Mar 03 17:21:59 CST 2023, children=[])])
输出bean -> map : {address=上海市, children=[{"address":"上海市","children":[],"name":"小张","applyTime":1677835319813,"age":2}], name=张三, applyTime=1677835319813, age=20}
Fri Mar 03 17:21:59 CST 2023
[LTDemo(name=小张, age=2, address=上海市, applyTime=Fri Mar 03 17:21:59 CST 2023, children=[])]
LTDemo(name=小张, age=2, address=上海市, applyTime=Fri Mar 03 17:21:59 CST 2023, children=[])
上海市


三、beanutils_BeanUtils工具类 不太好用

嵌套型map,转换会有问题,且不支持蛇型转成驼峰

    //-------------------    beanutils_BeanUtils  -----------------
    //map转java对象
    public static <T> T beanUtils_mapToObject(Map<String, Object> map, Class<T> clazz) throws Exception {
        if (map == null) {
            return null;
        }
        T bean = clazz.newInstance();
        BeanUtils.populate(bean, map);
        return bean;
    }
        LTDemo ltDemo = beanUtils_mapToObject(map, LTDemo.class);
        System.out.println("输出map -> bean: " + ltDemo.toString());
        System.out.println(ltDemo.getApplyTime());
        System.out.println(ltDemo.getChildren().get(0).getApplyTime());
输出map -> bean: LTDemo(name=张三, age=20, address=上海市, applyTime=Fri Mar 03 17:04:38 CST 2023, children=[{address=上海市, name=小张, applyTime=Fri Mar 03 17:04:38 CST 2023, age=2}])
Fri Mar 03 17:04:38 CST 2023
Exception in thread "main" java.lang.ClassCastException: java.util.HashMap cannot be cast to com.example.demo.map2bean.LTDemo
	at com.example.demo.map2bean.MapToBean.main(MapToBean.java:73)

四、cglib BeanMap工具类 不太好用

这个也很常用,也支持将蛇形转成驼,如:apply_time 会赋值到applyTime上

import net.sf.cglib.beans.BeanMap;

    // -------------------   cglib BeanMap  -------------------
    //map对象转java
    public static <T> T BeanMapMapToObject(Map<String, Object> map, Class<T> beanClass) throws Exception {
        T object = beanClass.newInstance();
        BeanMap beanMap = BeanMap.create(object);
        beanMap.putAll(map);
        return object;
    }

    //java对象转map
    public static Map<String, Object> BeanMapObjectToMap(Object obj) {
        Map<String, Object> map = Maps.newHashMap();
        if (obj != null) {
            BeanMap beanMap = BeanMap.create(obj);
            for (Object key : beanMap.keySet()) {
                map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }


        LTDemo ltDemo = beanMapMapToObject(map, LTDemo.class);
        Map demoMap = beanMapObjectToMap(ltDemo);
        System.out.println("输出map -> bean: " + ltDemo.toString());
        System.out.println("输出bean -> map : " + demoMap);
        System.out.println(ltDemo.getApplyTime());
        System.out.println(ltDemo.getChildren());
        ltDemo.getChildren().forEach(children -> System.out.println(children.toString()));

输出原生map: {address=上海市, children=[{address=上海市, name=小张, apply_time=Fri Mar 03 17:12:45 CST 2023, age=2}], name=张三, apply_time=Fri Mar 03 17:12:45 CST 2023, age=20}
输出map -> bean: LTDemo(name=张三, age=20, address=上海市, applyTime=null, children=[{address=上海市, name=小张, apply_time=Fri Mar 03 17:12:45 CST 2023, age=2}])
输出bean -> map : {address=上海市, children=[{address=上海市, name=小张, apply_time=Fri Mar 03 17:12:45 CST 2023, age=2}], name=张三, applyTime=null, age=20}
null
[{address=上海市, name=小张, apply_time=Fri Mar 03 17:12:45 CST 2023, age=2}]
Exception in thread "main" java.lang.ClassCastException: java.util.HashMap cannot be cast to com.example.demo.map2bean.LTDemo
	at java.util.ArrayList.forEach(ArrayList.java:1259)
	at com.example.demo.map2bean.MapToBean.main(MapToBean.java:75)

五、reflect 反射来玩 不太好玩

    //-------------------   reflect     -------------------
    //map转java对象
    public static Object reflectMapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null) {
            return null;
        }
        Object object = beanClass.newInstance();
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isFinal(mod) || Modifier.isStatic(mod)) {
                continue;
            }
            field.setAccessible(true);
            field.set(object, map.get(field.getName()));
        }
        return object;
    }

    //java对象转map
    public static Map<String, Object> reflectObjectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }
        LTDemo ltDemo = reflectMapToObject(map,LTDemo.class);
        Map demoMap = reflectObjectToMap(ltDemo);
        System.out.println("输出map -> bean: " + ltDemo.toString());
        System.out.println("输出bean -> map : " + demoMap);
        System.out.println(ltDemo.getApplyTime());
        System.out.println(ltDemo.getChildren());
        ltDemo.getChildren().forEach(children -> System.out.println(children.toString()));
输出原生map: {address=上海市, children=[{address=上海市, name=小张, apply_time=Fri Mar 03 17:16:35 CST 2023, age=2}], name=张三, apply_time=Fri Mar 03 17:16:35 CST 2023, age=20}
输出map -> bean: LTDemo(name=张三, age=20, address=上海市, applyTime=null, children=[{address=上海市, name=小张, apply_time=Fri Mar 03 17:16:35 CST 2023, age=2}])
输出bean -> map : {address=上海市, children=[{address=上海市, name=小张, apply_time=Fri Mar 03 17:16:35 CST 2023, age=2}], name=张三, applyTime=null, age=20}
null
[{address=上海市, name=小张, apply_time=Fri Mar 03 17:16:35 CST 2023, age=2}]
Exception in thread "main" java.lang.ClassCastException: java.util.HashMap cannot be cast to com.example.demo.map2bean.LTDemo
	at java.util.ArrayList.forEach(ArrayList.java:1259)
	at com.example.demo.map2bean.MapToBean.main(MapToBean.java:84)

六、Introspector类 不太好用

这个用起来,只能转换第一层,而且不支持蛇型转驼峰


import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;

 //----------------- Introspector    ------------------

    //map转java对象
    public static <T> T introspector_mapToObject(Map<String, Object> map, Class<T> clazz) throws Exception {
        if (map == null) {
            return null;
        }
        T bean = clazz.newInstance();
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            Method setter = property.getWriteMethod();
            if (setter != null) {
                setter.invoke(bean, map.get(property.getName()));
            }
        }
        return bean;
    }

    //java对象转map
    public static Map<String, Object> introspector_objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo
                .getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (key.compareToIgnoreCase("class") == 0) {
                continue;
            }
            Method getter = property.getReadMethod();
            Object value = getter != null ? getter.invoke(obj) : null;
            map.put(key, value);
        }
        return map;
    }
        LTDemo ltDemo = introspector_mapToObject(map, LTDemo.class);
        Map demoMap = introspector_objectToMap(ltDemo);
        System.out.println("输出map -> bean: " + ltDemo.toString());
        System.out.println("输出bean -> map : " + demoMap);

        System.out.println(ltDemo.getApplyTime());

        System.out.println(ltDemo.getChildren());

        System.out.println(ltDemo.getChildren().get(0).toString());

输出原生map: {address=上海市, children=[{address=上海市, name=小张, apply_time=Fri Mar 03 16:56:37 CST 2023, age=2}], name=张三, apply_time=Fri Mar 03 16:56:37 CST 2023, age=20}
输出map -> bean: LTDemo(name=张三, age=20, address=上海市, applyTime=null, children=[{address=上海市, name=小张, apply_time=Fri Mar 03 16:56:37 CST 2023, age=2}])
输出bean -> map : {address=上海市, children=[{address=上海市, name=小张, apply_time=Fri Mar 03 16:56:37 CST 2023, age=2}], name=张三, applyTime=null, age=20}
null
[{address=上海市, name=小张, apply_time=Fri Mar 03 16:56:37 CST 2023, age=2}]
Exception in thread "main" java.lang.ClassCastException: java.util.HashMap cannot be cast to com.example.demo.map2bean.LTDemo
	at com.example.demo.map2bean.MapToBean.main(MapToBean.java:65)

总结

不想说啥…看着用吧