DataTable 转换成 Json的3种方法
返回的都是string
1.using Newtonsoft.Json (推荐)
using Newtonsoft.Json;
public string DataTableToJsonWithJsonNet(DataTable table)
{
string JsonString=string.Empty;
JsonString = JsonConvert.SerializeObject(table);
return JsonString;
}
2.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);
}
3.using System.Text;
public string DataTableToJson(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();
}