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反射-获取包括父类在内的所有字段



阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Java