2015-10-13 95 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并添加到它的子类别