Datatable转换为Json

时间:2024-01-10 14:42:56
        /// <summary>
/// Datatable转换为Json
/// </summary>
/// <param name="table">Datatable对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataTable dt)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
DataRowCollection drc = dt.Rows;
for (int i = ; i < drc.Count; i++)
{
jsonString.Append("{");
for (int j = ; j < dt.Columns.Count; j++)
{
string strKey = dt.Columns[j].ColumnName;
string strValue = drc[i][j].ToString(); Type type = dt.Columns[j].DataType;
jsonString.Append("\"" + strKey + "\":");
strValue = String.Format(strValue, type);
if (j < dt.Columns.Count - )
{
jsonString.Append("\"" + strValue + "\"" + ",");
}
else
{
jsonString.Append("\"" + strValue + "\"");
}
}
jsonString.Append("},");
}
jsonString.Remove(jsonString.Length - , );
jsonString.Append("]");
return jsonString.ToString();
}