依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
工具类(直接上代码):
package com.itheima.common.util;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.PropertyUtils;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
/**
* 。
* (1) 使用泛型方法:把json字符串转换为相应的JavaBean对象;
* 转换为普通JavaBean:readValue(json,Student.class);
* (2) List Map转换List 对象:如List<Student>,将第二个参数传递为Student;
* (3) List 对象转换List Map:
* [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List;
*
* @param jsonStr
* @param valueType
* @return
*
*/
public final class JsonUtils {
private static ObjectMapper objectMapper;
/**
* (1) 使用泛型方法:把json字符串转换为相应的JavaBean对象;
* 转换为普通JavaBean:readValue(json,Student.class);
*/
public static <T> T readValue(String jsonStr, Class<T> valueType) throws Exception {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
return objectMapper.readValue(jsonStr, valueType);
}
/**
*(2).List Map转换List 对象:如List<Student>,将第二个参数传递为Student对象;
* map转换为bean
*/
public static Object mapToObject(Map<String, String> 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;
}
/**
*(3).List 对象转换List Map:
* [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List;
* bean转换为map
*/
public static <T> List<Map<String, Object>> listConvert(List<T> list){
List<Map<String, Object>> list_map = new ArrayList<Map<String, Object>>();
if (CollectionUtils.isNotEmpty(list)) {
list.forEach(item ->{
Map<String, Object> map = null;
try {
map = PropertyUtils.describe(item);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
list_map.add(map);
});
}
return list_map;
}
}
使用场景:
(1).使用泛型方法:把json字符串转换为相应的JavaBean对象 ;
一般用于:Controller层:
例如:
/**
* 保存:表单数据(保存和修改功能)
* 权限-管理员&专员
*
* @param param
* @return
*/
@PostMapping(value = "/saveFormData")
@AuthInterceptor("mag:XXlist:saveFormData")
public Result saveFormData(HttpServletRequest request,@RequestBody String param) {
try {
Map<String, Object> paramMap = JsonUtils.readValue(param, Map.class);
String refreshToken = request.getHeader("refreshToken");
Map<String, Object> current= tokenCache.getCurrentUsers(refreshToken);
paramMap.put("createdNo",current.get("pmNo"));
paramMap.put("createdBy",current.get("pmName"));
return ListService.saveFormData(paramMap);
} catch (Exception e) {
log.error("XXController saveFormData is error===:" + e.getMessage(), e);
return Result.failure("表单数据保存失败!");
}
}
(2).List Map转换List 对象:如List,将第二个参数传递为Student对象;
public Result addTask(@RequestBody String param) {
try {
List<Map<String, String>> params = JsonUtils.readValue(param, List.class);
//map转化为对象
StudentVo studentVo = (StudentVo)
JsonUtils.mapToObject(params.get(0), StudentVo.class);
//代码省略......
return Result.success().result("任务添加成功");
} catch (Exception e) {
log.error("===XXController addTask is error===:" + e.getMessage(), e);
return Result.failure(e.getMessage());
}
}
(3).List 对象转换List Map:
private List<Map<String, Object>> getHeaderssData() {
QueryWrapper<ListFormTableVo> qw = new QueryWrapper<ListFormTableVo>();
qw.orderByAsc("id");
List<ListFormTableVo> list = ListFormTemplateMapper.selectList(qw);
//List对象转化为List Map
List<Map<String, Object>> res = JsonUtils.listConvert(list);
res = res.stream().filter(e -> (!e.get("headerField").equals("pmNo"))).
filter(e -> (!e.get("headerField").equals("pmName"))).
collect(Collectors.toList());
return res;
}