Java中如何优雅的把Map转为对象

在项目开发中,经常碰到map转实体对象或者对象转map的场景,工作中,很多时候我们可能比较喜欢使用第三方jar包的API对他们进行转化,而且用起来也还算方便,比如像fastJson就可以轻松实现map和对象的互转,但这里,我想通过反射的方式对他们做转化,也算是对反射的学习和研究吧;

1、map转java对象

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mes.common.core.utils.StringUtils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
     * @Author: best_liu
     * @Description: map转java对象
     * @Date: 8:35 2022/3/22
     **/
    public static Object convertToObject(Class clazz, Map map) throws
            IntrospectionException, InstantiationException, IllegalAccessException {
        BeanInfo bi = Introspector.getBeanInfo(clazz);

        Object obj = clazz.newInstance();

        PropertyDescriptor[] pds = bi.getPropertyDescriptors();

        String pName;
        for (PropertyDescriptor pd : pds) {
            pName = pd.getName();
            if (map.containsKey(pName)) {
                try {
                    if (pd.getPropertyType().getName().equals("java.lang.Long")) {
                        if(StringUtils.isNotEmpty(map.get(pName).toString())){
                            pd.getWriteMethod().invoke(obj, Long.parseLong(map.get(pName).toString()));
                        }
//                        else{
//                            pd.getWriteMethod().invoke(obj, map.get(pName));
//                        }

                    } else {
                        pd.getWriteMethod().invoke(obj, map.get(pName));
                    }
                } catch (Exception ex) {
                    Logger.getLogger(MapUtil.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        return obj;
    }

2、java对象转map

/**
     * @Author: best_liu
     * @Description: java对象转map
     * @Date: 8:35 2022/3/22
     **/
    public static Map objectToMap(Object obj) {
        if (obj == null) {
            return null;
        }

        Map map = new HashMap();
        try {
            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;
                String v = null;
                if (value != null) {
                    v = value.toString();
                }
                map.put(key, v);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * @Author: best_liu
     * @Description: java对象转map
     * @Date: 8:35 2022/3/22
     **/
    public static Map objectToMapObj(Object obj) {
        if (obj == null) {
            return null;
        }

        Map map = new HashMap();
        try {
            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);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

3、Map转换为Json字符串

 /**
     * @Author: best_liu
     * @Description: Map转换为Json字符串
     * @Date: 8:35 2022/3/22
     **/
    public static String mapToJsonString(Map map) {
        JSONObject json = new JSONObject();
        Iterator> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = entries.next();
            json.put(entry.getKey(), entry.getValue());
        }
        return json.toString();
    }

4、Json字符串转换为Map

/**
     * @Author: best_liu
     * @Description: Json字符串转换为Map
     * @Date: 8:35 2022/3/22
     **/
    public static Map jsonStringToMap(String str) {
        Map map = (Map) JSON.parse(str);
        return map;
    }

你可能感兴趣的:(java,spring,spring,boot)