• DataTable转换成JSON字符串的函数


    public static string DataTableToJSON(DataTable table)
            {
                StringBuilder json = new StringBuilder();
                json.Append("[");
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    DataRow row = table.Rows[i];

                    // json object
                    json.Append("{");
                    for (int j = 0; j < table.Columns.Count; j++)
                    {
                        string columnName = table.Columns[j].ColumnName;
                        string columnType = table.Columns[j].DataType.Name;

                        // json field
                        if (columnType == "Int32" || columnType == "Int16" || columnType == "Decimal")
                        {
                            // don't surround numbers with quotes
                            json.AppendFormat("\"{0}\":\"{1}\"", columnName, row.IsNull(columnName) ? "" : row[columnName]);
                        }
                        else if (columnType == "Boolean")
                        {
                            // make the bool value lowercase
                            json.AppendFormat("\"{0}\":{1}", columnName, row.IsNull(columnName) ? "" : row[columnName].ToString().ToLower());
                        }
                        else
                        {
                            // everything else gets quotes around the data
                            json.AppendFormat("\"{0}\":\"{1}\"", columnName, row[columnName]);
                        }

                        if (j < table.Columns.Count - 1) json.Append(","); // add comma if not last column
                    }
                    json.Append("}");

                    if (i < table.Rows.Count - 1) json.Append(","); // add comma if not last row
                }
                json.Append("]");
                return json.ToString();
            }

  • 相关阅读:
    python找出数组中第二大的数
    【高并发解决方案】5、如何设计一个秒杀系统
    如何找出单链表中的倒数第k个元素
    二叉树的前序,中序,后序遍历
    剑指Offer题解(Python版)
    python之gunicorn的配置
    python3实现字符串的全排列的方法(无重复字符)
    python实现斐波那契数列
    每天一个linux命令(56):netstat命令
    每天一个linux命令(55):traceroute命令
  • 原文地址:https://www.cnblogs.com/cztom/p/1282448.html
Copyright © 2020-2023  润新知