title: Serializing a Tree into Json Object
body: <p>I have the following classes:</p>
  
  <p><strong>TreeNode.cs</strong></p>
  
  <pre><code>public class TreeNode : IEnumerable&lt;TreeNode&gt;
  {
      public readonly Dictionary&lt;string, TreeNode&gt; _children = new Dictionary&lt;string, TreeNode&gt;();
  
      public readonly string Id;
      public TreeNode Parent { get; private set; }
  
      public TreeNode(string id)
      {
          this.Id = id;
      }
  
      public TreeNode GetChild(string id)
      {
          return this._childs[id];
      }
  
      public void Add(TreeNode item)
      {
          if (item.Parent != null)
          {
              item.Parent._childs.Remove(item.Id);
          }
  
          item.Parent = this;
          this._childs.Add(item.Id, item);
      }
  
      public IEnumerator&lt;TreeNode&gt; GetEnumerator()
      {
          return this._childs.Values.GetEnumerator();
      }
  
      IEnumerator IEnumerable.GetEnumerator()
      {
          return this.GetEnumerator();
      }
  
      public int Count
      {
          get { return this._childs.Count; }
      }
  }
  </code></pre>
  
  <p><strong>FolderStructureNode.cs</strong></p>
  
  <pre><code>public class FolderStructureNode : TreeNode
  {
      //Some properties such as FolderName, RelativePath etc.
  }
  </code></pre>
  
  <p>So, when I have an object of type <code>FolderStructureNode</code> it is essentially a tree datastructure where each node represents a folder.
  I want to serialize this object into a JsonObject. I have tried both - JavaScriptSerializer and NewtonSoft. In both cases I get an output as -</p>
  
  <pre><code>[
    [
      []
    ],
    [
      []
    ],
    []
  ]
  </code></pre>
  
  <p>At the time of serialization, the tree looks something like this:</p>
  
  <p><img src="https://i.stack.imgur.com/ZShoY.png" alt="Tree"></p>
  
  <p>How do I serialize it in order to get the correct json object? Do I have to traverse the tree and create the json myself?</p>