map与java对象的相互转换
1. 使用org.apache.commons.beanutils转换
pom.xml
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
//map转java对象
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass)
throws Exception {
if (map == null) {
return null;
}
Object obj = beanClass.newInstance();
BeanUtils.populate(obj, map);
return obj;
}
//java对象转map
public static Map<?, ?> objectToMap(Object obj) {
if (obj == null)
return null;
return new BeanMap(obj);
}
可能出现的错误
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections/Transformer
解决方法案例
package com.example2.pojo;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils.BeanMap;
public class PojoToMap {
/**
* @param args
*/
public static void main(String[] args) {
Employee employee = new Employee();
employee.setName("张三");
employee.setAge(30);
Map map;
try {
map = objectToMap(employee);
Set<Map.Entry<String, Object>> set = map.entrySet();
for (Map.Entry<String, Object> entry : set) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static Map<?, ?> objectToMap(Object obj) {
if (obj == null)
return null;
return new BeanMap(obj);
}
}
package com.example2.pojo;
public class Employee {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
从报错信息上看,是缺少了org.apache.commons.collections.Transformer类,网上下载了commons-collections-3.2.1.jar包,引入后,重新执行,即可。
2. 使用Introspector转换
//map转java对象
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;
}
//java对象转map
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;
}
3. 使用reflect转换
//map转java对象
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null) {
return null;
}
Object object = beanClass.newInstance();
Field[] fields = beanClass.getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isFinal(mod) || Modifier.isStatic(mod)) {
continue;
}
field.setAccessible(true);
field.set(object, map.get(field.getName()));
}
return object;
}
//java对象转map
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 = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
}
4. 使用net.sf.cglib.beans.BeanMap转换
//map转java对象
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
Object object = beanClass.newInstance();
BeanMap beanMap = BeanMap.create(object);
beanMap.putAll(map);
return object;
}
//java对象转map
public static Map<String, Object> objectToMap(Object obj) {
Map<String, Object> map = Maps.newHashMap();
if (obj != null) {
BeanMap beanMap = BeanMap.create(obj);
for (Object key : beanMap.keySet()) {
map.put(key + "", beanMap.get(key));
}
}
return map;
}
可能出现的错误
Exception in thread "main" java.lang.NoClassDefFoundError: org/objectweb/asm/Type
解决案例
package com.example2.pojo;
import java.util.HashMap;
import java.util.Map;
import net.sf.cglib.beans.BeanMap;
public class MapToPojo {
/**
* @param args
*/
public static void main(String[] args) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "张三");
map.put("age", 30);
try {
Employee employee = (Employee) mapToBean(map, Employee.class);
System.out.print(employee.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object mapToBean(Map<String, Object> map, Class<?> beanClass) throws Exception {
Object object = beanClass.newInstance();
BeanMap beanMap = BeanMap.create(object);
beanMap.putAll(map);
return object;
}
}
package com.example2.pojo;
public class Employee {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Employee [name=" + name + ", age=" + age + "]";
}
}
从错误信息上看,是缺少了org.objectweb.asm.Type类,那么找一个就OK了,从网上下载了com.springsource.org.objectweb.asm-3.2.0.jar包,引入后,再次执行,即可。
补充:其实项目中已引入的spring-core-4.1.7.RELEASE.jar包中也已经集成了cglib模块,如图:
引用这个包里的BeanMap类也可以,
import org.springframework.cglib.beans.BeanMap;
执行后,达到同样效果。
5. 使用fastjson转换
pom.xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
//map转java对象
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
String jsonStr = JSONObject.toJSONString(map);
return JSONObject.parseObject(jsonStr, beanClass);
}
//java对象转map
public static Map<String, Object> objectToMap(Object obj) {
String jsonStr = JSONObject.toJSONString(obj);
return JSONObject.parseObject(jsonStr);
}
版权声明:本文为qq_40572200原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。