您的位置:首页 > Web前端 > JavaScript

C# DataTable转换成JSON数据

2016-01-13 17:29 597 查看
public string DataTableToJson(DataTable dt)

{

string str = "";

if (dt.Rows.Count > 0)

{

string[] titlecolumn = new string[dt.Columns.Count];

for (int i = 0; i <= dt.Columns.Count - 1; i++)

{

titlecolumn[i] = dt.Columns[i].ColumnName;

}

for (int z = 0; z <= dt.Rows.Count - 1; z++)

{

str += "{";

for (int j = 0; j <= dt.Columns.Count - 1; j++)

{

if (j < (dt.Columns.Count - 1))

{

str += "\"" + titlecolumn[j] + "\":\"" + dt.Rows[z][j].ToString() + "\",\n";

}

else

{

if (z < (dt.Rows.Count - 1))

str += "\"" + titlecolumn[j] + "\":\"" + dt.Rows[z][j].ToString() + "\"},\n";

else

str += "\"" + titlecolumn[j] + "\":\"" + dt.Rows[z][j].ToString() + "\"}\n";

}

}

}

}

return "[" + str + "]";

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: