DataTable转为JSON数据格式代码
时间:2011-03-11 来源:墟零
public static string GetJSON(DataTable dt) { StringBuilder sb = new StringBuilder(); sb.Append("{\"totalCount\":" + dt.Rows.Count + ",\"data\":"); sb.Append("["); try { if (dt.Rows.Count > 0) { Hashtable ht = new Hashtable(); for (int i = 0; i < dt.Columns.Count; i++) { ht.Add(i, dt.Columns[i].ColumnName); } for (int i = 0; i < dt.Rows.Count; i++) { sb.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { sb.Append(string.Format("\"{0}\":\"{1}\",", ht[j], dt.Rows[i][j].ToString())); } sb.Remove(sb.ToString().LastIndexOf(","), 1); sb.Append("},"); } sb.Remove(sb.ToString().LastIndexOf(","), 1);2 ht.Clear(); ht = null; } } catch (Exception ex) { throw new Exception(ex.Message); } finally { sb.Append("]}"); } return sb.ToString(); }
相关阅读 更多 +