学生业务对象定义:Student
Student student = new Student();
student.setId(1L);
student.setName("令狐冲")
student.setAge(10)
com.alibaba
fastjson
1.2.66
//Object转Map
Map map = JSONObject.parseObject(JSONObject.toJSONString(student), Map.class);
Map map = JSONObject.parseObject(JSON.toJSONString(student));
//Map转Object
Student s1 = JSON.parseObject(JSON.toJSONString(map), Student.class);
Student s2 = JSONObject.toJavaObject(JSON.toJSONString(map), Student.class);
一般情况下我们引入MVC,MVC里面帮我们引入了Jackso依赖
org.springframework.boot
spring-boot-starter-web
最终的依赖:
ObjectMapper mapper = new ObjectMapper();
//对象转map
Map m = mapper.readValue(mapper.writeValueAsString(student), Map.class);
//map转对象
Student s = mapper.readValue(mapper.writeValueAsString(m), Student.class);
commons-beanutils
commons-beanutils
1.9.3
#使用org.apache.commons.beanutils.BeanMap进行转换,实现Bean转Map
Map map = new org.apache.commons.beanutils.BeanMap(student);
#使用org.apache.commons.beanutils.BeanUtils将map转为对象
BeanUtils.populate(student, map);
//Object转Map
public static Map getObjectToMap(Object obj) throws IllegalAccessException {
Map map = new LinkedHashMap();
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;
}
//Map转Object
public static Object mapToObject(Map