「Java 开发实例」对象转Map与map转对象 的 5 种方法

850 阅读2分钟

废话不多说系列,直接开搞 ~

美女2.png

一、使用 org.apache.commons.beanutils 进行转换

public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {    
    if (map == null)  
        return null;  

    Object obj = beanClass.newInstance();  

    org.apache.commons.beanutils.BeanUtils.populate(obj, map);  

    return obj;  
}    

public static Map<?, ?> objectToMap(Object obj) {  
    if(obj == null)  
        return null;   

    return new org.apache.commons.beanutils.BeanMap(obj);  
}

二、使用 Introspector 进行转换

import lombok.Data;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class test {

    @Data
    static
    class User {
        private Integer id;
        private String name;
    }

    public static void main(String[] args) {
        Map<String, Object> am = new HashMap<>();
        am.put("id", 23);
        am.put("name", "Drew");

        try {
            // 测试  map → object
            User user = (User) mapToObject(am, User.class);
            System.out.println(user);
            // 测试 object → map
            Map<String, Object> result = objectToMap(user);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * map转对象类
     *
     * @param map       目标map集合
     * @param beanClass 实体对象
     * @return 对象
     * @throws Exception
     */
    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null) {
            return null;
        }
        Object obj = beanClass.newInstance();
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            Method setter = property.getWriteMethod();
            if (setter != null) {
                setter.invoke(obj, map.get(property.getName()));
            }
        }
        return obj;
    }

    /**
     * 对象 转 map
     *
     * @param obj 对象
     * @return map集合
     * @throws Exception
     */
    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();

        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;
    }
}

image.png

三、使用 reflect 进行转换

import lombok.Data;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

public class Test {

    @Data
    static
    class User {
        private Integer id;
        private String name;
    }

    public static void main(String[] args) {
        Map<String, Object> am = new HashMap<>();
        am.put("id", 23);
        am.put("name", "Drew");

        try {
            // 测试  map → object
            User user = (User) mapToObject(am, User.class);
            System.out.println(user);
            // 测试 object → map
            Map<String, Object> result = objectToMap(user);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * map 转 对象
     *
     * @param map       目标map
     * @param beanClass 对象类
     * @return 对象
     * @throws Exception
     */
    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null) {
            return null;
        }
        Object obj = beanClass.newInstance();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }
            field.setAccessible(true);
            field.set(obj, map.get(field.getName()));
        }
        return obj;
    }

    /**
     * 对象 转 map
     *
     * @param obj 对象类
     * @return map
     * @throws Exception
     */
    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>(16);
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }
}

四、利用 Fastjson 转对象

(1)引入 Fastjson 依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.76</version>
</dependency>
(2)使用示例
@Data
@NoArgsConstructor
@AllArgsConstructor
static class User {
    private Integer id;
    private String name;
}

	/**
     * 单个对象转map
     * @param User 对象集合
     * @return map对象
     */
public static Map<String, String> objectSingleToMap(User User) {
    // 核心:通过转成JSON字符串,再来转成Map
    Map<String, String> resultMap = JSON.parseObject(JSON.toJSONString(User), new TypeReference<Map<String, String>>() {
    });

    // 输出 resultMap (迭代器输出 map键值对)
    Iterator<Map.Entry<String, String>> iterator = resultMap.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, String> ent = iterator.next();
        String value = ent.getValue();
        String key = ent.getKey();
        System.out.println(key + " : " + value);
    }
    return resultMap;
}

五、Java8 对象转Map

@Data
public class User {
    private Integer id;
    private String name;
    private String age;
}

// 演示接口案例
public void testObj2Map() {
    // 用户ID -> 用户信息
    Map<Integer, User> baseEntryCompanyMap = entryCompanyService.selectList(new EntityWrapper<>())
        .stream().collect(
        Collectors.toMap(
            User::getId, // map 的 key
            i1 -> i1, // map 的 value
            (i1, i2) -> i1  // 映射关系
        )
    );

    // 用户ID -> 用户名称
    Map<Integer, String> userInfo = userService.selectList(new EntityWrapper<>())
        .stream().collect(Collectors.toMap(User::getId, User::getName, (i1, i2) -> i1));
}

至此,感谢阅读!🙏

美女2.png