簡體   English   中英

用Java創建動態樹

[英]Create a dynamic tree in java

我需要基於JSON數據創建動態樹。 我有一個類別列表,每個類別都有一個子類別,該子類別有一個子類別。

我的JSON數據示例是:

    [
      {
        "Id": 110,
        "Name": "Winter Collection",
        "ParentCategoryId": 0,
        "Description": null,
        "DisplayOrder": 0
      },
      {
        "Id": 111,
        "Name": "Hoodies",
        "ParentCategoryId": 110,
        "Description": null,
        "DisplayOrder": 0
      },
      {
        "Id": 113,
        "Name": "Pullover/Sweater",
        "ParentCategoryId": 110,
        "Description": null,
        "DisplayOrder": 0
      }
{
    "Id": 116,
    "Name": "Jacket \u0026 Blazer",
    "ParentCategoryId": 110,
    "Description": null,
    "DisplayOrder": 0
  },
  {
    "Id": 118,
    "Name": "Sweatshirts",
    "ParentCategoryId": 110,
    "Description": null,
    "DisplayOrder": 0
  },
  {
    "Id": 119,
    "Name": "Winter Accessories",
    "ParentCategoryId": 110,
    "Description": null,
    "DisplayOrder": 2
  },
  {
    "Id": 23,
    "Name": "Men\u0027s T-Shirt",
    "ParentCategoryId": 0,
    "Description": null,
    "DisplayOrder": 1
  },
  {
    "Id": 24,
    "Name": "Men\u0027s T-Shirt (Full sleeve)",
    "ParentCategoryId": 23,
    "Description": null,
    "DisplayOrder": -1
  },
  {
    "Id": 79,
    "Name": "Black T-Shirt",
    "ParentCategoryId": 23,
    "Description": null,
    "DisplayOrder": 0
  },
  {
    "Id": 80,
    "Name": "White T-Shirt",
    "ParentCategoryId": 23,
    "Description": null,
    "DisplayOrder": 0
  },
  {
    "Id": 81,
    "Name": "Red T-Shirt",
    "ParentCategoryId": 23,
    "Description": null,
    "DisplayOrder": 0
  },
  {
    "Id": 82,
    "Name": "Blue T-Shirt",
    "ParentCategoryId": 23,
    "Description": null,
    "DisplayOrder": 0
  },
    ...............
    ] 

主要Categories ,其parentid==0Subcategories (孩子)是他們parentId是eqaual到id號第Categories 隨后,每個Subcategory都可以容納Child

我需要蓋一棵樹。 如果JSON數據返回List<Category>則最終的樹將是此類List (即List<ParentCategory>

public class ParentCategory {
   Category category;
   List<ParentCategory> Subcategories;
}

如何在Java數據結構中表示這棵樹?

最簡單的方法是通過兩遍遍遍列表:

Pass1:創建一個由Map<Integer, ParentCategory> id Map<Integer, ParentCategory>鍵鍵入類別的Map<Integer, ParentCategory> ,而忽略ParentCategoryId和Subcategories。

Pass2:使用ParentCategoryId查找在Pass1中創建的ParentCategory,並將其添加到其子類別中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM