zoukankan      html  css  js  c++  java
  • ASP.NET dataset转json和dataTable转json

    public class JsonParseService
        {
            /// <summary>
            /// dataset转Json
            /// </summary>
            /// <param name="ds"></param>
            /// <returns></returns>
            public static string DatasetToJson(System.Data.DataSet ds)
            {
                StringBuilder json = new StringBuilder();
                json.Append("{\"Tables\":");
                json.Append("[");
                foreach (System.Data.DataTable dt in ds.Tables)
                {
                    json.Append(DataTableToJson(dt));
                    json.Append(",");
                }
                json.Remove(json.Length - 1, 1);
                json.Append("]");
                json.Append("}");
                return json.ToString();
            }
            /// <summary>
            /// table转json
            /// </summary>
            /// <param name="dt"></param>
            /// <returns></returns>
            public static string DataTableToJson(System.Data.DataTable dt)
            {
                StringBuilder jsonBuilder = new StringBuilder();
                jsonBuilder.Append("{\"Name\":\"" + dt.TableName + "\",\"Rows");
                jsonBuilder.Append("\":[");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    jsonBuilder.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        jsonBuilder.Append("\"");
                        jsonBuilder.Append(dt.Columns[j].ColumnName);
                        jsonBuilder.Append("\":\"");
                        jsonBuilder.Append(dt.Rows[i][j].ToString().Replace("\"", "\\\""));
                        jsonBuilder.Append("\",");
                    }
                    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                    jsonBuilder.Append("},");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("]");
                jsonBuilder.Append("}");
                return jsonBuilder.ToString();
            }
        }

    ASP.NET讨论qq群  :171560784   欢迎各位加入

  • 相关阅读:
    FCKeditor的问题
    每天学习一点点(2010年二月)
    Excel使用小技巧
    JavaScript 取页面属性
    附加 数据库错误 5120
    CSS中元素水平居中显示的方法
    css中height:100%不起作用的解决方法
    SQL SERVER数据库开发之存储过程应用(转载)
    双路由器双小型交换机组建公司网络,2个公网IP上网案例(转载)
    如何解决VS2005没有代码智能提示(联想)的问题(转载)
  • 原文地址:https://www.cnblogs.com/kezhiping/p/3048932.html
Copyright © 2011-2022 走看看