title: Converting xml tree to json tree
body: <p>Here's my code which succesfully creates XML:</p>
  
  <pre><code>XDocument xdoc = new XDocument();
  XElement root = new XElement("tree");
  root.Add(new XAttribute("id", 0));
  xdoc.Add(root);
  
  new BuildFoldersTree(root, db);
  
  var items = (from x in db.Items orderby x.name select new { x.name, x.id, x.parent }).ToList();
  foreach (var p in items)
  {
      XElement e = new XElement("item",
          new XAttribute("text", p.name),
          new XAttribute("id", p.id),
          new XAttribute("parentId", p.parent));
      XElement parent = root.XPathSelectElement(String.Format("//*[@id=\"FOLDER_{0}\"] ", p.parent.ToString()));
      if (parent != null) parent.Add(e);
   }
  </code></pre>
  
  <p>and:</p>
  
  <pre><code>public void BuildFoldersTree(XElement root, MyEntities db)
  {
      List&lt;Folder&gt; folders = (from x in db.Folders orderby x.parent select x).ToList();
  
      for (int i = 0; i &lt; folders.Count; i++)
      {
          int f_id = folders[i].parent;
          Folder folder = folders[i];
  
          XElement e = new XElement("item",
              new XAttribute("text", folder.name),
              new XAttribute("id", "FOLDER_" + folder.id.ToString()),
              new XAttribute("parentId", folder.parent));
  
          if (folder.parent == 0)
          {
              root.Add(e);
          }
          else
          {
              XElement parent = root.XPathSelectElement(String.Format("//*[@id=\"FOLDER_{0}\"] ", folder.parent.ToString()));
               parent.Add(e);
          }
      }
  }
  </code></pre>
  
  <p>Here's what's going on there:
  I have two tables in my database. One for Folders, and one for Items. Each item has a parent folder. The item has a column 'parent' which is integer and which represents the folder id.
  But, each folder also has a parent. The folder has a column named 'parent' which is integer and which represents an id of another folder.</p>
  
  <p>With that code, I'm creating an xml tree with folders, and then I add the items to the correct folder.</p>
  
  <p>The previous code works.</p>
  
  <p>Now, I need to make the same algorithm but for Json. So, it won't use Xml, it should create a Json tree.</p>
  
  <p>I have no idea on how to begin. What should I use?</p>
  
  <p>Here's an example of what the result xml looks like:</p>
  
  <pre><code>&lt;tree id="0"&gt;
      &lt;item text="Folder_name" id="FOLDER_1" parentId="0"&gt;
          &lt;item text="Other folder name" id="FOLDER_96" parentId="1"&gt;
              &lt;item text="Third folder name" id="FOLDER_127" parentId="96"&gt;
                  &lt;item text="New folder" id="FOLDER_147" parentId="127" /&gt;
                  &lt;item text="item name" id="959" parentId="147" /&gt;
                  &lt;item text="item name sdgdfh" id="1152" parentId="147" /&gt;
              &lt;/item&gt;
          &lt;/item&gt;
      &lt;/item&gt;
  &lt;/tree&gt;
  </code></pre>