铭轩同学

铭轩,为自己代言!

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace Common
{
    public class JsonHelper
    {

        /// <summary>
        /// DataTable 转 Json
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="fromCount">来自的行数</param>
        /// <param name="totalCountStr">总行数</param>
        /// <param name="tbname">表名</param>
        /// <returns></returns>
        public static string DT2JSON(DataTable dt, string tbname)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{\"" + tbname + "\":[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i > 0)
                    jsonBuilder.Append(",");
                jsonBuilder.Append("{");
                jsonBuilder.Append("\"no\":\"" + i + "\",");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (j > 0)
                        jsonBuilder.Append(",");
                    if (dt.Columns[j].DataType.Equals(typeof(DateTime)) && dt.Rows[i][j].ToString() != "")
                        jsonBuilder.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\": \"" + Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy-MM-dd HH:mm:ss") + "\"");
                    else if (dt.Columns[j].DataType.Equals(typeof(String)))
                        jsonBuilder.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\": \"" + dt.Rows[i][j].ToString().Replace("\\", "\\\\").Replace("\'", "\\\'").Replace("\t", " ").Replace("\r", " ").Replace("\n", "<br/>") + "\"");
                    else
                        jsonBuilder.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\": \"" + dt.Rows[i][j].ToString() + "\"");
                }
                jsonBuilder.Append("}");
            }
            jsonBuilder.Append("]}");
            return jsonBuilder.ToString();

        }
    }
}

  

posted on 2014-05-15 17:38  铭轩同学  阅读(600)  评论(0编辑  收藏  举报