java map转对象

时间:2025-02-16 10:47:38

原文地址:
/code/view/1423280939826

1.使用使用进行转换,该方式可以把继承自父类的属性字段也进行赋值,靠谱.

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

        Object obj = ();  

        (obj, map);  

        return obj;  
    }    

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

        return new (obj);  
    }    

2.使用java的reflect进行转换,转换后的对象继承父类的字段没有正确赋值

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

        Object obj = ();  

        Field[] fields = ().getDeclaredFields();   
        for (Field field : fields) {    
            int mod = ();    
            if((mod) || (mod)){    
                continue;    
            }    

            (true);    
            (obj, (()));   
        }   

        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>();    

        Field[] declaredFields = ().getDeclaredFields();    
        for (Field field : declaredFields) {    
            (true);  
            ((), (obj));  
        }    

        return map;  
    }   

3.结束