如何将对象附加到JSON变量?

时间:2013-08-09 01:02:21

标签: c# json

这里的问题是每次运行循环时都会重新创建类“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;
    }
}

1 个答案:

答案 0 :(得分:3)

在第一个循环之外定义obj作为列表。

var obj = new List<Parent>();

然后

obj.Add(new Parent(...));