Convert DataTable to JSON using StringBuilder in ASP.NET C#

Convert DataTable to JSON using StringBuilder in ASP.NET C#

using StringBuilder we can create similar JSON Structured String.

using System.Text;
public string DataTableToJsonWithStringBuilder(DataTable table)
{
   var jsonString = new StringBuilder();
   if (table.Rows.Count > 0)
   {
	   jsonString.Append("[");
	   for (int i = 0; i < table.Rows.Count; i++)
	   {
		   jsonString.Append("{");
		   for (int j = 0; j < table.Columns.Count; j++)
		   {
			   if (j < table.Columns.Count - 1)
			   {
				   jsonString.Append("\"" + table.Columns[j].ColumnName.ToString()
									 + "\":" + "\""
									 + table.Rows[i][j].ToString() + "\",");
			   }
			   else if (j == table.Columns.Count - 1)
			   {
				   jsonString.Append("\"" + table.Columns[j].ColumnName.ToString()
									 + "\":" + "\""
									 + table.Rows[i][j].ToString() + "\"");
			   }
		   }
		   if (i == table.Rows.Count - 1)
		   {
			   jsonString.Append("}");
		   }
		   else
		   {
			   jsonString.Append("},");
		   }
	   }
	   jsonString.Append("]");
   }
	return jsonString.ToString();
}

 

2020-02-02