来自我上一个关于链接Iterate over a json input and create the treeview like hierarchy based on the "keys" taking account of the children "keys"的论坛问题。我正在以此问题为基础,并希望根据List<KeyId>
的内容创建一个Treeview。
深度嵌套的JSON被映射到c#树中,其中每个节点具有两个属性-字符串键和长T_id-以及相同类型的子级集合。
public partial class KeyIdObject
{
public string key { get; set; }
public long T_id { get; set; }
public List<KeyIdObject> Children { get; set; }
}
json的结构如下:
{
"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
}
}
然后可以将其用于生成递归列表,如下所示:
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();
}
}
List<KeyIdObject>
的内容如下所示:
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
}
]
}
]
}
]
根据这些信息,我希望能够解析每个“键”及其子级,并在用户单击相应键时构建如下所示的视图,将出现一个包含相应内容的下拉列表。
>Soccer
>Clubs
ClubA
ClubB
>Subs
SubA
>Subs_Used
SubK
我认为最好按如下所示创建两个ObservableCollection。
ObservableCollection<KeyIdObject> rootMenuItem;
//仅保留“足球”字符串及其“ T_id”?ObservableCollection<KeyIdObject> subMenuItem;
//将此集合作为子项在完成填充后最后附加到rootMenuItem上当我遍历结果输出列表时,我想像递归函数一样使用,该函数可以将层次结构中的所有“子级”添加到输出List<KeyIdObject>
中,以产生如下所示的内容:>
>Clubs
ClubA
ClubB
>Subs
SubA
>Subs_Used
SubK
我不确定如何创建递归函数。任何指导将不胜感激。我不确定这是最有效的方法还是有更好的方法。
我正在使用https://help.syncfusion.com/xamarin/sftreeview/getting-started中的SfTreeView