我们假设我有这个输入
0 //1st zero
1 //is child of 1st zero
0 //2nd zero
1 //is child of 2nd zero
1 //is child of 2nd zero
2 //is child of 2nd one
2 //is child of 2nd one
1 //etc...
2
3
2
1
0
和这个班级
public class Node
{
public int Number { get; set; }
public Node Parent { get; set; }
public List<Node> Children { get; set; }
}
解析此输出然后将其序列化为json的最佳方法是什么?
我真正需要的是遍历此输入并创建多叶树结构的算法,以便我可以序列化为json,然后将其传递给d3js javascript库,这将可视化此树。
答案 0 :(得分:0)
伪代码,如果您需要更多信息,请与我们联系:
// Added to Node class:
public int GetDepthRecursive()
{
return Parent == null ? 0 : (Parent.GetDepthRecursive() + 1);
}
// To parse the text file into a node tree:
Node rootNode = new Node { Number = 0 }; // You need a node for all those zero nodes to hang off
Node currentNode = rootNode;
foreach (var row in rows)
{
rowDepth = row.StartingSpaces.Count(); // Use any method you want to count these spaces
var rowNode = new Node { Number = int.Parse(row) };
// The new row node is at the same or lower depth than us
// Go back up the tree to find the right parent for it
while (currentNode.GetDepthRecursive() > rowDepth)
{
currentNode = currentNode.Parent;
}
rowNode.Parent = currentNode;
currentNode = rowNode;
}