title: How to build object hierarchy for serialization with json.net?
body: <p>I'm trying to properly write code to build a data structure to serialize into json.</p>
  
  <p>I'm using json.net.</p>
  
  <p>I don't want to create a bunch of classes to hold this data, as I thought there should be some classes that will already do this in json.net</p>
  
  <p>I've already got all the data I need in a series of nested loops, and now I just want to add them to an object hierarchy before I run JsonConvert.SerializeObject on it.</p>
  
  <p>I've already tried code like this, but it doesn't seem to work</p>
  
  <pre><code>JArray container = new JArray();
  
          container.Add(new JObject(new JProperty("name", "Client1"), new JProperty("projects", new JArray())));
  
          container[0].AddAfterSelf(new JObject(new JProperty("projects", new JArray())));            
          container[1].AddAfterSelf(new JObject(new JProperty("projects", "Project2")));
          container[1].AddAfterSelf(new JObject(new JProperty("projects", "Project3")));
          container.Add(new JProperty("name", "Client2"));            
  
          var test = JsonConvert.SerializeObject(container);
  </code></pre>
  
  <p><strong>The problem is that when I use [i]. or ElementAt(i) to access somewhere in the structure, either .Add() is missing or .ElementAt isn't there.
  How do I step through the data structure to make this nicely output the below, or do I have to create my own container class for all of this?</strong></p>
  
  <p>This is the data format I am trying to make.</p>
  
  <pre><code>[
      {
      "name": "student1",
      "projects": 
      [
          {
          "name": "Project1",
          "tasks": 
                  [
                      {
                      "name": "task1",
                      "id": 2
                      }
                  ],
          "id": 6
          }
      ]
  },
      {
      "name": "Student2",
      "projects": [
                  {
                  "name": "Project1",
                  "tasks": [
                           {
                           "name": "Task2",
                           "id": 1
                           },
                           {
                           "name": "Task3",
                           "id": 3
                           },
                           {
                           "name": "Task4",
                           "id": 4
                           }
                           ],
                  "id": 2
  </code></pre>
  
  <p>etc...</p>