引用名称空知间using System.Web.Script.Serialization;(如果无法引用,请道添加程序集)
JavaScriptSerializer js = new JavaScriptSerializer();
//序列化成回json字符串
string json= js.Serialize("数据库查询出答来的数据");
/// <summary>
/// 将datatable转换为json
/// </summary>
/// <param name="dtb">Dt</param>
/// <returns>JSON字符串</returns>
public static string Dtb2Json(DataTable dtb)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
System.Collections.ArrayList dic = new System.Collections.ArrayList();
foreach (DataRow dr in dtb.Rows)
{
System.Collections.Generic.Dictionary<string, object> drow = new System.Collections.Generic.Dictionary<string, object>();
foreach (DataColumn dc in dtb.Columns)
{
drow.Add(dc.ColumnName, dr[dc.ColumnName]);
}
dic.Add(drow);
}
//序列化
return jss.Serialize(dic);
}