递归实现MorphDynaBean 转换为Map

String requestData = StreamUtils.copyToString(servletRequest.getInputStream(), StandardCharsets.UTF_8);
Map param = (Map) JSONObject.toBean(new JSONObject().fromObject(requestData), Map.class);
Map<String, Object> data = (Map<String, Object>) param.get("data");

如上即为在过滤器中获取请求的参数,将其转换为Map<String,Object类型>,如果是寻常的格式则可以正常解析,但是遇到Map嵌套的情况,则不支持。

如下为Map嵌套的情况:

{
    "organId": "123",
    "data": {
        "data1": [
            {
                "pay_app_no ": "202301",
                "status": "100",
                "hold1": "202301"
            }
        ],
        "summary": "0f0c4ed5c6cdd164dc6aaa5308605f6144",
        "fiscalYear": "2023"
    }
}

按照上面的代码,会将data解析成MorphDynaBean 类型,强制转换会报错。

因此需要手动实现,主要通过递归的思想,具体代码如下:

Map<String, Object> data = convertDynaBeanToMap(param.get("data"));
 /**
     * 递归处理复杂MorphDynaBean对象,将其转为map
     * @param obj
     * @return
     */
    public static Map<String, Object> convertDynaBeanToMap(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj instanceof Map) {
            Map<String, Object> data = new HashMap<>();
            for (Map.Entry<?, ?> entry : ((Map<?, ?>) obj).entrySet()) {
                String key = String.valueOf(entry.getKey());
                Object value = entry.getValue();
                if (value instanceof MorphDynaBean) {
                    value = convertDynaBeanToMap(value);
                }
                data.put(key, value);
            }
            return data;
        }
        if (obj instanceof MorphDynaBean) {
            MorphDynaBean dynaBean = (MorphDynaBean) obj;
            Map<String, Object> data = new HashMap<>();
            DynaProperty[] props = dynaBean.getDynaClass().getDynaProperties();
            for (DynaProperty prop : props) {
                String name = prop.getName();
                Object value = dynaBean.get(name);
                if (value instanceof MorphDynaBean) {
                    value = convertDynaBeanToMap(value);
                }
                if(value instanceof List){
                    List<Map<String, Object>> list = new ArrayList<>();
                    for (Object item : (List<?>) value) {
                        if (item instanceof MorphDynaBean) {
                            item = convertDynaBeanToMap(item);
                        }
                        if (item instanceof Map) {
                            list.add((Map<String, Object>) item);
                        }
                    }
                    value = list;
                }
                data.put(name, value);
            }
            return data;
        }
        throw new IllegalArgumentException("Unsupported object type: " + obj.getClass());
    }

 

posted @ 2023-06-27 14:17  雪山上的蒲公英  阅读(288)  评论(0编辑  收藏  举报
/* 返回顶部代码 */