From my previous forum question on the link, Iterate over a json input and create the treeview like hierarchy based on the "keys" taking account of the children "keys". I am building upon this question and want to create a Treeview from the content of the List<KeyId>
.
The deeply nested JSON is mapped into a c# tree where each node has two properties -- a string key and a long T_id -- as well as a collection of children of the same type.
public partial class KeyIdObject
{
public string key { get; set; }
public long T_id { get; set; }
public List<KeyIdObject> Children { get; set; }
}
The json has a structure as follows:
{
"Soccer":{
"T_id":0,
"T_state":"valid",
"Clubs":{
"ClubA":{
"T_id":"1",
"T_state":"Champs"
},
"ClubB":{
"T_id":"2",
"T_state":"Runnerups"
}
},
"Subs":{
"SubA":{
"T_id":"3",
"T_state":"Unfit",
//this is nested key
"SubE":{
"T_id":"3",
"T_state":"Unfit"
}
}
},
"Subs_Used":{
"SubK":{
"T_id":"3",
"T_state":"Unfit"
}
}
//many more nested n-levels
}
}
Then it can be used to generate a recursive List like so:
public partial class KeyIdObject
{
public static List<KeyIdObject> ToIdObjects(JToken root)
{
return root.TopDescendantsWhere<JObject>(o => o["T_id"] != null)
.Select(o => new KeyIdObject { key = ((JProperty)o.Parent).Name, T_id = (long)o["T_id"], Children = ToIdObjects(o) })
.ToList();
}
}
The List<KeyIdObject>
contents looks something like this below:
Output List<KeyIdObject>:
[
{
"key": "Soccer",
"T_id": 0,
"Children": [
{
"key": "Clubs",
"Children": [
{
"key": "ClubA",
"T_id": 1
},
{
"key": "ClubB",
"T_id": 2
}
]
},
{
"key": "Subs",
"Children": [
{
"key": "SubA",
"T_id": 3,
"Children": [
{
"key": "SubE",
"T_id": 3
}
]
}
]
},
{
"key": "Subs_Used",
"Children": [
{
"key": "SubK",
"T_id": 3
}
]
}
]
}
]
From this information, I want to be able to parse each "key" and its children and build a view like the following when the user clicks on the respective key, there will will be drop-down list with the respective contents.
>Soccer
>Clubs
ClubA
ClubB
>Subs
SubA
>Subs_Used
SubK
I thought it would be good to create two ObservableCollection as follows.
ObservableCollection<KeyIdObject> rootMenuItem;
//to hold just the "Soccer" string and its "T_id"?ObservableCollection<KeyIdObject> subMenuItem;
//append this collection as the child to the rootMenuItem in the end after done populating
When I iterate over the resulting outputlist, I want to maybe use like a recursive function that can add all the "children" in the hierarchy as shown in the Output List<KeyIdObject>
to produce something like this below:
>Clubs
ClubA
ClubB
>Subs
SubA
>Subs_Used
SubK
I am not sure on how to create the recursive function which will do this. Any guidance would be highly appreciated. I am not sure if this is the most efficient way to do it or is there a better way.
I am using the SfTreeView
from https://help.syncfusion.com/xamarin/sftreeview/getting-started