C# DataTable to JSON

       /// <summary>
        /// datatable转换为json对象
        /// </summary>
        /// <param name="dt"></param>
        /// <returns>string</returns>
        public static string DataTableToJson(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
                return "[]";

            StringBuilder strbuild = new StringBuilder();

            int length = dt.Rows.Count;

            strbuild.Append("[");//转换成多个model的形式 
            for (int i = 0; i < length; i++)
            {
                strbuild.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    strbuild.Append("\"");
                    strbuild.Append(dt.Columns[j].ColumnName);
                    strbuild.Append("\":\"");
                    strbuild.Append(dt.Rows[i][j].ToString());
                    strbuild.Append("\",");
                }
                strbuild.Remove(strbuild.Length - 1, 1);
                strbuild.Append("},");
            }
            strbuild.Remove(strbuild.Length - 1, 1);
            strbuild.Append("]");
            return strbuild.ToString();
        }

 

posted @ 2017-09-22 17:06 araki 阅读(...) 评论(...) 编辑 收藏