asp. net Method of Constructing Json String Using DataTable
- 2021-07-10 19:24:30
- OfStack
This article illustrates how asp. net uses DataTable to construct Json strings. Share it for your reference, as follows:
/// <summary>
/// Will datatable Convert to json
/// </summary>
/// <param name="dtb"></param>
/// <returns></returns>
private string Dtb2Json(DataTable dtb) {
JavaScriptSerializer jss = new JavaScriptSerializer();
System.Collections.ArrayList dic = new System.Collections.ArrayList();
foreach (DataRow dr in dtb.Rows)
{
System.Collections.Generic.Dictionary<string, object> drow = new System.Collections.Generic.Dictionary<string, object>();
foreach (DataColumn dc in dtb.Columns)
{
drow.Add(dc.ColumnName, dr[dc.ColumnName]);
}
dic.Add(drow);
}
// Serialization
return jss.Serialize(dic);
} /// <summary>
/// Build JSON String
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string CreateJsonParameters(DataTable dt)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
if (dt != null && dt.Rows.Count > 0)
{
sb.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
sb.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
// If the value is not last 1 Add comma separation for each
if (j < dt.Columns.Count - 1)
{
sb.Append("/"" + dt.Columns[j].ColumnName.ToString() + "/":" + "/"" + dt.Rows[i][j].ToString() + "/",");
}
// If the value is the last character, no comma is added
else if (j == dt.Columns.Count - 1)
{
sb.Append("/"" + dt.Columns[j].ColumnName.ToString() + "/":" + "/"" + dt.Rows[i][j].ToString() + "/"");
}
}
// If it is the last 1 Words of value No commas are added
if (i == dt.Rows.Count - 1)
{
sb.Append("}");
}
else
{
sb.Append("},");
}
}
sb.Append("]");
return sb.ToString();
}
else { return null; }
}
I hope this article is helpful to everyone's asp. net programming.