java中map和对象互转的方法总结----MapUtils工具类

package com.eco.business.marketing.model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eco.base.util.StringUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

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

public class MapUtils {
    //方法001
    //json的转换
    private static <T> T mapTodata(Map<String ,Object> map, Class<T> obj) throws Exception {
        T instance = null;
        Map<String, Method> methodMap = new HashMap<>();
        //获取类中声明的所有字段
        Field[] fields = obj.getDeclaredFields();
        //创建新的实例对象
        Map<String, Object> meMap = new HashMap<>();
        //利用循环
        for (int i = 0; i < fields.length; i++) {
            //获取字段的名称
            String name = fields[i].getName();
            //把序列化id筛选掉
            if (name.equals("serialVersionUID")) {
                continue;
            }
            // 首字母大写
            String replace = name.substring(0, 1).toUpperCase() + name.substring(1);
            Method setMethod = methodMap.get("set" + replace);
            Object strObject = map.get(name);
            String str = strObject == null ? "" : strObject.toString();
            if (str != null && !"".equals(str) && StringUtil.isNotEmpty(str) && setMethod!=null) {
                meMap.put(name, str);
            }
        }
        try{
            //instance = obj.newInstance();
            //返回实体类对象
            instance= JSON.parseObject(JSON.toJSONString(meMap), obj);
            //另外一种方法  ---org.apache.commons.beanutils.BeanUtils.populate(obj, map);
            return instance;
        }catch (Exception e){
            throw new Exception("对象转换失败");
        }
    }
    private static Map<String,Object> dataToMap(Object obj){
        Map<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(obj), Map.class);
        return map;
    }
    //方法002
    //遍历对象所有的字段
    //Map转Object
    public static <T> T mapToObject(Map<Object, Object> map, Class<T> beanClass) throws Exception {
        if (map == null)
            return null;
        T 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);
            if (map.containsKey(field.getName())) {
                field.set(obj, map.get(field.getName()));
            }
        }
        return obj;
    }
    //Object转Map
    public static Map<String, Object> getObjectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        Class<?> clazz = obj.getClass();
        System.out.println(clazz);
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            if (value == null){
                value = "";
            }
            map.put(fieldName, value);
        }
        return map;
    }
    //方法003
    //使用 com.fasterxml.jackson.databind.ObjectMapper 进行转换
    public static <T> T mapFoObject (Map<String, Object> map, Class<T> beanClass) throws Exception {
        if (map == null) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        T obj = objectMapper.convertValue(map, beanClass);
        return obj;
    }
    public static Map<?, ?> objectFoMap (Object obj) {
        if (obj == null) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        Map<?, ?> mappedObject = objectMapper.convertValue(obj, Map.class);
        return mappedObject;
    }
    //方法004
    //使用 org.apache.commons.beanutils 进行转换
    public static <T> T mapToObj(Map<String, Object> map, Class<T> beanClass) throws Exception {
        if (map == null) {
            return null;
        }
        T obj = beanClass.newInstance();
        org.apache.commons.beanutils.BeanUtils.populate(obj, map);
        return obj;
    }
    public static Map<?, ?> objToMap(Object obj) {
        if (obj == null) {
            return null;
        }
        return new org.apache.commons.beanutils.BeanMap(obj);
    }
    //方法005
    //使用 Introspector 进行转换
    public static <T> T  mapToObjecta(Map<String, Object> map, Class<T> beanClass) throws Exception {
        if (map == null) {
            return null;
        }
        T 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;
    }
    public static Map<String, Object> 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;
    }
    //方法006
    //使用 reflect 进行转换
    public static <T> T  mapToObjectb(Map<String, Object> map, Class<T> beanClass) throws Exception {
        if (map == null) {
            return null;
        }
        T 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;
    }
    public static Map<String, Object> objectToMapb(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;
    }

    /**
     * 将map的value值转为实体类中字段类型匹配的方法
     * @param value
     * @param fieldTypeClass
     * @return
     */
    private static Object convertValType(Object value, Class<?> fieldTypeClass) {
        Object retVal = null;
        if (Long.class.getName().equals(fieldTypeClass.getName())
                || long.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Long.parseLong(value.toString());
        } else if (Integer.class.getName().equals(fieldTypeClass.getName())
                || int.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Integer.parseInt(value.toString());
        } else if (Float.class.getName().equals(fieldTypeClass.getName())
                || float.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Float.parseFloat(value.toString());
        } else if (Double.class.getName().equals(fieldTypeClass.getName())
                || double.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Double.parseDouble(value.toString());
        } else {
            retVal = value;
        }
        return retVal;
    }

}

 

下划线命名 转 驼峰命名
  /**
     * 功能:下划线命名 转 驼峰命名
     * 将下划线替换为空格,将字符串根据空格分割成数组,再将每个单词首字母大写
     * @param  para
     * @return String
     */
    public static String Underline(String para){
        if(StringUtil.isNotEmpty(para)){
            String res = para.toLowerCase();
            StringBuffer stringBuffer = new StringBuffer();
            Boolean re= res.lastIndexOf("_") == res.length() - 1;
            if(re){
                res = res.substring(0, res.length() -1);
            }
            String a[]=res.split("_");
            for(String s:a){
                if(stringBuffer.length()==0){
                    stringBuffer.append(s.toLowerCase());
                }else{
                    stringBuffer.append(s.substring(0, 1).toUpperCase());
                    stringBuffer.append(s.substring(1).toLowerCase());
                }
            }
          return stringBuffer.toString();
        }else {
            return "";
        }

    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值