title: How to create hierarchy in json string from string array?
body: <p>I am trying to generate json string for the hierarchy like below:</p>
  
  <pre><code>Company(select * from Company)
      Department(select * from Department)
          Employee(select * from Employee)
  </code></pre>
  
  <p>Each of the above query will return fields like below:</p>
  
  <pre><code>Company Fields -  (Id,Name,Location)
  Department Fields - (Id,Name,CompanyId)
  Employee Fields - (Id,Name,DepartmentId)
  </code></pre>
  
  <p>Now I am trying to generate JSON string for above entities like below:</p>
  
  <p><strong>Expected output:</strong> </p>
  
  <pre><code>{
    "Id": "",
    "Name": "",
    "Location": "",
    "Department": 
          {
             "Id": "",
             "Name": "",
             "CompanyId": "",
             "Employee" : 
                 {
                    "Id": "",
                    "Name": "",
                    "DepartmentId": "", 
                 }
          }
  }
  </code></pre>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>public string GetData(Child model,List&lt;Parent&gt; parents)
          {
             var fields = new List&lt;string[]&gt;();
             if (parents != null)
             {
                  foreach (var parent in parents)
                  {
                          var columns = GetColumns(parent); //returns string[] of columns
                          fields.Add(columns);
                   }
              }
              fields.Add(GetColumns(model));
              string json = JsonConvert.SerializeObject(fields.ToDictionary(key =&gt; key, v =&gt; string.Empty),
                                          Formatting.Indented);
              return json;
          }
  </code></pre>
  
  <p>Now when I don't have any parents and want to generate json string for only child then below code is working fine:</p>
  
  <pre><code>string json = JsonConvert.SerializeObject(fields.ToDictionary(key =&gt; key, v =&gt; string.Empty),Formatting.Indented)
  </code></pre>
  
  <p><strong>Output :</strong></p>
  
  <pre><code>{
    "Id": "",
    "Name": "",
    "Location": "",
  }
  </code></pre>
  
  <p>But now I want to generate JSON for my hierarchy with any such inbuilt way.</p>
  
  <p>I know I can loop,append and create json string but I want to do this in better way like I have done for my child.</p>
  
  <p><strong>Update:</strong> </p>
  
  <pre><code>public class Child
  {
      public string Name { get; set; } // Contains Employee
     //Other properties and info related to process sql query and connection string
  }
  
  
  public class Parent
  {
      public string Name { get; set; } // Contains Company,Department.
      public string SqlQuery { get; set; } // query related to Company and Department.
      //Other properties and info related to connection string
  }
  </code></pre>