Search code examples
c#.netjsondatatablejavascriptserializer

DataTable to nested JSON using Javascript serializer in C#


I'm converting a Data Table rows into a JSON string. Using a Javascript serializer I have generated a normal JSON string. How can we generated it as Nested string.

Current Json output

{  
   "PatientId":"32424",
   "CustomerId":"XXXX",
   "Name":"DiastolicBloodPressure",
   "Value":89,
   "Unit":"mmHg",
   "MinValue":50,
   "MaxValue":90,
   "SessionElementResponseText":null
}

Expected

{  
   "PatientId":"32424",
   "CustomerId":"XXXX",
   "VitalThreshold":{  
      "Name":"DiastolicBloodPressure",
      "Value":89,
      "Unit":"mmHg",
      "MinValue":50,
      "MaxValue":90
   },
   "SessionElementResponseText":null
}

Code

public static string DataTableToJSON(DataTable table)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    Dictionary<string, object> row;
    foreach(DataRow dr in table.Rows)
    {
        row = new Dictionary<string, object>();
        foreach(DataColumn col in table.Columns)
        {
            if(col.ColumnName.Equals("Name"))
            {
                //Trying here
            }
            row.Add(col.ColumnName, dr[col]);
        }
        rows.Add(row);
    }
    serializer.MaxJsonLength = int.MaxValue;
    return serializer.Serialize(rows);
}

Solution

  • Basically, you have to add one condition to buffer the inner row. Then, at the end of the loop add the "inner row" into the main row.

        public static string DataTableToJSON(DataTable table)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            var innerList = new string[] { "Name", "Value", "Unit", "MinValue", "MaxValue" };
            var innerRow = new Dictionary<string, object>();
            foreach (DataRow dr in table.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in table.Columns)
                {
                    if (innerList.Contains(col.ColumnName))
                    {
                        innerRow.Add(col.ColumnName, dr[col]);
                    }
                    else
                    {
                        row.Add(col.ColumnName, dr[col]);
                    }
    
                }
                row.Add("VitalThreshold", innerRow);
                rows.Add(row);
            }
            serializer.MaxJsonLength = int.MaxValue;
            return serializer.Serialize(rows);
        }