search
HomeJavajavaTutorialJAVA example code for producing tree-structured JSON data based on database table content

1. Utilization scenario

Organization tree usually has an organization table, which has code (code), pcode (superior code), name (organization name) and other fields

2. Structural data (the following data is not organizational data, but purely data made up by myself)

List<Tree<Test>> trees = new ArrayList<Tree<Test>>();
tests.add(new Test("0", "", "关于本人"));
tests.add(new Test("1", "0", "技术学习"));
tests.add(new Test("2", "0", "兴趣"));
tests.add(new Test("3", "1", "JAVA"));
tests.add(new Test("4", "1", "oracle"));
tests.add(new Test("5", "1", "spring"));
tests.add(new Test("6", "1", "springmvc"));
tests.add(new Test("7", "1", "fastdfs"));
tests.add(new Test("8", "1", "linux"));
tests.add(new Test("9", "2", "骑行"));
tests.add(new Test("10", "2", "吃喝玩乐"));
tests.add(new Test("11", "2", "学习"));
tests.add(new Test("12", "3", "String"));
tests.add(new Test("13", "4", "sql"));
tests.add(new Test("14", "5", "ioc"));
tests.add(new Test("15", "5", "aop"));
tests.add(new Test("16", "1", "等等"));
tests.add(new Test("17", "2", "等等"));
tests.add(new Test("18", "3", "等等"));
tests.add(new Test("19", "4", "等等"));
tests.add(new Test("20", "5", "等等"));

3. Source code

Tree.java

package pers.kangxu.datautils.bean.tree;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
/**
 * tree TODO <br>
 *
 * @author kangxu2 2017-1-7
 *
 */
public class Tree<T> {
  /**
   * 节点ID
   */
  private String id;
  /**
   * 显示节点文本
   */
  private String text;
  /**
   * 节点状态,open closed
   */
  private String state = "open";
  /**
   * 节点是否被选中 true false
   */
  private boolean checked = false;
  /**
   * 节点属性
   */
  private List<Map<String, Object>> attributes;
  /**
   * 节点的子节点
   */
  private List<Tree<T>> children = new ArrayList<Tree<T>>();
  /**
   * 父ID
   */
  private String parentId;
  /**
   * 是否有父节点
   */
  private boolean isParent = false;
  /**
   * 是否有子节点
   */
  private boolean isChildren = false;
  public String getId() {
    return id;
  }
  public void setId(String id) {
    this.id = id;
  }
  public String getText() {
    return text;
  }
  public void setText(String text) {
    this.text = text;
  }
  public String getState() {
    return state;
  }
  public void setState(String state) {
    this.state = state;
  }
  public boolean isChecked() {
    return checked;
  }
  public void setChecked(boolean checked) {
    this.checked = checked;
  }
  public List<Map<String, Object>> getAttributes() {
    return attributes;
  }
  public void setAttributes(List<Map<String, Object>> attributes) {
    this.attributes = attributes;
  }
  public List<Tree<T>> getChildren() {
    return children;
  }
  public void setChildren(List<Tree<T>> children) {
    this.children = children;
  }
  public boolean isParent() {
    return isParent;
  }
  public void setParent(boolean isParent) {
    this.isParent = isParent;
  }
  public boolean isChildren() {
    return isChildren;
  }
  public void setChildren(boolean isChildren) {
    this.isChildren = isChildren;
  }
  public String getParentId() {
    return parentId;
  }
  public void setParentId(String parentId) {
    this.parentId = parentId;
  }
  public Tree(String id, String text, String state, boolean checked,
      List<Map<String, Object>> attributes, List<Tree<T>> children,
      boolean isParent, boolean isChildren, String parentID) {
    super();
    this.id = id;
    this.text = text;
    this.state = state;
    this.checked = checked;
    this.attributes = attributes;
    this.children = children;
    this.isParent = isParent;
    this.isChildren = isChildren;
    this.parentId = parentID;
  }
  public Tree() {
    super();
  }
  @Override
  public String toString() {
    return JSON.toJSONString(this);
  }
}

BuildTree.java

package pers.kangxu.datautils.common.tree;
import java.util.ArrayList;
import java.util.List;
import pers.kangxu.datautils.bean.tree.Tree;
/**
 * 构建tree
 * TODO
 * <br>
 * @author kangxu2 2017-1-7
 *
 */
public class BuildTree {
  /**
   *
   * TODO
   * <br>
   * @author kangxu2 2017-1-7
   *
   * @param nodes
   * @return
   */
  public static <T> Tree<T> build(List<Tree<T>> nodes) {
    if(nodes == null){
      return null;
    }
    List<Tree<T>> topNodes = new ArrayList<Tree<T>>();
    for (Tree<T> children : nodes) {
      String pid = children.getParentId();
      if (pid == null || "".equals(pid)) {
        topNodes.add(children);
        continue;
      }
      for (Tree<T> parent : nodes) {
        String id = parent.getId();
        if (id != null && id.equals(pid)) {
          parent.getChildren().add(children);
          children.setParent(true);
          parent.setChildren(true);
          continue;
        }
      }
    }
    Tree<T> root = new Tree<T>();
    if (topNodes.size() == 0) {
      root = topNodes.get(0);
    } else {
      root.setId("-1");
      root.setParentId("");
      root.setParent(false);
      root.setChildren(true);
      root.setChecked(true);
      root.setChildren(topNodes);
      root.setText("顶级节点");
    }
    return root;
  }
}

##BuildTreeTester.java

package pers.kangxu.datautils.test;
import java.util.ArrayList;
import java.util.List;
import pers.kangxu.datautils.bean.tree.Tree;
import pers.kangxu.datautils.common.tree.BuildTree;
public class BuildTreeTester {
  public static void main(String[] args) {
    List<Tree<Test>> trees = new ArrayList<Tree<Test>>();
    List<Test> tests = new ArrayList<Test>();
    tests.add(new Test("0", "", "关于本人"));
    tests.add(new Test("1", "0", "技术学习"));
    tests.add(new Test("2", "0", "兴趣"));
    tests.add(new Test("3", "1", "JAVA"));
    tests.add(new Test("4", "1", "oracle"));
    tests.add(new Test("5", "1", "spring"));
    tests.add(new Test("6", "1", "springmvc"));
    tests.add(new Test("7", "1", "fastdfs"));
    tests.add(new Test("8", "1", "linux"));
    tests.add(new Test("9", "2", "骑行"));
    tests.add(new Test("10", "2", "吃喝玩乐"));
    tests.add(new Test("11", "2", "学习"));
    tests.add(new Test("12", "3", "String"));
    tests.add(new Test("13", "4", "sql"));
    tests.add(new Test("14", "5", "ioc"));
    tests.add(new Test("15", "5", "aop"));
    tests.add(new Test("16", "1", "等等"));
    tests.add(new Test("17", "2", "等等"));
    tests.add(new Test("18", "3", "等等"));
    tests.add(new Test("19", "4", "等等"));
    tests.add(new Test("20", "5", "等等"));
    for (Test test : tests) {
      Tree<Test> tree = new Tree<Test>();
      tree.setId(test.getId());
      tree.setParentId(test.getPid());
      tree.setText(test.getText());
      trees.add(tree);
    }
    Tree<Test> t = BuildTree.build(trees);
    System.out.println(t);
  }
}
class Test {
  private String id;
  private String pid;
  private String text;
  public String getId() {
    return id;
  }
  public void setId(String id) {
    this.id = id;
  }
  public String getPid() {
    return pid;
  }
  public void setPid(String pid) {
    this.pid = pid;
  }
  public String getText() {
    return text;
  }
  public void setText(String text) {
    this.text = text;
  }
  public Test(String id, String pid, String text) {
    super();
    this.id = id;
    this.pid = pid;
    this.text = text;
  }
  public Test() {
    super();
  }
  @Override
  public String toString() {
    return "Test [id=" + id + ", pid=" + pid + ", text=" + text + "]";
  }
}

4. Running results

JSON data:

{
  "checked": true,
  "children": [
    {
      "checked": false,
      "children": [
        {
          "checked": false,
          "children": [
            {
              "checked": false,
              "children": [
                {
                  "checked": false,
                  "children": [],
                  "id": "12",
                  "parent": true,
                  "parentId": "3",
                  "state": "open",
                  "text": "String"
                },
                {
                  "checked": false,
                  "children": [],
                  "id": "18",
                  "parent": true,
                  "parentId": "3",
                  "state": "open",
                  "text": "等等"
                }
              ],
              "id": "3",
              "parent": true,
              "parentId": "1",
              "state": "open",
              "text": "JAVA"
            },
            {
              "checked": false,
              "children": [
                {
                  "checked": false,
                  "children": [],
                  "id": "13",
                  "parent": true,
                  "parentId": "4",
                  "state": "open",
                  "text": "sql"
                },
                {
                  "checked": false,
                  "children": [],
                  "id": "19",
                  "parent": true,
                  "parentId": "4",
                  "state": "open",
                  "text": "等等"
                }
              ],
              "id": "4",
              "parent": true,
              "parentId": "1",
              "state": "open",
              "text": "oracle"
            },
            {
              "checked": false,
              "children": [
                {
                  "checked": false,
                  "children": [],
                  "id": "14",
                  "parent": true,
                  "parentId": "5",
                  "state": "open",
                  "text": "ioc"
                },
                {
                  "checked": false,
                  "children": [],
                  "id": "15",
                  "parent": true,
                  "parentId": "5",
                  "state": "open",
                  "text": "aop"
                },
                {
                  "checked": false,
                  "children": [],
                  "id": "20",
                  "parent": true,
                  "parentId": "5",
                  "state": "open",
                  "text": "等等"
                }
              ],
              "id": "5",
              "parent": true,
              "parentId": "1",
              "state": "open",
              "text": "spring"
            },
            {
              "checked": false,
              "children": [],
              "id": "6",
              "parent": true,
              "parentId": "1",
              "state": "open",
              "text": "springmvc"
            },
            {
              "checked": false,
              "children": [],
              "id": "7",
              "parent": true,
              "parentId": "1",
              "state": "open",
              "text": "fastdfs"
            },
            {
              "checked": false,
              "children": [],
              "id": "8",
              "parent": true,
              "parentId": "1",
              "state": "open",
              "text": "linux"
            },
            {
              "checked": false,
              "children": [],
              "id": "16",
              "parent": true,
              "parentId": "1",
              "state": "open",
              "text": "等等"
            }
          ],
          "id": "1",
          "parent": true,
          "parentId": "0",
          "state": "open",
          "text": "技术学习"
        },
        {
          "checked": false,
          "children": [
            {
              "checked": false,
              "children": [],
              "id": "9",
              "parent": true,
              "parentId": "2",
              "state": "open",
              "text": "骑行"
            },
            {
              "checked": false,
              "children": [],
              "id": "10",
              "parent": true,
              "parentId": "2",
              "state": "open",
              "text": "吃喝玩乐"
            },
            {
              "checked": false,
              "children": [],
              "id": "11",
              "parent": true,
              "parentId": "2",
              "state": "open",
              "text": "学习"
            },
            {
              "checked": false,
              "children": [],
              "id": "17",
              "parent": true,
              "parentId": "2",
              "state": "open",
              "text": "等等"
            }
          ],
          "id": "2",
          "parent": true,
          "parentId": "0",
          "state": "open",
          "text": "兴趣"
        }
      ],
      "id": "0",
      "parent": false,
      "parentId": "",
      "state": "open",
      "text": "关于本人"
    }
  ],
  "id": "-1",
  "parent": false,
  "parentId": "",
  "state": "open",
  "text": "顶级节点"
}

More JAVA based on database table content For articles related to the example code for producing tree-structured JSON data, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteTop 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteMar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedSpring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedMar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

Node.js 20: Key Performance Boosts and New FeaturesNode.js 20: Key Performance Boosts and New FeaturesMar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg: The Future of Data Lake TablesIceberg: The Future of Data Lake TablesMar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

How can I implement functional programming techniques in Java?How can I implement functional programming techniques in Java?Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

How to Share Data Between Steps in CucumberHow to Share Data Between Steps in CucumberMar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)