JAVA8自带TreeUtils

 

 

 

 tree.json

{
  "code": 200,
  "msg": "操作成功",
  "data": [
    {
      "id": "310000",
      "name": "电子商务",
      "parentId": "000000"
    },
    {
      "id": "310100",
      "name": "大宗商品",
      "parentId": "310000"
    },
    {
      "id": "310101",
      "name": "大宗商品综合",
      "parentId": "310100"
    },
    {
      "id": "310102",
      "name": "钢铁类电商",
      "parentId": "310100"
    }
  ]
}
@GetMapping("testTreeUtils")
    public List<TreeNode<String>> testTreeUtils() throws Exception {
        ClassPathResource classPathResource = new ClassPathResource("data/tree.json");
        InputStream fileInputStream =classPathResource.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
        StringBuilder sb = new StringBuilder();
        int ch = 0;
        while((ch = inputStreamReader.read())!=-1){
            sb.append((char)ch);
        }
        inputStreamReader.close();
        String treeStr = sb.toString();
        JSONObject jsonObject = JSONObject.parseObject(treeStr);
        JSONArray data = jsonObject.getJSONArray("data");
        List<Category> categories = JSONArray.parseArray(data.toJSONString(), Category.class);
        List<TreeNode<String>> node = TreeUtils.createNode(categories, "000000");
        return node;

    }

运行结果:

 流创建树:

 

 

 

posted @ 2022-12-16 12:02  蔡徐坤1987  阅读(380)  评论(0编辑  收藏  举报