通常我们使用JavaScriptSerializer或者JSON.NET来序列化一个对象,但对于Datatable来说,其包含的数据比它的可序列化的属性更重要。
我尝试把DataRow转化为一个Directory对象,然后将每一个Directory对象放入List中,最终生成的是DataRow的数组,代码如下:
/// <summary> /// DataTable转为json /// </summary> /// <param name="dt">DataTable</param> /// <returns>json数据</returns> public static string ToJson(DataTable dt) { List<Dictionary<string, object>> list = new List<Dictionary<string, object>>(); foreach (DataRow dr in dt.Rows) { Dictionary<string, object> result = new Dictionary<string, object>(); foreach (DataColumn dc in dt.Columns) { result.Add(dc.ColumnName, dr[dc]); } list.Add(result); } return SerializeToJson(list); }
/// <summary> /// 序列化对象为Json字符串 /// </summary> /// <param name="obj">要序列化的对象</param> /// <param name="recursionLimit">序列化对象的深度,默认为100</param> /// <returns>Json字符串</returns> public static string SerializeToJson(this object obj, int recursionLimit = 100) { JavaScriptSerializer serialize = new JavaScriptSerializer(); serialize.RecursionLimit = recursionLimit; return serialize.Serialize(obj); }