1 #region 转换Table为JSON数据 2 ///3 /// 转换Table为JSON数据 4 /// 5 /// 6 ///7 public static string TableToJson(DataTable dt) 8 { 9 StringBuilder sb = new StringBuilder("[");10 foreach (DataRow row in dt.Rows)11 {12 if (!row.Equals(dt.Rows[0])) sb.Append(",");13 sb.Append("{ ");14 foreach (DataColumn col in dt.Columns)15 {16 if (!col.Equals(dt.Columns[0])) sb.Append(",");17 string value = GetText(row, col.ColumnName);18 if (string.IsNullOrEmpty(value)) continue; //跳过为空的数据19 sb.Append("\"").Append(col.ColumnName).Append("\":\"").Append(value).Append("\"");20 }21 sb.Append("}");22 }23 sb.Append("]");24 return sb.ToString();25 }26 /// 27 /// 从datable中读取文本28 /// 29 /// 30 /// 31 ///32 private static string GetText(DataRow row, string col)33 {34 return row.IsNull(col) ? string.Empty : row[col].ToString();35 }36 #endregion