在项目中难免会用到树形结构,毕竟这是一种常用的组织架构。楼主这里整理了两个实现的版本,可以直接拿来使用,非常方便。

  楼主没有单独建项目,直接在以前的一个Demo上实现的。第一种,看下面代码:

  1. package com.johanChan.WebSocket.utils;
  2.  
  3. import com.alibaba.fastjson.JSON;
  4.  
  5. import java.util.ArrayList;
  6. import java.util.List;
  7.  
  8. //图层结构
  9. public class TreeBuilder {
  10.  
  11. List<Node> nodes = new ArrayList<>();
  12.  
  13. public String buildTree(List<Node> nodes) {
  14. TreeBuilder treeBuilder = new TreeBuilder(nodes);
  15. return treeBuilder.buildJSONTree();
  16. }
  17.  
  18. public TreeBuilder() {}
  19.  
  20. public TreeBuilder(List<Node> nodes) {
  21. super();
  22. this.nodes = nodes;
  23. }
  24.  
  25. // 构建JSON树形结构
  26. public String buildJSONTree() {
  27. List<Node> nodeTree = buildTree();
  28. String jsonStr = JSON.toJSONString(nodeTree);
  29. return jsonStr;
  30. }
  31.  
  32. // 构建树形结构
  33. public List<Node> buildTree() {
  34. List<Node> treeNodes = new ArrayList<>();
  35. List<Node> rootNodes = getRootNodes();
  36. for (Node rootNode : rootNodes) {
  37. buildChildNodes(rootNode);
  38. treeNodes.add(rootNode);
  39. }
  40. return treeNodes;
  41. }
  42.  
  43. // 递归子节点
  44. public void buildChildNodes(Node node) {
  45. List<Node> children = getChildNodes(node);
  46. if (!children.isEmpty()) {
  47. for (Node child : children) {
  48. buildChildNodes(child);
  49. }
  50. node.setChildren(children);
  51. }
  52. }
  53.  
  54. // 获取父节点下所有的子节点
  55. public List<Node> getChildNodes(Node pnode) {
  56. List<Node> childNodes = new ArrayList<>();
  57. for (Node n : nodes) {
  58. if (pnode.getId().equals(n.getParentId())) {
  59. childNodes.add(n);
  60. }
  61. }
  62. return childNodes;
  63. }
  64.  
  65. // 判断是否为根节点
  66. public boolean rootNode(Node node) {
  67. boolean isRootNode = true;
  68. for (Node n : nodes) {
  69. if (node.getParentId().equals(n.getId())) {
  70. isRootNode = false;
  71. break;
  72. }
  73. }
  74. return isRootNode;
  75. }
  76.  
  77. // 获取集合中所有的根节点
  78. public List<Node> getRootNodes() {
  79. List<Node> rootNodes = new ArrayList<>();
  80. for (Node n : nodes) {
  81. if (rootNode(n)) {
  82. rootNodes.add(n);
  83. }
  84. }
  85. return rootNodes;
  86. }
  87.  
  88. public static class Node {
  89. private Integer id;
  90. private Integer parentId;
  91. private String name;
  92. private String code;
  93. private Integer level;
  94. private List<Node> children;
  95.  
  96. public Node() {}
  97. public Node(Integer id,Integer parentId,String name,String code,Integer level){
  98. super();
  99. this.id = id;
  100. this.parentId = parentId;
  101. this.name = name;
  102. this.code = code;
  103. this.level = level;
  104. }
  105.  
  106. public Integer getId() {
  107. return id;
  108. }
  109.  
  110. public void setId(Integer id) {
  111. this.id = id;
  112. }
  113.  
  114. public Integer getParentId() {
  115. return parentId;
  116. }
  117.  
  118. public void setParentId(Integer parentId) {
  119. this.parentId = parentId;
  120. }
  121.  
  122. public String getName() {
  123. return name;
  124. }
  125.  
  126. public void setName(String name) {
  127. this.name = name;
  128. }
  129.  
  130. public String getCode() {
  131. return code;
  132. }
  133.  
  134. public void setCode(String code) {
  135. this.code = code;
  136. }
  137.  
  138. public Integer getLevel() {
  139. return level;
  140. }
  141.  
  142. public void setLevel(Integer level) {
  143. this.level = level;
  144. }
  145.  
  146. public List<Node> getChildren() {
  147. return children;
  148. }
  149.  
  150. public void setChildren(List<Node> children) {
  151. this.children = children;
  152. }
  153. }
  154. }

  看起来很长对吗?没关系,直接copy一下就可以使用。首先生成一个树形结构的数据:

  1. public static List<TreeBuilder.Node> buildNode(){
  2. List<TreeBuilder.Node> nodeList = new ArrayList<>();
  3. TreeBuilder.Node node = new TreeBuilder.Node(0,-1,"地球","WORD",1);
  4. TreeBuilder.Node node1 = new TreeBuilder.Node(1,0,"中国","CHN",1);
  5.  
  6. TreeBuilder.Node node2 = new TreeBuilder.Node(2,1,"华北区域","A",2);
  7. TreeBuilder.Node node3 = new TreeBuilder.Node(3,1,"华南区域","B",2);
  8. TreeBuilder.Node node4 = new TreeBuilder.Node(4,1,"华东区域","C",2);
  9. TreeBuilder.Node node5 = new TreeBuilder.Node(5,1,"华西区域","D",2);
  10. TreeBuilder.Node node6 = new TreeBuilder.Node(6,1,"华中区域","E",2);
  11.  
  12. TreeBuilder.Node node7 = new TreeBuilder.Node(7,6,"河南","豫",3);
  13. TreeBuilder.Node node8 = new TreeBuilder.Node(8,6,"湖北","鄂",3);
  14. TreeBuilder.Node node9 = new TreeBuilder.Node(9,6,"湖南","湘",3);
  15. TreeBuilder.Node node10 = new TreeBuilder.Node(10,6,"江西","赣",3);
  16.  
  17. TreeBuilder.Node node11 = new TreeBuilder.Node(11,7,"郑州","豫A",4);
  18. TreeBuilder.Node node12 = new TreeBuilder.Node(12,7,"开封","豫B",4);
  19. TreeBuilder.Node node13 = new TreeBuilder.Node(13,7,"洛阳","豫C",4);
  20. TreeBuilder.Node node14 = new TreeBuilder.Node(14,7,"南阳","豫R",4);
  21.  
  22. TreeBuilder.Node node15 = new TreeBuilder.Node(15,11,"金水区","豫A-1",5);
  23.  
  24. nodeList.add(node);
  25. nodeList.add(node1);nodeList.add(node2);nodeList.add(node3);
  26. nodeList.add(node4);nodeList.add(node5);nodeList.add(node6);
  27. nodeList.add(node7);nodeList.add(node8);nodeList.add(node9);
  28. nodeList.add(node10);nodeList.add(node11);nodeList.add(node12);
  29. nodeList.add(node13);nodeList.add(node14);nodeList.add(node15);
  30.  
  31. return nodeList;
  32. }

  然后调用new TreeBuilder().buildTree(nodeList)就可以返回json格式的字符串了:

  1. package com.johanChan.WebSocket.controller;
  2.  
  3. import com.alibaba.fastjson.JSON;
  4. import com.johanChan.WebSocket.utils.CommonUtils;
  5. import com.johanChan.WebSocket.utils.TreeBuilder;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.web.bind.annotation.PathVariable;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10.  
  11. import java.util.List;
  12.  
  13. @Controller
  14. public class TreeController {
  15.  
  16. List<TreeBuilder.Node> nodeList ;
  17. {
  18. nodeList = CommonUtils.buildNode();
  19. }
  20.  
  21. @ResponseBody
  22. @RequestMapping("/getTreeJson")
  23. public String getTreeJson() {
  24. // List<TreeBuilder.Node> nodeList = CommonUtils.buildNode();
  25. String result = CommonUtils.buildTree(nodeList);
  26. return result;
  27. }
  28.  
  29. }

  启动项目,访问/getTreeJson可以看到,页面返回了json字符串:

  整理后如下:

  1. [
  2. {
  3. "children":[
  4. {
  5. "children":[
  6. {
  7. "code":"A",
  8. "id":2,
  9. "level":2,
  10. "name":"华北区域",
  11. "parentId":1
  12. },
  13. {
  14. "code":"B",
  15. "id":3,
  16. "level":2,
  17. "name":"华南区域",
  18. "parentId":1
  19. },
  20. {
  21. "code":"C",
  22. "id":4,
  23. "level":2,
  24. "name":"华东区域",
  25. "parentId":1
  26. },
  27. {
  28. "code":"D",
  29. "id":5,
  30. "level":2,
  31. "name":"华西区域",
  32. "parentId":1
  33. },
  34. {
  35. "children":[
  36. {
  37. "children":[
  38. {
  39. "children":[
  40. {
  41. "code":"豫A-1",
  42. "id":15,
  43. "level":5,
  44. "name":"金水区",
  45. "parentId":11
  46. }
  47. ],
  48. "code":"豫A",
  49. "id":11,
  50. "level":4,
  51. "name":"郑州",
  52. "parentId":7
  53. },
  54. {
  55. "code":"豫B",
  56. "id":12,
  57. "level":4,
  58. "name":"开封",
  59. "parentId":7
  60. },
  61. {
  62. "code":"豫C",
  63. "id":13,
  64. "level":4,
  65. "name":"洛阳",
  66. "parentId":7
  67. },
  68. {
  69. "code":"豫R",
  70. "id":14,
  71. "level":4,
  72. "name":"南阳",
  73. "parentId":7
  74. }
  75. ],
  76. "code":"豫",
  77. "id":7,
  78. "level":3,
  79. "name":"河南",
  80. "parentId":6
  81. },
  82. {
  83. "code":"鄂",
  84. "id":8,
  85. "level":3,
  86. "name":"湖北",
  87. "parentId":6
  88. },
  89. {
  90. "code":"湘",
  91. "id":9,
  92. "level":3,
  93. "name":"湖南",
  94. "parentId":6
  95. },
  96. {
  97. "code":"赣",
  98. "id":10,
  99. "level":3,
  100. "name":"江西",
  101. "parentId":6
  102. }
  103. ],
  104. "code":"E",
  105. "id":6,
  106. "level":2,
  107. "name":"华中区域",
  108. "parentId":1
  109. }
  110. ],
  111. "code":"CHN",
  112. "id":1,
  113. "level":1,
  114. "name":"中国",
  115. "parentId":0
  116. }
  117. ],
  118. "code":"WORD",
  119. "id":0,
  120. "level":1,
  121. "name":"地球",
  122. "parentId":-1
  123. }
  124. ]

  第一种方法完成,下面是第二种实现,首先建立一个类:

  1. package com.johanChan.WebSocket.utils;
  2.  
  3. import java.util.ArrayList;
    import java.util.List;
  4.  
  5. public class Tree<T> {
    /**
    * 节点ID
    */
    private Integer id;
    /**
    * 显示节点文本
    */
    private String text;
    /**
    * 父ID
    */
    private Integer parentId;
  6.  
  7. private Integer level;
    /**
    * 节点的子节点
    */
    // private List<Tree<T>> nodes = new ArrayList<Tree<T>>();
    private List<Tree<T>> nodes = null;
  8.  
  9. public Tree() {}
    public Tree(Integer id,Integer parentId,String text,Integer level){
    super();
    this.id = id;
    this.text = text;
    this.parentId = parentId;
    this.level = level;
    }
  10.  
  11. public Integer getId() {
    return id;
    }
  12.  
  13. public void setId(Integer id) {
    this.id = id;
    }
  14.  
  15. public String getText() {
    return text;
    }
  16.  
  17. public void setText(String text) {
    this.text = text;
    }
  18.  
  19. public Integer getParentId() {
    return parentId;
    }
  20.  
  21. public void setParentId(Integer parentId) {
    this.parentId = parentId;
    }
  22.  
  23. public Integer getLevel() {
    return level;
    }
  24.  
  25. public void setLevel(Integer level) {
    this.level = level;
    }
  26.  
  27. public List<Tree<T>> getNodes() {
    if(nodes==null){
    nodes = new ArrayList<Tree<T>>();
    }
    return nodes;
    }
  28.  
  29. public void setNodes(List<Tree<T>> nodes) {
    this.nodes = nodes;
    }
  30.  
  31. }

  然后对Tree进行排序:

  1. package com.johanChan.WebSocket.utils;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. public class BuildTree {
  7. public static <T> List<Tree<T>> build(List<Tree<T>> nodes) {
  8. if (nodes == null) {
  9. return null;
  10. }
  11. List<Tree<T>> topNodes = new ArrayList<>();
  12.  
  13. for (Tree<T> children : nodes) {
  14. String pid = children.getParentId();
  15. if (pid.equals(children.getId() )) {
  16. topNodes.add(children);
  17. continue;
  18. }
  19. for (Tree<T> parent : nodes) {
  20. String id = parent.getId();
  21. if (id != null && id.equals(pid)) {
  22. parent.getNodes().add(children);
  23. }
  24. }
  25. }
  26. return topNodes;
  27. }
  28.  
  29. }

  然后生成数据:

  1. public static List<Tree<TreeBuilder.Node>> buildTree(){
  2. List<Tree<TreeBuilder.Node>> treeList = new ArrayList<>();
  3. Tree<TreeBuilder.Node> tree = new Tree<TreeBuilder.Node>(0,0,"地球",1);
  4. Tree tree1 = new Tree(1,0,"中国",1);
  5.  
  6. Tree tree2 = new Tree(2,1,"华北区域",2);
  7. Tree tree3 = new Tree(3,1,"华南区域",2);
  8. Tree tree4 = new Tree(4,1,"华东区域",2);
  9. Tree tree5 = new Tree(5,1,"华西区域",2);
  10. Tree tree6 = new Tree(6,1,"华中区域",2);
  11.  
  12. Tree tree7 = new Tree(7,6,"河南",3);
  13. Tree tree8 = new Tree(8,6,"湖北",3);
  14. Tree tree9 = new Tree(9,6,"湖南",3);
  15. Tree tree10 = new Tree(10,6,"江西",3);
  16.  
  17. Tree tree11 = new Tree(11,7,"郑州",4);
  18. Tree tree12 = new Tree(12,7,"开封",4);
  19. Tree tree13 = new Tree(13,7,"洛阳",4);
  20. Tree tree14 = new Tree(14,7,"南阳",4);
  21.  
  22. Tree tree15 = new Tree(15,11,"金水区",5);
  23.  
  24. treeList.add(tree);
  25. treeList.add(tree1);treeList.add(tree2);treeList.add(tree3);
  26. treeList.add(tree4);treeList.add(tree5);treeList.add(tree6);
  27. treeList.add(tree7);treeList.add(tree8);treeList.add(tree9);
  28. treeList.add(tree10);treeList.add(tree11);treeList.add(tree12);
  29. treeList.add(tree13);treeList.add(tree14);treeList.add(tree15);
  30.  
  31. return treeList;
  32. }

  调用方法:

  1. package com.johanChan.WebSocket.controller;
  2.  
  3. import com.alibaba.fastjson.JSON;
  4. import com.johanChan.WebSocket.utils.BuildTree;
  5. import com.johanChan.WebSocket.utils.CommonUtils;
  6. import com.johanChan.WebSocket.utils.Tree;
  7. import com.johanChan.WebSocket.utils.TreeBuilder;
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.web.bind.annotation.PathVariable;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.ResponseBody;
  12.  
  13. import java.util.List;
  14.  
  15. @Controller
  16. public class TreeController {
  17.  
  18. List<TreeBuilder.Node> nodeList ;
  19. List<Tree<TreeBuilder.Node>> treeList;
  20. {
  21. nodeList = CommonUtils.buildNode();
  22. treeList = CommonUtils.buildTree();
  23. }
  24.  
  25. @ResponseBody
  26. @RequestMapping("/getTreeJson")
  27. public String getTreeJson() {
  28. // List<TreeBuilder.Node> nodeList = CommonUtils.buildNode();
  29. // String result = CommonUtils.buildTree(nodeList);
  30. List<Tree<TreeBuilder.Node>> resultList = BuildTree.build(treeList);
  31. String result = JSON.toJSONString(resultList);
  32. return result;
  33. }
  34.  
  35. }

  返回数据如下:

  整理后:

  1. [
  2. {
  3. "id":0,
  4. "level":1,
  5. "nodes":[
  6. {
  7. "id":1,
  8. "level":1,
  9. "nodes":[
  10. {
  11. "id":2,
  12. "level":2,
  13. "nodes":[
  14.  
  15. ],
  16. "parentId":1,
  17. "text":"华北区域"
  18. },
  19. {
  20. "id":3,
  21. "level":2,
  22. "nodes":[
  23.  
  24. ],
  25. "parentId":1,
  26. "text":"华南区域"
  27. },
  28. {
  29. "id":4,
  30. "level":2,
  31. "nodes":[
  32.  
  33. ],
  34. "parentId":1,
  35. "text":"华东区域"
  36. },
  37. {
  38. "id":5,
  39. "level":2,
  40. "nodes":[
  41.  
  42. ],
  43. "parentId":1,
  44. "text":"华西区域"
  45. },
  46. {
  47. "id":6,
  48. "level":2,
  49. "nodes":[
  50. {
  51. "id":7,
  52. "level":3,
  53. "nodes":[
  54. {
  55. "id":11,
  56. "level":4,
  57. "nodes":[
  58. {
  59. "id":15,
  60. "level":5,
  61. "nodes":[
  62.  
  63. ],
  64. "parentId":11,
  65. "text":"金水区"
  66. }
  67. ],
  68. "parentId":7,
  69. "text":"郑州"
  70. },
  71. {
  72. "id":12,
  73. "level":4,
  74. "nodes":[
  75.  
  76. ],
  77. "parentId":7,
  78. "text":"开封"
  79. },
  80. {
  81. "id":13,
  82. "level":4,
  83. "nodes":[
  84.  
  85. ],
  86. "parentId":7,
  87. "text":"洛阳"
  88. },
  89. {
  90. "id":14,
  91. "level":4,
  92. "nodes":[
  93.  
  94. ],
  95. "parentId":7,
  96. "text":"南阳"
  97. }
  98. ],
  99. "parentId":6,
  100. "text":"河南"
  101. },
  102. {
  103. "id":8,
  104. "level":3,
  105. "nodes":[
  106.  
  107. ],
  108. "parentId":6,
  109. "text":"湖北"
  110. },
  111. {
  112. "id":9,
  113. "level":3,
  114. "nodes":[
  115.  
  116. ],
  117. "parentId":6,
  118. "text":"湖南"
  119. },
  120. {
  121. "id":10,
  122. "level":3,
  123. "nodes":[
  124.  
  125. ],
  126. "parentId":6,
  127. "text":"江西"
  128. }
  129. ],
  130. "parentId":1,
  131. "text":"华中区域"
  132. }
  133. ],
  134. "parentId":0,
  135. "text":"中国"
  136. }
  137. ],
  138. "parentId":0,
  139. "text":"地球"
  140. }
  141. ]

  OK!以上两种方法都比较有通用性,把自己的数据整理后调用就可以了。

Java实现树形结构的数据转Json格式的更多相关文章

  1. java返回树形结构的正确姿势

    业务场景 通常我们前端需要一个树形的导航菜单或者分类菜单,如后台权限管理中的权限树,亦或者下面例子中商城系统的商品分类多级菜单(一般为三级菜单) 数据库设计 数据库设计,采用parentId来指向自己 ...

  2. C# 把带有父子关系的数据转化为------树形结构的数据 ,以及 找出父子级关系的数据中里面的根数据Id

    紧接上一篇,将List<Menu>的扁平结构数据, 转换成树形结构的数据 返回给前端   ,   废话不多说,开撸! --------------------- 步骤: 1. 建 Menu ...

  3. 数据转换为json格式的方法

    数据转换为json格式: 如果一张表中存在主外键关系,模板自动生成的类是不可以转换成JSON格式的,此时需要重新写一个类,类前面需加[DataContract],字段前需加[DataMember],实 ...

  4. jmeter随笔(1)-在csv中数据为json格式的数据不完整

    昨天同事在使用jmeter遇到问题,在csv中数据为json格式的数据,在jmeter中无法完整的取值,小怪我看了下,给出解决办法,其实很简单,我们一起看看,看完了记得分享给你的朋友. 问题现象: 1 ...

  5. C# 任意类型数据转JSON格式(转)

    HOT SUMMER 每天都是不一样,积极的去感受生活 C# 任意类型数据转JSON格式 /// <summary> /// List转成json /// </summary> ...

  6. 关于多条数据转为json格式单次传输的问题 2017.05.27

    数据形式如下: var mycars = [];//定义数组存放多条数据 for(var i=0;i<2;i++){ var jsonData = {};//定义变量存放单条数据 jsonDat ...

  7. 了解php数据转json格式与前端交互基础

    php数据转json格式与前端交互 ArryJson1.php <?php $test=array(); $word=array("我12","要43", ...

  8. 接口数据转json格式

    接口数据转json格式 function tojson($result, $callback = null){ header('Content-Type:text/html; charset=utf- ...

  9. jmeter 导入csv数据中json格式数据取值不完整

    1.jmeter中添加csv数据文件时,数据是json格式 2.jmeter中执行取值发现只取了一部分 分析原因,json格式数据,中间有逗号,而csv是根据逗号来分割的,这回导致我们取值错位. 解决 ...

随机推荐

  1. 日志分析-利用grep,awk等文本处理工具完成(2019-4-9)

    0x00 基础日志分析命令 1. tail - 监控末尾日志的变化 $tail -n 10 error2019.log #显示最后10行日志内容 $tail -n +5 nginx2019.log # ...

  2. 使用Faker库生成模拟数据

    一.相关文档 该库在laravel框架中默认已经存在,无需手动进行安装.使用参考文档: https://packagist.org/packages/fzaninotto/faker 二.简单示例 & ...

  3. Android实现EditText插入表情、超链接等格式

    参考:https://www.jianshu.com/p/84067ad289d2 参考:https://www.jianshu.com/p/d82ac2edc7e8

  4. Python更新列表

    Python更新列表: 使用索引下标进行更新: # 修改列表的第 6 个元素为 d lst = ['a','b','c',1,2,3] lst[5] = 'd' print(lst) # ['a', ...

  5. PDOStatement::getAttribute

    PDOStatement::getAttribute — 检索一个语句属性(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)高佣联盟 www.cgewang.com 说 ...

  6. CF 878E Numbers on the blackboard 并查集 离线 贪心

    LINK:Numbers on the blackboard 看完题觉得很难. 想了一会发现有点水 又想了一下发现有点困难. 最终想到了 但是实现的时候 也很难. 先观察题目中的这个形式 使得前后两个 ...

  7. 教你如何使用零代码开发的Foreach循环功能代替for循环

    使用技巧:Foreach循环功能! 项目中为了避免将同样的语句重复写很多次,相信大家在编程过程中肯定用过循环语句.其中For循环作为基础中的基础,大家一定不会陌生.不过今天小V要讲的可不是For循环, ...

  8. 2 DC电参数测试 (1)

    基本常识: (1)Hot switch好的程序应避免使用热切换(这里热的含义类似于热插拔的“热“),热切换是指带点操作,有电流的情况下断开开关或闭合开关的瞬间,有电流通过,这会减少开关的寿命甚至直接损 ...

  9. Python 教你自动发微博,每日一句英语

    作者:周萝卜 最近在研究用 Python 来制作各个类别的机器人,今天先来分享一个自动发布新浪微博的机器人. 基本思路 其实要实现一个简单的自动发布微博机器人还是不难的,只需要每天按时找好要发布的素材 ...

  10. Web接口测试理论知识分享

    首先谈下接口的定义分为2类,程序接口和协议接口 1.程序模块接口,具体到程序中就是提供了输入输出的类 方法,我们可以通过传入不同的参数,来验证程序接口的功能 2.协议接口  比如HTTP/SOAP协议 ...