如何在json中动态创建元素层次结构? C#

时间:2018-04-20 09:09:16

标签: c# asp.net asp.net-mvc

我有一个方法repo.jfrog.org,它返回子节点作为参数传递的父节点的身份
那些孩子也可以有自己的孩子到任何水平

如果我想创建一个代表孩子和父母的整个层次结构的JSON,那我该怎么办?

GetChild(id)

这只是第一级

如何递归使用此public ActionResult GetChild(long id) { Dal objDal = new Dal(); var res = objDal.db.ChildGet(id).ToList(); return Json(res, JsonRequestBehavior.AllowGet); } 方法?

任何形式的帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

    public class Comment
    {
        public int Id { get; set; }
        public int ParentId { get; set; }
        public string Text { get; set; }
        public List<Comment> Children { get; set; }
    }
    public JsonResult Test()
    {
        List<Comment> categories = new List<Comment>()
        {
            new Comment () { Id = 1, Text = "Yabancı Dil", ParentId = 0},
            new Comment() { Id = 2, Text = "İngilizce", ParentId = 1 },
            new Comment() { Id = 3, Text = "YDS", ParentId = 2 },
            new Comment() { Id = 4, Text = "TOEFL", ParentId = 2 },
            new Comment() { Id = 5, Text = "YDS Seviye1", ParentId = 3 },
            new Comment() { Id = 6, Text = "TOEFL Seviye1", ParentId = 4 }
        };

        List<Comment> hierarchy = new List<Comment>();

        hierarchy = categories
                        .Where(c => c.Id == 2)
                        .Select(c => new Comment()
                        {
                            Id = c.Id,
                            Text = c.Text,
                            ParentId = c.ParentId,
                            Children = GetChildren(categories, c.Id)
                        })
                        .ToList();

        List<Comment> list = new List<Comment>();
        List<string> list2 = new List<string>();
        if (hierarchy != null)
        {
            liste.AddRange(hierarchy);

        }

        return Json(liste, JsonRequestBehavior.AllowGet);
    }

    public static List<Comment> GetChildren(List<Comment> comments, int parentId)
    {
        hAbDbContext db = new hAbDbContext();
        return comments
                .Where(c => c.ParentId == parentId)
                .Select(c => new Comment()
                {
                    Id = c.Id,
                    Text = c.Text,
                    ParentId = c.ParentId,
                    Children = GetChildren(comments, c.Id)
                })
                .ToList();
    }