BeanUtils 实现 Map 与 Bean 进行相互转换

基本使用

Map -> Bean

BeanUtils.populate(Object bean, Map<String, ? extends Object> properties);

Bean -> Map

BeanMap testMap = new BeanMap(Object bean);

需要添加的 Maven 依赖

<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.3</version>
</dependency>

案例

public class MapBeanConvert {

    public static void main(String[] args) throws Exception {
        User user = new User();
        Map<String, Object> map = new HashMap<>();
        map.put("name", "Joe.Ye");
        map.put("home", "http://www.appblog.cn");
        map.put("city", "HZ");
        map.put("age", 25);
        BeanUtils.populate(user, map);
        System.out.println(JSON.toJSONString(user));

        BeanMap beanMap = new BeanMap(user);
        System.out.println(JSON.toJSONString(beanMap));
    }

    public static class User {
        String name;
        String home;
        int age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getHome() {
            return home;
        }

        public void setHome(String home) {
            this.home = home;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}
{"age":25,"home":"http://www.appblog.cn","name":"Joe.Ye"}
{"name":"Joe.Ye","class":"com.lianlian.global.pay.test.MapBeanConvert$User","age":25,"home":"http://www.appblog.cn"}

功能封装

bean 转换成 map

private Map<String, String> bean2Map(Object object) {
    Map<String, String> map = null;
    try {
        map = BeanUtils.describe(object);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return map;
}

private BeanMap bean2Map(Object object) {
    return new BeanMap(object);
}

map 转换成 bean

private static <T> T map2Bean(Map<String, String> map, Class<T> clazz) {
    T bean = null;
    try {
        bean = clazz.newInstance();
        BeanUtils.populate(bean, map);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bean;
}

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/02/25/beanutils-implement-conversion-between-map-and-bean/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
BeanUtils 实现 Map 与 Bean 进行相互转换
基本使用 Map -> Bean BeanUtils.populate(Object bean, Map<String, ? extends Object> properties); Bean -> Map BeanMap testMap = new BeanM……
<<上一篇
下一篇>>
文章目录
关闭
目 录