Java map和bean互转常用的方法总结

 更新时间:2023年09月22日 10:40:03   作者:我老菜  
这篇文章主要给大家介绍了关于Java中map和bean互转常用方法的相关资料,平时日常Java开发,经常会涉及到Java Bean和Map之间的类型转换,需要的朋友可以参考下

一、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)

总结

到此这篇关于Java map和bean互转常用方法的文章就介绍到这了,更多相关Java map和bean互转内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java中Lambda表达式用法介绍

    Java中Lambda表达式用法介绍

    本文详细讲解了Java中Lambda表达式的用法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-12-12
  • 防止未登录用户操作—基于struts2拦截器的简单实现

    防止未登录用户操作—基于struts2拦截器的简单实现

    下面小编就为大家带来一篇防止未登录用户操作—基于struts2拦截器的简单实现。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • java类Circle定义计算圆的面积和周长代码示例

    java类Circle定义计算圆的面积和周长代码示例

    要用Java计算圆的周长和面积,需要使用圆的半径和一些数学公式,下面这篇文章主要给大家介绍了关于java类Circle定义计算圆的面积、周长的相关资料,需要的朋友可以参考下
    2024-04-04
  • 最全MyBatis核心配置文件总结(收藏)

    最全MyBatis核心配置文件总结(收藏)

    这篇文章主要介绍了最全MyBatis核心配置文件总结(收藏),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • SpringBoot+Vue+Element-ui实现前后端分离

    SpringBoot+Vue+Element-ui实现前后端分离

    使用前后端分离的方式,可以减少代码耦合,本文主要介绍了SpringBoot+Vue+Element-ui实现前后端分离,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-06-06
  • RocketMq深入分析讲解两种削峰方式

    RocketMq深入分析讲解两种削峰方式

    当上游调用下游服务速率高于下游服务接口QPS时,那么如果不对调用速率进行控制,那么会发生很多失败请求,通过消息队列的削峰方法有两种,这篇文章主要介绍了RocketMq深入分析讲解两种削峰方式
    2023-01-01
  • 浅谈MyBatis通用Mapper实现原理

    浅谈MyBatis通用Mapper实现原理

    这篇文章主要介绍了浅谈MyBatis通用Mapper实现原理,本文会先介绍通用 Mapper 的简单原理,然后使用最简单的代码来实现这个过程。感兴趣的小伙伴们可以参考一下
    2018-10-10
  • 基于Spring Cache实现Caffeine+Redis二级缓存

    基于Spring Cache实现Caffeine+Redis二级缓存

    本文主要介绍了基于Spring Cache实现Caffeine+Redis二级缓存,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • Servlet生命周期与工作原理详解

    Servlet生命周期与工作原理详解

    这篇文章主要为大家详细介绍了Servlet生命周期与工作原理的相关资料,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-04-04
  • Sentinel源码解析入口类和SlotChain构建过程详解

    Sentinel源码解析入口类和SlotChain构建过程详解

    这篇文章主要为大家介绍了Sentinel源码解析入口类和SlotChain构建过程详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09

最新评论