商品业务对象定义:Product
Product product = new Product();
product.setId(1L);
product.setName("爱他美")
product.setProductDt("2022-03-16")
第一种:通过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(product), Map.class);
Map<String,Object> map = JSONObject.parseObject(JSON.toJSONString(product));
//Map转Object
Product productDto1 = JSON.parseObject(JSON.toJSONString(map), Product.class);
Product productDto2 = JSONObject.toJavaObject(JSON.toJSONString(map), Product.class);
第二种:通过SpringBoot自带 Jackso实现
一般情况下我们引入MVC,MVC里面帮我们引入了Jackso依赖
<!-- springboot web(MVC)-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
最终的依赖:
ObjectMapper mapper = new ObjectMapper();
//对象转map
Map m = mapper.readValue(mapper.writeValueAsString(product), Map.class);
//map转对象
Product dto = mapper.readValue(mapper.writeValueAsString(m), Product.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(product);
#使用org.apache.commons.beanutils.BeanUtils将map转为对象
BeanUtils.populate(product, 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;
}
|