public static <T> T convertJsonRequestToVo(HttpServletRequest request, Class<T> voClass) throws Exception {
request.setCharacterEncoding("utf-8");
String requestBody = HttpServletRequestUtil.readHttpServletRequestBody(request);
Map<String, Object> requestMap = (Map<String, Object>) JSON.parse(requestBody);
return convertMapToVo(requestMap, voClass);
}
public static <T> T convertMapToVo(Map<String, Object> map, Class<T> voClass) throws Exception {
T obj = voClass.newInstance();
if (map.isEmpty())
return obj;
BeanWrapper beanWrapper = new BeanWrapperImpl(obj);
List<String> fieldList = Stream.of(voClass.getDeclaredFields())
.map(Field::getName)
.collect(Collectors.toList());
fieldList.addAll(Stream.of(voClass.getSuperclass().getDeclaredFields())
.map(Field::getName)
.collect(Collectors.toList()));
for (Map.Entry<String, Object> entry : map.entrySet())
if (!StringUtils.isEmpty(String.valueOf(entry.getValue())))
if (fieldList.contains(entry.getKey()))
beanWrapper.setPropertyValue(entry.getKey(), entry.getValue());
return obj;
}
参考资料:
1、java反射以获取父类属性的值
2、 Java-Reflection反射-获取包括父类在内的所有字段