这里的问题是每次运行循环时都会重新创建类“obj”的实例,所以在循环结束时,我只有1组对象。它应该有几个。
foreach (var project in projectsDictionary)
{
foreach (var season in seasonsDictionary)
{
foreach (var episode in episodesDictionary)
{
obj = new Parent
{
Title = project.Value, Link = "1", Children = new List<Parent>
{
new Parent
{
Title = season.Value, Link = "1", Children = new List<Parent>
{
new Parent
{
Title = episode.Value, Link = "1", Children = null
}
}
}
}
};
}
}
}
var responseBody = JsonConvert.SerializeObject(obj);
return responseBody;
public class Parent
{
public string Title
{
get;
set;
}
public string Link
{
get;
set;
}
public List<Parent> Children
{
get;
set;
}
}
答案 0 :(得分:3)
在第一个循环之外定义obj
作为列表。
var obj = new List<Parent>();
然后
obj.Add(new Parent(...));