栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA 转换 树结构数据

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA 转换 树结构数据

JAVA 转换 树结构数据

第一步:引入fastjson


    com.alibaba
    fastjson
    ${fastjson.version}

第二步:用到了工具内的JSONPath

JSONPath使用教程

    
    public static  List tree(Object obj, String parentCodeFieldName, String parentCode, String currentCodeFieldName, String childrenFiledName, Class c) {
 long t1 = System.currentTimeMillis();
 String jsonStr = JSON.toJSONString(obj);
 log.debug("树转换开始 >>>>>>>>>>>>>>>> {}", JSON.toJSONString(obj));
 //获取第一层级的数据
 JSonArray jsonArray = (JSONArray) JSONPath.read(jsonStr, "$[" + parentCodeFieldName + "=" + parentCode + "]");
 if (CollectionUtils.isEmpty(jsonArray)) {
     //为空的话直接返回空集合
     return Lists.newArrayList();
 }
 for (int i = 0; i < jsonArray.size(); i++) {
     JSonObject jsonObject = jsonArray.getJSONObject(i);
     String code = jsonObject.getString(currentCodeFieldName);
     treeChildren(jsonStr, jsonObject, parentCodeFieldName, code, currentCodeFieldName, childrenFiledName);
 }
 List list = JSONArray.parseArray(jsonArray.toString(), c);
 log.debug("树转换结束, 转换时间: {} ms . >>>>>>>>>>>>>>>> {}", (System.currentTimeMillis() - t1), JSON.toJSONString(list));
 return list;
    }

    private static void treeChildren(String jsonStr, JSonObject currentJsonObj, String parentCodeFieldName, String parentCode, String currentCodeFieldName, String childrenFiledName) {
 JSonArray jsonArray = (JSONArray) JSONPath.read(jsonStr, "$[" + parentCodeFieldName + "=" + parentCode + "]");
 if (CollectionUtils.isEmpty(jsonArray)) {
     return;
 }
 currentJsonObj.put(childrenFiledName, jsonArray);
 for (int i = 0; i < jsonArray.size(); i++) {
     JSonObject jsonObject = jsonArray.getJSONObject(i);
     String code = jsonObject.getString(currentCodeFieldName);
     treeChildren(jsonStr, jsonObject, parentCodeFieldName, code, currentCodeFieldName, childrenFiledName);
 }
    }

赵小胖个人博客

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号