【发布时间】:2019-08-31 01:51:03
【问题描述】:
采用这样的嵌套递归 JSON sn-p 可以继续到任何深度:
{
"Id": null,
"Foos": [
{
"FooId": 1,
"FooName": "ABC",
"Foos": [
{
"FooId": 2,
"FooName": "DEF",
"Foos": null
},
{
"FooId": 3,
"FooName": "GHI",
"Foos": [
{
"FooId": 4,
"FooName": "JKL",
"Foos": null
},
{
"FooId": 5,
"FooName": "MNO",
"Foos": [
{
"FooId": 6,
"FooName": "PQR",
"Foos": null
},
{
"FooId": 7,
"FooName": "STU",
"Foos": null
}
]
}
]
}
]
}
]
}
使用 JSON.NET,我可以将其映射到这样的结构中:
public class Root {
public string Id { get; set; }
public List<Foo> Foos { get; set; }
}
public class Foo {
public int FooId { get; set; }
public string FooName { get; set; }
public List<Foo> Foos { get; set; }
}
到目前为止一切都很好......但现在我需要从层次结构的底部向上工作(从 FooId=5 的孩子开始),然后再回到根目录。如何有效地解决这个问题?
【问题讨论】:
-
反序列化后迭代一次树会不会不好?
-
澄清一下,您希望按 6、7、5、4、3、2、1 的顺序迭代对象?
-
如果我们有树
A [ B [ C, D ] , E [ F, G ] ]怎么办?你想要C、D、B、F、G、E、A吗?或者你想要 C、D、F、G、B、E、A 吗?第一个是后序遍历,第二个是级别遍历,它们的区别很大。从您的问题中不清楚您需要哪个。 -
请阅读en.wikipedia.org/wiki/Tree_traversal并说清楚你想要哪种遍历。
-
或者,你真的只想遍历
FooId": 5节点的父节点,类似于XElement.AncestorsAndSelf或JToken.AncestorsAndSelf()枚举给定节点的父节点的方式吗?例如。祖先是5, 3, 1, null