此问题中的代码生成以下 JSON。
代码应该通过 line 排除空的“Children”键.Where(a => a.Values != null)
,但它不起作用。
我可以在哪里放置 where 子句,以便 JSON 不包含一堆空的“儿童”数组?
谢谢你的帮助。
[{
"NodeID" : 1,
"NodeText" : "Country",
"Children" : [{
"NodeID" : 3,
"NodeText" : "President",
"Children" : []
}, {
"NodeID" : 4,
"NodeText" : "Population",
"Children" : []
}, {
"NodeID" : 5,
"NodeText" : "State",
"Children" : [{
"NodeID" : 6,
"NodeText" : "Governor",
"Children" : []
}, {
"NodeID" : 7,
"NodeText" : "Population",
"Children" : []
}, {
"NodeID" : 8,
"NodeText" : "County",
"Children" : [{
"NodeID" : 9,
"NodeText" : "Population",
"Children" : []
}
]
}
]
}
]
}, {
"NodeID" : 2,
"NodeText" : "Year",
"Children" : []
}
]
以下是生成上述 JSON 的示例代码:
public class Node
{
public int? ParentNodeID { get; set; }
public int NodeID { get; set; }
public string NodeText { get; set; }
public Node(int? parentNodeID, int nodeID, string nodeText)
{
ParentNodeID = parentNodeID;
NodeID = nodeID;
NodeText = nodeText;
}
}
public List<Dictionary<string, object>> BuildTree(int? parentNodeID = null, List<Node> exampleData = null)
{
// kickstart the recursion with example data
if (exampleData == null)
{
exampleData = new List<Node>();
exampleData.Add(new Node(null, 1, "Country"));
exampleData.Add(new Node(null, 2, "Year"));
exampleData.Add(new Node(1, 3, "President"));
exampleData.Add(new Node(1, 4, "Population"));
exampleData.Add(new Node(1, 5, "State"));
exampleData.Add(new Node(5, 6, "Governor"));
exampleData.Add(new Node(5, 7, "Population"));
exampleData.Add(new Node(5, 8, "County"));
exampleData.Add(new Node(8, 9, "Population"));
}
List<Dictionary<string, object>> result = new List<Dictionary<string, object>>();
var nodes = exampleData.Where(a => a.ParentNodeID == parentNodeID).ToList();
if (nodes != null)
{
result.AddRange(nodes
.Select(a => new Dictionary<string, object> {
{ "NodeID", a.NodeID},
{ "NodeText", a.NodeText },
{ "Children", BuildTree(a.NodeID, exampleData) }
})
.Where(a => a.Values != null) // this doesn't have any effect
.ToList()
);
}
return result;
}