码迷,mamicode.com
首页 > Web开发 > 详细

dataTable/dataSet转换成Json格式

时间:2015-05-18 22:39:09      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

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

 

dataTable/dataSet转换成Json格式

标签:

原文地址:http://www.cnblogs.com/kandyvip/p/4512963.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!