0


常用的map转bean互转方法

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

常用的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=FriMar0317:21:01CST2023, age=2}], name=张三, apply_time=FriMar0317:21:01CST2023, age=20}
输出map -> bean:LTDemo(name=张三, age=20, address=上海市, applyTime=FriMar0317:21:01CST2023, children=[LTDemo(name=小张, age=2, address=上海市, applyTime=FriMar0317:21:01CST2023, children=[])])
输出bean -> map :{name=张三, age=20, address=上海市, applyTime=FriMar0317:21:01CST2023, children=[LTDemo(name=小张, age=2, address=上海市, applyTime=FriMar0317:21:01CST2023, children=[])]}FriMar0317:21:01CST2023[LTDemo(name=小张, age=2, address=上海市, applyTime=FriMar0317:21:01CST2023, children=[])]LTDemo(name=小张, age=2, address=上海市, applyTime=FriMar0317:21:01CST2023, 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=FriMar0317:21:59CST2023, age=2}], name=张三, apply_time=FriMar0317:21:59CST2023, age=20}
输出map -> bean:LTDemo(name=张三, age=20, address=上海市, applyTime=FriMar0317:21:59CST2023, children=[LTDemo(name=小张, age=2, address=上海市, applyTime=FriMar0317:21:59CST2023, children=[])])
输出bean -> map :{address=上海市, children=[{"address":"上海市","children":[],"name":"小张","applyTime":1677835319813,"age":2}], name=张三, applyTime=1677835319813, age=20}FriMar0317:21:59CST2023[LTDemo(name=小张, age=2, address=上海市, applyTime=FriMar0317:21:59CST2023, children=[])]LTDemo(name=小张, age=2, address=上海市, applyTime=FriMar0317:21:59CST2023, children=[])
上海市

三、beanutils_BeanUtils工具类 不太好用

嵌套型map,转换会有问题,且

不支持蛇型转成驼峰
//-------------------    beanutils_BeanUtils  -----------------//map转java对象publicstatic<T>TbeanUtils_mapToObject(Map<String,Object> map,Class<T> clazz)throwsException{if(map ==null){returnnull;}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=FriMar0317:04:38CST2023, children=[{address=上海市, name=小张, applyTime=FriMar0317:04:38CST2023, age=2}])FriMar0317:04:38CST2023Exception in thread "main"java.lang.ClassCastException:java.util.HashMap cannot be cast tocom.example.demo.map2bean.LTDemo
    at com.example.demo.map2bean.MapToBean.main(MapToBean.java:73)

四、cglib BeanMap工具类 不太好用

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

importnet.sf.cglib.beans.BeanMap;// -------------------   cglib BeanMap  -------------------//map对象转javapublicstatic<T>TBeanMapMapToObject(Map<String,Object> map,Class<T> beanClass)throwsException{T object = beanClass.newInstance();BeanMap beanMap =BeanMap.create(object);
        beanMap.putAll(map);return object;}//java对象转mappublicstaticMap<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=FriMar0317:12:45CST2023, age=2}], name=张三, apply_time=FriMar0317:12:45CST2023, age=20}
输出map -> bean:LTDemo(name=张三, age=20, address=上海市, applyTime=null, children=[{address=上海市, name=小张, apply_time=FriMar0317:12:45CST2023, age=2}])
输出bean -> map :{address=上海市, children=[{address=上海市, name=小张, apply_time=FriMar0317:12:45CST2023, age=2}], name=张三, applyTime=null, age=20}null[{address=上海市, name=小张, apply_time=FriMar0317:12:45CST2023, age=2}]Exception in thread "main"java.lang.ClassCastException:java.util.HashMap cannot be cast tocom.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对象publicstaticObjectreflectMapToObject(Map<String,Object> map,Class<?> beanClass)throwsException{if(map ==null){returnnull;}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对象转mappublicstaticMap<String,Object>reflectObjectToMap(Object obj)throwsException{if(obj ==null){returnnull;}Map<String,Object> map =newHashMap<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=FriMar0317:16:35CST2023, age=2}], name=张三, apply_time=FriMar0317:16:35CST2023, age=20}
输出map -> bean:LTDemo(name=张三, age=20, address=上海市, applyTime=null, children=[{address=上海市, name=小张, apply_time=FriMar0317:16:35CST2023, age=2}])
输出bean -> map :{address=上海市, children=[{address=上海市, name=小张, apply_time=FriMar0317:16:35CST2023, age=2}], name=张三, applyTime=null, age=20}null[{address=上海市, name=小张, apply_time=FriMar0317:16:35CST2023, age=2}]Exception in thread "main"java.lang.ClassCastException:java.util.HashMap cannot be cast tocom.example.demo.map2bean.LTDemo
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at com.example.demo.map2bean.MapToBean.main(MapToBean.java:84)

六、Introspector类 不太好用

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

importjava.beans.BeanInfo;importjava.beans.Introspector;importjava.beans.PropertyDescriptor;//----------------- Introspector    ------------------//map转java对象publicstatic<T>Tintrospector_mapToObject(Map<String,Object> map,Class<T> clazz)throwsException{if(map ==null){returnnull;}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对象转mappublicstaticMap<String,Object>introspector_objectToMap(Object obj)throwsException{if(obj ==null){returnnull;}Map<String,Object> map =newHashMap<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=FriMar0316:56:37CST2023, age=2}], name=张三, apply_time=FriMar0316:56:37CST2023, age=20}
输出map -> bean:LTDemo(name=张三, age=20, address=上海市, applyTime=null, children=[{address=上海市, name=小张, apply_time=FriMar0316:56:37CST2023, age=2}])
输出bean -> map :{address=上海市, children=[{address=上海市, name=小张, apply_time=FriMar0316:56:37CST2023, age=2}], name=张三, applyTime=null, age=20}null[{address=上海市, name=小张, apply_time=FriMar0316:56:37CST2023, age=2}]Exception in thread "main"java.lang.ClassCastException:java.util.HashMap cannot be cast tocom.example.demo.map2bean.LTDemo
    at com.example.demo.map2bean.MapToBean.main(MapToBean.java:65)

总结

不想说啥…看着用吧

标签: java servlet 前端

本文转载自: https://blog.csdn.net/qq_37700773/article/details/129323025
版权归原作者 我老菜 所有, 如有侵权,请联系我们删除。

“常用的map转bean互转方法”的评论:

还没有评论