I have a table like this (Groups):
ID Name ParentID
1 Group 1 null
2 Group 2 null
3 SubGr 1-1 1
4 SubGr 1-2 1
5 SubGr 2-1 2
6 Group 3 null
7 SubGr 1-2-1 4
..... and so on
I want to serialize this to JSON looking like this:
[{"id":1,
"name":"Group 1",
"children": [
{
"id":3,
"name":"SubGr 1-1",
"children":null
},{
"id":4,
"name":"SubGr 1-2",
"children": [
{
"id":7,
"name":"SubGr 1-2-1",
"children": null
}
]
}
]
},
{"id":2,
"name":"Group 2",
"children": [
{
"id":5,
"name":"SubGr 2-1",
"children":null
}
]
},
{"id":6,
"name": "Group 3",
"children": null
}
]
As you can see, you can have indefinite subgroups.
How can I make such a query in LINQ and output it in JSON like the example above?
I have no problem outputting the JSON as seperated elements, with ParentID, but I need to have the structure as mentioned above.
This is the code that I am currently working with, after trying different things around, but with no luck still (this version only gives two levels):
public ActionResult GetGroups()
{
var groupobjs = db.GroupObjs.ToList();
var items = groupobjs.Where(p => p.ParentID == null).Select(p => new
{
id = p.ID,
name = p.Name,
children = groupobjs.Where(c => c.ParentID == p.ID).Select(c => new {
id = c.ID,
name = c.Name
})
});
return Json(items, JsonRequestBehavior.AllowGet);
}
I was working on some code similar to what @Hunter-974 recommended.