title: How to create a nested (parent-Child ) JSON response in c#?
body: <p>I am making a web service which will give a response in JSON format. I have fetched data from sql server and stored it in a Datatable. This is how the dt looks:-</p>
  
  <pre><code>id      Caption                 pid
  F182    GLOBAL REPORTS          NULL
  F184    software                NULL
  F1227   LYB P&amp;L Reports         F184
  F1245   LYB Training            F184
  F1239   test3                   F182
  F1249   Paavan_Test_Reports     F184
  </code></pre>
  
  <p>Items in caption column which have pid as <strong>Null</strong> are the parents and they have children which have the same <strong>pid</strong> as their respective parent's <strong>id</strong>. </p>
  
  <p><strong>Eg:</strong> <strong>GLOBAL REPORTS</strong> has 1 child i.e <strong>test3</strong> and <strong>software</strong> has 3 child.</p>
  
  <p>I want the JSON response into the following format</p>
  
  <pre><code>[{ 
      id='F182',  
      caption='GLOBAL REPORTS',
      pid=null;
      items:[{
      id='F1239',
      caption='test3',
      pid='F182'}] 
      },
      { 
      id='F184',
      caption='software',
      pid='NULL',
      items:[{
      id='F1227',
      caption='LYB P&amp;L Reports',
      pid='F184'
      },
      {
      id='F1245',
      caption='LYB Training',
      pid='F184'
      },
      { 
      id='F1249',
      caption='Paavan_Test_Reports',
      pid='F184'
      }
  }]
  </code></pre>
  
  <p>i have made a class <strong>folder</strong></p>
  
  <pre><code>    class folder
      {
      string id{get;set;}
      string pid{get;set;}
      string caption{get;set;}
     }
  </code></pre>
  
  <p>How can i get the array of objects <strong>items</strong> which will contain all the available child of a particular parent? I am new to Json objects and responses,</p>
  
  <p>I have tried using the following method:</p>
  
  <pre><code> var obj = dt.AsEnumerable()
                  .GroupBy(r =&gt; r["pid"])
                  .ToDictionary(g =&gt; g.Key.ToString(),
                                g =&gt; g.Select(r =&gt; new {
                                item = r["caption"].ToString(),
                                }).ToArray());
       var json = JsonConvert.SerializeObject(obj);
  </code></pre>
  
  <p>but this is giving me a simple json response without any hierarchy.</p>