dataTable/dataSet转换成Json格式

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();
    }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。