我需要基于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等价于idCategories。随后,每个Subcategory都可以容纳Child

我需要盖一棵树。如果JSON数据返回List<Category>,则最终树将是此类List(即List<ParentCategory>

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


如何在Java数据结构中表示这棵树?

最佳答案

最简单的方法是通过两遍遍遍列表:

Pass1:创建一个由ID键入的类别的Map<Integer, ParentCategory>,忽略ParentCategoryId和子类别。

Pass2:使用ParentCategoryId查找在Pass1中创建的ParentCategory,并将其添加到其子类别中

关于java - 用Java创建动态树,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33105657/

10-09 07:23