Java java지도 시간 데이터베이스 테이블 내용을 기반으로 트리 구조 json 데이터를 생성하는 Java 방법

데이터베이스 테이블 내용을 기반으로 트리 구조 json 데이터를 생성하는 Java 방법

Jan 10, 2017 am 11:47 AM

1. 활용 시나리오

조직 트리에는 일반적으로 코드(code), pcode(상위 코드), 이름(조직 이름) 및 기타 필드가 있는 조직 테이블이 있습니다

2. 데이터 구축 (아래 데이터는 기관 데이터가 아니고 순전히 제가 만든 데이터입니다.)

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. 소스코드

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. 실행 결과

JSON 데이터:

{
  "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": "顶级节点"
}
로그인 후 복사

위는 편집자가 가져온 데이터베이스 테이블의 내용을 기반으로 Java가 트리 구조 json 데이터를 생성하는 전체 방법입니다. PHP 중국어 웹 사이트를 모두 지원하시기 바랍니다~

이 내용을 기반으로 더 많은 Java 제작이 가능합니다. 데이터베이스 테이블의 트리 구조 json 데이터 방법과 관련된 기사는 PHP 중국어 웹사이트에 주목하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

2025 년 상위 4 개의 JavaScript 프레임 워크 : React, Angular, Vue, Svelte 2025 년 상위 4 개의 JavaScript 프레임 워크 : React, Angular, Vue, Svelte Mar 07, 2025 pm 06:09 PM

이 기사는 2025 년에 상위 4 개의 JavaScript 프레임 워크 (React, Angular, Vue, Svelte)를 분석하여 성능, 확장 성 및 향후 전망을 비교합니다. 강력한 공동체와 생태계로 인해 모두 지배적이지만 상대적으로 대중적으로

Spring Boot Snakeyaml 2.0 CVE-2022-1471 문제 고정 Spring Boot Snakeyaml 2.0 CVE-2022-1471 문제 고정 Mar 07, 2025 pm 05:52 PM

이 기사는 원격 코드 실행을 허용하는 중요한 결함 인 Snakeyaml의 CVE-2022-1471 취약점을 다룹니다. Snakeyaml 1.33 이상으로 Spring Boot 응용 프로그램을 업그레이드하는 방법에 대해 자세히 설명합니다.

Java의 클래스로드 메커니즘은 다른 클래스 로더 및 대표 모델을 포함하여 어떻게 작동합니까? Java의 클래스로드 메커니즘은 다른 클래스 로더 및 대표 모델을 포함하여 어떻게 작동합니까? Mar 17, 2025 pm 05:35 PM

Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.

카페인 또는 구아바 캐시와 같은 라이브러리를 사용하여 자바 애플리케이션에서 다단계 캐싱을 구현하려면 어떻게해야합니까? 카페인 또는 구아바 캐시와 같은 라이브러리를 사용하여 자바 애플리케이션에서 다단계 캐싱을 구현하려면 어떻게해야합니까? Mar 17, 2025 pm 05:44 PM

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

Node.js 20 : 주요 성능 향상 및 새로운 기능 Node.js 20 : 주요 성능 향상 및 새로운 기능 Mar 07, 2025 pm 06:12 PM

Node.js 20은 V8 엔진 개선, 특히 더 빠른 쓰레기 수집 및 I/O를 통해 성능을 크게 향상시킵니다. 새로운 기능에는 더 나은 webAssembly 지원 및 정제 디버깅 도구, 개발자 생산성 및 응용 속도 향상이 포함됩니다.

빙산 : 데이터 호수 테이블의 미래 빙산 : 데이터 호수 테이블의 미래 Mar 07, 2025 pm 06:31 PM

대규모 분석 데이터 세트를위한 오픈 테이블 형식 인 Iceberg는 데이터 호수 성능 및 확장 성을 향상시킵니다. 내부 메타 데이터 관리를 통한 Parquet/Orc의 한계를 해결하여 효율적인 스키마 진화, 시간 여행, 동시 W를 가능하게합니다.

오이의 단계간에 데이터를 공유하는 방법 오이의 단계간에 데이터를 공유하는 방법 Mar 07, 2025 pm 05:55 PM

이 기사는 오이 단계간에 데이터를 공유하는 방법, 시나리오 컨텍스트, 글로벌 변수, 인수 통과 및 데이터 구조를 비교합니다. 간결한 컨텍스트 사용, 설명을 포함하여 유지 관리에 대한 모범 사례를 강조합니다.

Java에서 기능 프로그래밍 기술을 어떻게 구현할 수 있습니까? Java에서 기능 프로그래밍 기술을 어떻게 구현할 수 있습니까? Mar 11, 2025 pm 05:51 PM

이 기사는 Lambda 표현식, 스트림 API, 메소드 참조 및 선택 사항을 사용하여 기능 프로그래밍을 Java에 통합합니다. 간결함과 불변성을 통한 개선 된 코드 가독성 및 유지 관리 가능성과 같은 이점을 강조합니다.

See all articles