如何在 C# 中创建这个嵌套的子 json?我无法弄清楚如何嵌套地添加到子列表中。我正在使用 this .
JSON
{
"name": "Top Level",
"parent": "null",
"children": [
{
"name": "Level 2: A",
"parent": "Top Level",
"children": [
{
"name": "Son of A",
"parent": "Level 2: A"
,
"children": [
{
"name": "Son of A",
"parent": "Level 2: A"
},
{
"name": "Daughter of A",
"parent": "Level 2: A"
}
]
},
{
"name": "Daughter of A",
"parent": "Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level"
}
]
}
Root 和 Child 的图形表示
类
public class d3_mitch
{
public string name { get; set; }
public string parent { get; set; }
public List<d3_mitch> children { get; set; }
}
我在做什么
d3_mitch d3 = new d3_mitch();
d3.id = 1;
d3.name = "Root";
d3.type = "Root";
d3.description = "abc blah blah";
d3.children = new List<d3_mitch>()
{
new d3_mitch() { name = "Carnivores", type = "Type", id = 2, description = "Diet consists solely of animal materials",
children=new List<d3_mitch>(){ new d3_mitch() { id= 3 ,name="Felidae",type="Family",description="Also known as cats"} }
}
};
现在问题是
如何将 child 添加到每个 id = N 的 parent 列表中?
像这样
d3.children = new List<d3_mitch>()
{
new d3_mitch() { name = "Carnivores", type = "Type", id = 2, description = "Diet consists solely of animal materials",
children=new List<d3_mitch>(){ new d3_mitch() { id= 3 ,name="Felidae",type="Family",description="Also known as cats",
//This one
children=new List<d3_mitch>(){ new d3_mitch() { id = 4, name = "Felidae4", type = "Family", description = "Also known as cats" } }
} }
}
};
最佳答案
由于你的类定义在你的例子中有所不同,我已经为这个例子做了我自己的定义:
public class MyNode
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Name { get; set; }
public List<MyNode> Nodes { get; set; }
public MyNode()
{
Nodes = new List<MyNode>();
}
}
接下来我们可以创建一个简单的节点列表,它们的关系由它们的 id 定义:
var rootNode = new MyNode() { ParentId = -1, Id = 1, Name = "Root" };
var nodes = new [] {
rootNode,
new MyNode() { ParentId = 1, Id = 2, Name = "ChildA" },
new MyNode() { ParentId = 1, Id = 3, Name = "ChildB" },
new MyNode() { ParentId = 2, Id = 4, Name = "ChildA.A" },
new MyNode() { ParentId = 2, Id = 5, Name = "ChildA.B" },
new MyNode() { ParentId = 3, Id = 6, Name = "ChildB.A" },
new MyNode() { ParentId = 3, Id = 7, Name = "ChildB.B" }
};
然后我们可以遍历每个项目以查找其父级并将其添加到其父级的子级列表中:
var nodeDict = nodes.ToDictionary(n => n.Id);
foreach (var item in nodes)
{
MyNode parentNode = null;
if (item.ParentId == -1 || !nodeDict.TryGetValue(item.ParentId, out parentNode)) // we don't want to look up the root node since it doesn't have a parent. you might want to add error handling if the parent node isn't found
{
continue;
}
parentNode.Nodes.Add(item);
}
然后我们可以序列化结果:
Console.WriteLine(JsonConvert.SerializeObject(rootNode, Formatting.Indented));
使用类似技术的稍微复杂的方法是创建“构建器”:
public interface IRootHierarchyBuilder
{
IHierarchyBuilder AddRootNode(MyNode rootNode);
}
public interface IHierarchyBuilder
{
IHierarchyBuilder AddNode(MyNode childNode);
MyNode Build();
}
public class HierarchyBuilder : IRootHierarchyBuilder, IHierarchyBuilder
{
private readonly IDictionary<int, MyNode> _nodes;
private MyNode _rootNode;
private HierarchyBuilder()
{
_nodes = new Dictionary<int, MyNode>();
}
public static IRootHierarchyBuilder Create()
{
return new HierarchyBuilder();
}
IHierarchyBuilder IRootHierarchyBuilder.AddRootNode(MyNode rootNode)
{
if (_rootNode != null)
{
throw new InvalidOperationException("Root node already exists.");
}
_rootNode = rootNode;
_nodes[rootNode.Id] = rootNode;
return this;
}
IHierarchyBuilder IHierarchyBuilder.AddNode(MyNode childNode)
{
if (_rootNode == null)
{
throw new InvalidOperationException("Root node not set.");
}
if (_nodes.ContainsKey(childNode.Id))
{
throw new Exception("This child has already been added.");
}
MyNode parentNode;
if (!_nodes.TryGetValue(childNode.ParentId, out parentNode))
{
throw new KeyNotFoundException("Parent node not found.");
}
parentNode.Nodes.Add(childNode);
_nodes[childNode.Id] = childNode;
return this;
}
MyNode IHierarchyBuilder.Build()
{
if (_rootNode == null)
{
throw new InvalidOperationException("Root node not set.");
}
return _rootNode;
}
}
然后你可以像这样使用:
var rootNode = HierarchyBuilder.Create()
.AddRootNode(new MyNode() { Id = 1, ParentId = -1, Name = "Root" })
.AddNode(new MyNode() { Id = 2, ParentId = 1, Name = "ChildA" })
.AddNode(new MyNode() { Id = 3, ParentId = 1, Name = "ChildB" })
.AddNode(new MyNode() { Id = 4, ParentId = 2, Name = "ChildA.A" })
.AddNode(new MyNode() { Id = 5, ParentId = 2, Name = "ChildA.B" })
.AddNode(new MyNode() { Id = 6, ParentId = 3, Name = "ChildB.A" })
.AddNode(new MyNode() { Id = 7, ParentId = 3, Name = "ChildB.B" })
.Build();
同样,我们可以序列化结果:
Console.WriteLine(JsonConvert.SerializeObject(rootNode, Formatting.Indented));
关于c# - 创建嵌套的子 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57815696/