标签:
using System.Text;
using System.Collections.Generic;
public static string DataTable2Json(DataTable dt) { StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.Append("{\""); jsonBuilder.Append(dt.TableName.ToString()); jsonBuilder.Append("\":["); List<string> si = new List<string>(); for (int i = 0; i < dt.Rows.Count; i++) { StringBuilder sb = new StringBuilder(); sb.Append("{"); List<string> sf = new List<string>(); for (int j = 0; j < dt.Columns.Count; j++) { StringBuilder fb = new StringBuilder(); fb.Append("‘"); fb.Append(dt.Columns[j].ColumnName.Replace("‘", "‘‘")); fb.Append("‘:"); if (dt.Rows[i][j] != null) { string str = dt.Rows[i][j].ToString().Replace("‘", "‘‘"); str = str.Replace("\n", "\\n"); fb.AppendFormat("\‘{0}\‘", str); } else { fb.Append("null"); } sf.Add(fb.ToString()); } sb.Append(string.Join(",", sf.ToArray())); sb.Append("}"); si.Add(sb.ToString()); } jsonBuilder.Append(string.Join(",", si.ToArray())); jsonBuilder.Append("]"); jsonBuilder.Append("}"); return jsonBuilder.ToString(); }
public static string Dataset2Json(DataSet ds) { List<string> l = new List<string>(); foreach (DataTable dt in ds.Tables) { StringBuilder si = new StringBuilder(); si.Append("\""); si.Append(dt.TableName); si.Append("\":"); si.Append(DataTable2Json(dt)); l.Add(si.ToString()); } StringBuilder json = new StringBuilder(); json.Append("{"); json.Append(string.Join(",", l.ToArray())); json.Append("}"); return json.ToString(); }
标签:
原文地址:http://www.cnblogs.com/kandyvip/p/4512963.html