2015-10-13 60 views
0

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

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 
    }, 
    ............... 
    ] 

主要Categoriesparentid==0Subcategories(孩子)是其parentId是eqaual到id S的Categories。隨後每個Subcategory可以容納Child

我需要建立一棵樹。如果JSON數據返回List<Category>那麼最終的樹將是這個類List(即List<ParentCategory>

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

我怎麼能代表該樹Java數據結構?

回答

1

最簡單的方式是通過列表有兩個通行證運行:

1步:創建由ID鍵入的類別,忽略ParentCategoryId和子類別的Map<Integer, ParentCategory>

Pass2:使用ParentCategoryI查找在Pass1中創建的ParentCategory並添加到它的子類別