using System.Data;
using System.Text;
DataTable dataTable = new
DataTable();
DataRow? dataRow = null;
dataTable.Columns.Add("EmpCode", typeof(string));
dataTable.Columns.Add("EmpName", typeof(string));
dataRow = dataTable.NewRow();
dataRow["EmpCode"] = "E0001";
dataRow["EmpName"] = "Ram";
dataTable.Rows.Add(dataRow);
dataRow = dataTable.NewRow();
dataRow["EmpCode"] = "E0002";
dataRow["EmpName"] = "Shyam";
dataTable.Rows.Add(dataRow);
Console.WriteLine(Utility.ConvertDataTableToJsonString(dataTable));
Console.ReadLine();
public class Utility
{
public static string
ConvertDataTableToJsonString(DataTable dataTable)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("[");
int
totalColumnCount = dataTable.Columns.Count;
int
totalRowCount = dataTable.Rows.Count;
int rowCount
= 0;
foreach (DataRow
row in dataTable.Rows)
{
rowCount++;
stringBuilder.Append("{");
int
columnCount = 0;
foreach
(DataColumn dataColumn in dataTable.Columns)
{
columnCount++;
stringBuilder.Append("\"" +
dataColumn.ColumnName.ToString() + "\":" + "\"" +
row[dataColumn.ColumnName].ToString() + "\"");
if
(columnCount != totalColumnCount)
{
stringBuilder.Append(",");
}
}
stringBuilder.Append("}");
if (rowCount
!= totalRowCount)
{
stringBuilder.Append(",");
}
}
stringBuilder.Append("]");
return
stringBuilder.ToString();
}
}
No comments:
Post a Comment