前后台传值一般情况下,都会用到json类型的数据,比较常见,但是每次用到的时候去网上找比较麻烦,所以自己记录一下,下次直接用。
构造的json串格式,如下:
[{"id":"0","name":"name","active":"active","user_id":"user_id","no_of_reports":"no_of_reports"},
{"id":"1","name":"name","active":"active","user_id":"user_id","no_of_reports":"no_of_reports"},
{"id":"2","name":"name","active":"active","user_id":"user_id","no_of_reports":"no_of_reports"},
{"id":"3","name":"name","active":"active","user_id":"user_id","no_of_reports":"no_of_reports"},
{"id":"4","name":"name","active":"active","user_id":"user_id","no_of_reports":"no_of_reports"},
{"id":"5","name":"name","active":"active","user_id":"user_id","no_of_reports":"no_of_reports"},
{"id":"6","name":"name","active":"active","user_id":"user_id","no_of_reports":"no_of_reports"},
{"id":"7","name":"name","active":"active","user_id":"user_id","no_of_reports":"no_of_reports"},
{"id":"8","name":"name","active":"active","user_id":"user_id","no_of_reports":"no_of_reports"},
{"id":"9","name":"name","active":"active","user_id":"user_id","no_of_reports":"no_of_reports"}]
一、构造DataTable
public DataTable getData() { DataTable dt = new DataTable(); dt.Columns.Add("id", typeof(Int32)); dt.Columns.Add("name", typeof(string)); dt.Columns.Add("active", typeof(string)); dt.Columns.Add("user_id", typeof(string)); dt.Columns.Add("no_of_reports", typeof(string)); for (int i = 0; i < 10; i++) { dt.Rows.Add(i, "name", "active", "user_id", "no_of_reports"); } return dt; }
二、DataTable转json
public string DataTableToJsonWithStringBuilder(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(); }
三、调用
DataTable dt = getData(); string str = DataTableToJsonWithStringBuilder(dt);