JJ.
JJ.

Reputation: 9970

How do I append objects to a JSON variable?

The issue here is that the instance of the class "obj" is re-created every time I run through the loop so at the end of the loop, I only have 1 set of the object. It should have several.

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;
    }
}

Upvotes: 0

Views: 159

Answers (1)

Jonathan
Jonathan

Reputation: 6003

Outside the first loop define obj as a list.

var obj = new List<Parent>();

then

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

Upvotes: 3

Related Questions