将json串转换成下拉树格式传回前端

由于前台需要带children的json串返回,所以我们需要处理返回的json
转换前的json格式

 {
      "id": "3",
     "title": "1.1.1",
     "fuid": "2",
      }
     {
       "id": "2",
      "title": "1.1",
      "fuid": "1",
     }
    {
      "id": "1",
      "title": "1",
      "fuid": "0",
    }

controller层返回时处理json串

public Map<String,Object> pipeLineTree(@RequestParam(required = false)String state){
		List<Map<String, Object>> maps= new ArrayList<>();
		Map<String, Object> returnMap = new HashMap<String, Object>();
		try{
			maps = pipeLineService.pipeLineInforList(state);
           JSONArray result = listToTree(JSONArray.parseArray(JSON.toJSONString(maps)),"id","title","fuid","children");
            returnMap.put("status", "1");
			returnMap.put("data", result);
		}catch(Exception ex){
			returnMap.put("status", "0");
			returnMap.put("message", "系统出现异常,工程师正在玩命抢修!");
		}
		return returnMap;
	}
    public static JSONArray listToTree(JSONArray arr,String id,String title,String fuid,String child){
        JSONArray r = new JSONArray();
        JSONObject hash = new JSONObject();
        //将数组转为Object的形式,key为数组中的id
        for(int i=0;i<arr.size();i++){
            JSONObject json = (JSONObject) arr.get(i);
            hash.put(json.getString(id), json);
        }
        //遍历结果集
        for(int j=0;j<arr.size();j++){
            //单条记录
            JSONObject aVal = (JSONObject) arr.get(j);
            //在hash中取出key为单条记录中pipePId的值
            JSONObject hashVP = (JSONObject) hash.get(aVal.get(fuid).toString());
            //如果记录的fuid存在,则说明它有父节点,将她添加到孩子节点的集合中
            if(hashVP!=null){
                //检查是否有child属性
                if(hashVP.get(child)!=null){
                    JSONArray ch = (JSONArray) hashVP.get(child);
                    ch.add(aVal);
                    hashVP.put(child, ch);
                }else{
                    JSONArray ch = new JSONArray();
                    ch.add(aVal);
                    hashVP.put(child, ch);
                }
            }else{
                r.add(aVal);
            }
        }
        return r;
    }


处理完成后为

 {
      "children": [
        {
          "children": [
            {
              "id": "3",
              "title": "1.1.1",
              "fuid": "2",
            }
          ],
          "id": "2",
          "title": "1.1",
          "fuid": "1",
        }
      ],
      "id": "1",
      "title": "1",
      "fuid": "0",
    },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值