我得到以下结果(来自外部 API 的响应):
Results = [
{
"ID": "2",
"Name": "Home",
"ParentID": "1",
"Path": "/home"
},
{
"ID": "3",
"Name": "Contacts",
"ParentID": "1",
"Path": "/contacts"
},
{
"ID": "4",
"Name": "Help",
"ParentID": "3",
"Path": "/contacts/help"
},
{
"ID": "5",
"Name": "Form",
"ParentID": "4",
"Path": "/contacts/help/form"
},
{
"ID": "6",
"Name": "Information",
"ParentID": "4",
"Path": "/contacts/help/information"
}
]
ID财产始终是唯一的;
ParentID属性是对父级的引用(ID)(ParentID=1是源“/”)。每个对象都有一个ParentID。
我需要创建一个具有以下响应的 HTTP 方法(在 C# 中):
Output = [
{
"Name": "Home",
"Path": "/home",
"Childrens": []
},
{
"Name": "Contacts",
"Path": "/contacts",
"Childrens": [
{
"Name": "Help",
"Path": "/contacts/help",
"Childrens": [
{
"Name": "Form",
"Path": "/contacts/help/form",
"Childrens": []
},
{
"Name": "Information",
"Path": "/contacts/help/information",
"Childrens": []
}
]
}
]
}
]
我该怎么做?我可以做一个递归函数吗?
附注如果您只给我建议和提示,我将不胜感激。
(已编辑)
我在 python 中用两步完成了这个(抱歉不知道 csharp 语法):
这是示例代码:
def recAdd(vck, objs, target):
children = []
for x in vck[target]:
children.append(recAdd(vck, objs, x))
obj = {
"Name" : objs[target]["Name"],
"Path" : objs[target]["Path"],
"Children" : children
}
return obj
def convert(objs):
ids = {}
for obj in objs:
ids[obj["ID"]] = obj
valueIsChildOfKey= {}
for k,v in ids.items():
if k not in valueIsChildOfKey.keys():
valueIsChildOfKey[k] = []
if v["ParentID"] in valueIsChildOfKey.keys():
valueIsChildOfKey[v["ParentID"]].append(k)
else:
valueIsChildOfKey[v["ParentID"]] = [k]
out = []
for x in valueIsChildOfKey["1"]:
out.append(recAdd(valueIsChildOfKey, ids, x))
return out
if __name__ == "__main__":
Results = [ {"ID": "2","Name": "Home","ParentID": "1","Path": "/home"}, { "ID": "3", "Name": "Contacts", "ParentID": "1", "Path": "/contacts" }, { "ID": "4", "Name": "Help", "ParentID": "3", "Path": "/contacts/help" }, { "ID": "5", "Name": "Form", "ParentID": "4", "Path": "/contacts/help/form" }, { "ID": "6", "Name": "Information", "ParentID": "4", "Path": "/contacts/help/information" } ]
print(convert(Results))