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

  • 相关阅读:
    itertools mode 之 combinations用法
    Java排序方法及效率测试
    python数据处理——csv文件读取
    python数据处理——bsonId与时间戳的相互转换
    python图文识别案例
    python数据处理——字符串转数值类型
    ajax实现异步请求
    使用redis的evalsha功能实现获取数据时备份数据
    U盘写入保护去除(非物理性的)
    Git——.gitignore文件语法规范
  • 原文地址:https://www.cnblogs.com/cztom/p/1282448.html
Copyright © 2020-2023  润新知