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   欢迎各位加入

  • 相关阅读:
    sublime manjaro
    codeforce 1027C 贪心算法
    codeforce B
    java生成随机数保留数点后两位
    form表单无限提交的问题
    Jquery TimePicker时间箭头无法加载的问题(http://localhost:8080/css/images/ui-icons_444444_256x240.png)
    Mysql 创建事件时出现near‘DO create event...’错误
    线程之实现
    redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool at redis.clients.util.Pool.getResource(Pool.java:53)
    Recursion递归
  • 原文地址:https://www.cnblogs.com/kezhiping/p/3048932.html
Copyright © 2011-2022 走看看