using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Web; using System.Web.Script.Serialization; /// <summary> /// JsonConvert 的摘要说明 /// </summary> public class JsonConvert { #region dataTable转换成Json格式 /// <summary> /// dataTable转换成Json格式 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string ToJson(DataTable dt) { JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>(); Dictionary<string, object> childRow; foreach (DataRow row in dt.Rows) { childRow = new Dictionary<string, object>(); foreach (DataColumn col in dt.Columns) { childRow.Add(col.ColumnName, row[col]); } parentRow.Add(childRow); } return jsSerializer.Serialize(parentRow); } #endregion dataTable转换成Json格式 #region DataSet转换成Json格式 /// <summary> /// DataSet转换成Json格式 /// </summary> /// <param name="ds">DataSet</param> /// <returns></returns> public static string ToJson(DataSet ds) { StringBuilder json = new StringBuilder(); foreach (DataTable dt in ds.Tables) { json.Append("{\""); json.Append(dt.TableName); json.Append("\":"); json.Append(ToJson(dt)); json.Append("}"); } return json.ToString(); } #endregion }
时间: 2024-11-07 19:15:48