学生业务对象定义:Student
java
Student student = new Student();
student.setId(1L);
student.setName("令狐冲")
student.setAge(10)
第一种:通过Alibaba Fastjson实现
pom.xml 文件依赖
java
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.66</version>
</dependency>
代码实现
java
//Object转Map
Map map = JSONObject.parseObject(JSONObject.toJSONString(student), Map.class);
Map<String,Object> 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);
第二种:通过SpringBoot自带 Jackso实现
一般情况下我们引入MVC,MVC里面帮我们引入了Jackso依赖
导入依赖
XML
<!-- springboot web(MVC)-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
最终的依赖:
代码实现
java
ObjectMapper mapper = new ObjectMapper();
//对象转map
Map m = mapper.readValue(mapper.writeValueAsString(student), Map.class);
//map转对象
Student s = mapper.readValue(mapper.writeValueAsString(m), Student.class);
第三种:通过Apache common Bean工具类实现
pom.xml文件依赖
XML
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
代码实现
java
#使用org.apache.commons.beanutils.BeanMap进行转换,实现Bean转Map
Map<String, Object> map = new org.apache.commons.beanutils.BeanMap(student);
#使用org.apache.commons.beanutils.BeanUtils将map转为对象
BeanUtils.populate(student, map);
第四种: 通过反射实现
通过反射实现Bean 转Map
java
//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;
}
通过反射实现Map转Bean
java
//Map转Object
public static Object mapToObject(Map<Object, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;
Object 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;
}