学生业务对象定义:Student
Student student = new Student();
student.setId(1L);
student.setName("令狐冲")
student.setAge(10)
第一种:通过Alibaba Fastjson实现
pom.xml 文件依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.66</version>
</dependency>
代码实现
//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依赖
导入依赖
<!-- springboot web(MVC)-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
最终的依赖:文章来源:https://www.toymoban.com/news/detail-633428.html
文章来源地址https://www.toymoban.com/news/detail-633428.html
代码实现
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文件依赖
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
代码实现
#使用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
//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
//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;
}
到了这里,关于Object & Map 的相互转换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!