datatable如果想转换成JSON类型的数据,是需要处理的。直接用微软提供的JavaScriptSerializer类直接序列化,会报错。
所以这里需要贴上两个方法,专门用来转换datatable的
#region DataTable转换为JSON
///
/// DataTable生成JSON
///
///
///
public static string CreateJSON(DataTable dt)
{
Dictionarydit = new Dictionary ();
List> list = DateTableConverter(dt);
if (list != null)
{
dit[dt.TableName] = DateTableConverter(dt);
return new JavaScriptSerializer().Serialize(dit);
}
else
{
return "";
}
}
///
/// 将DataTable数据转化为字典类型
///
///
///
public static List> DateTableConverter(DataTable dt)
{
List> list = new List >();
string cloName = string.Empty;
foreach (DataRow dr in dt.Rows)
{
Dictionarycloumn = new Dictionary ();
foreach (DataColumn dc in dt.Columns)
{
cloName = dc.ColumnName;
cloumn.Add(cloName, dr[cloName].ToString());
}
list.Add(cloumn);
}
return list;
}
#endregion
2.调用代码如下
DataTable table = new DataTable("Table1");
DataColumn col1 = new DataColumn("ID", typeof(string));
DataColumn col2 = new DataColumn("Name", typeof(string));
table.Columns.Add(col1);
table.Columns.Add(col2);
DataRow row1 = table.NewRow();
row1["ID"] = "1";
row1["Name"] = "a";
table.Rows.Add(row1);
DataRow row2 = table.NewRow();
row2["ID"] = "2";
row2["Name"] = "b";
table.Rows.Add(row2);
string json = CreateJSON(table);
3.json结果如下
{"Table1":[{"ID":"1","Name":"a"},{"ID":"2","Name":"b"}]}
4.数组中每一个元素,都是一行数据。只要循环遍历,然后将结果添加入你已经创建好的table中就可以了。还有疑问,继续追问吧。我先去吃饭了。
$("#table1").append("