DataTable转换为Json字符串的三种方法

时间:2024-01-10 14:38:14
//第一种:使用StringBuilder 
 public string DataTableToJson(DataTable table)
{
var JsonString = new StringBuilder();
if (table.Rows.Count > )
{
JsonString.Append("[");
for (int i = ; i < table.Rows.Count; i++)
{
JsonString.Append("{");
for (int j = ; j < table.Columns.Count; j++)
{
if (j < table.Columns.Count - )
{
JsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\",");
}
else if (j == table.Columns.Count - )
{
JsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\"");
}
}
if (i == table.Rows.Count - )
{
JsonString.Append("}");
}
else
{
JsonString.Append("},");
}
}
JsonString.Append("]");
}
return JsonString.ToString();
}

//第二种:使用JavaScriptSerializer序列化数据

 using System.Web.Script.Serialization;  

 public string DataTableToJsonWithJavaScriptSerializer(DataTable table)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List < Dictionary < string, object >> parentRow = new List < Dictionary < string, object >> ();
Dictionary < string, object > childRow;
foreach(DataRow row in table.Rows)
{
childRow = new Dictionary < string, object > ();
foreach(DataColumn col in table.Columns)
{
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
}

//第三种:使用Json.Net DLL (Newtonsoft)。

这个方法中要添加Json.Net DLL引用,我们可以从Newtonsoft下载Json.Net DLL,再导入命名空间,代码如下:

 using Newtonsoft.Json;  

 public string DataTableToJsonWithJsonNet(DataTable table)
{
string JsonString=string.Empty;
JsonString = JsonConvert.SerializeObject(table);
return JsonString;
}