如何将对象附加到JSON变量中
本文关键字:JSON 变量 对象 | 更新日期: 2023-09-27 18:26:53
这里的问题是,每次运行循环时都会重新创建类"obj"的实例,因此在循环结束时,我只有一组对象。它应该有几个。
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;
}
}
在第一个循环之外,将obj
定义为列表。
var obj = new List<Parent>();
然后
obj.Add(new Parent(...));