将table转换为Json(Jquery的Ajax方法读取)


1. 创建Users表 

  1. create table Users  
  2. (  
  3.     UserId int identity(1,1) primary key,  
  4.     UserName varchar(20)  
  5. )  
  6.   
  7. insert into Users values('Bradley')  
  8. insert into Users values('Dan')  
create table Users
(
	UserId int identity(1,1) primary key,
	UserName varchar(20)
)

insert into Users values('Bradley')
insert into Users values('Dan')

 

2. 创建JsonHelper类

  1. public class JsonHelper  
  2.    {  
  3.        #region  序列化和反序列化  
  4.        // 序列化  
  5.        public static  string JsonSerializer<T>(T t)  
  6.        {  
  7.            // 使用 DataContractJsonSerializer 将 T 对象序列化为内存流。   
  8.            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof (T));  
  9.            MemoryStream ms = new MemoryStream();  
  10.            // 使用 WriteObject 方法将 JSON 数据写入到流中。   
  11.            jsonSerializer.WriteObject(ms, t);  
  12.            // 流转字符串  
  13.            string jsonString = Encoding.UTF8.GetString(ms.ToArray());  
  14.            ms.Close();  
  15.            //替换Json的Date字符串    
  16.            string p = @"\\/Date\((\d+)\+\d+\)\\/";     
  17.            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);    
  18.            Regex reg = new Regex(p);     
  19.            jsonString = reg.Replace(jsonString, matchEvaluator);  
  20.            return jsonString;  
  21.        }  
  22.        public static T JsonDeserialize<T>(string  jsonString)  
  23.        {  
  24.            //将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式    
  25.            string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";     
  26.            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);     
  27.            Regex reg = new Regex(p);    
  28.            jsonString = reg.Replace(jsonString, matchEvaluator);  
  29.            DataContractJsonSerializer jsonSerializer=new DataContractJsonSerializer(typeof(T));  
  30.            // 字符串转流  
  31.            MemoryStream ms=new MemoryStream(Encoding.UTF8.GetBytes(jsonString));  
  32.            // 通过使用 DataContractJsonSerializer 的 ReadObject 方法,将 JSON 编码数据反序列化为T   
  33.            T obj = (T) jsonSerializer.ReadObject(ms);  
  34.            return obj;  
  35.        }  
  36.        public static string ConvertJsonDateToDateString(Match match)  
  37.        {  
  38.            string result = string.Empty;  
  39.            DateTime dateTime=new DateTime(1970,1,1);  
  40.            dateTime = dateTime.AddMilliseconds(long.Parse(match.Groups[1].Value));  
  41.            dateTime = dateTime.ToLocalTime();  
  42.            result = dateTime.ToString("yyyy-MM-dd HH:mm:ss");  
  43.            return result;  
  44.        }  
  45.        private static string ConvertDateStringToJsonDate(Match m)  
  46.        {  
  47.            string result = string.Empty;     
  48.            DateTime dt = DateTime.Parse(m.Groups[0].Value);   
  49.            dt = dt.ToUniversalTime();     
  50.            TimeSpan ts = dt - DateTime.Parse("1970-01-01");    
  51.            result = string.Format("\\/Date({0}+0800)\\/",ts.TotalMilliseconds);     
  52.            return result;  
  53.        }  
  54.        #endregion  
  55.   
  56.        // 对象转换为Json  
  57.        public static  string  ObjectToJson(object obj)  
  58.        {  
  59.            JavaScriptSerializer js=new JavaScriptSerializer();  
  60.            try  
  61.            {  
  62.                return js.Serialize(obj);  
  63.            }  
  64.            catch (Exception exception)  
  65.            {  
  66.                  
  67.                throw new Exception(exception.Message);  
  68.            }  
  69.        }  
  70.        // 数据表转化为集合  
  71.        public static List<Dictionary<string,object>> DataTableToList(DataTable dt)  
  72.        {  
  73.            List<Dictionary<string ,object>> list=new List<Dictionary<stringobject>>();  
  74.            foreach (DataRow dataRow in dt.Rows)  
  75.            {  
  76.                Dictionary<string,object> dic=new Dictionary<stringobject>();  
  77.                foreach (DataColumn dc in dt.Columns)  
  78.                {  
  79.                    dic.Add(dc.ColumnName,dataRow[dc.ColumnName]);  
  80.                }  
  81.                list.Add(dic);  
  82.            }  
  83.            return list;  
  84.        }  
  85.        // 表转换为Json  
  86.        public static string DataTableToJson(DataTable dt)  
  87.        {  
  88.            return ObjectToJson(DataTableToList(dt));  
  89.        }  
  90.    }  
 public class JsonHelper
    {
        #region  序列化和反序列化
        // 序列化
        public static  string JsonSerializer<T>(T t)
        {
            // 使用 DataContractJsonSerializer 将 T 对象序列化为内存流。 
            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof (T));
            MemoryStream ms = new MemoryStream();
            // 使用 WriteObject 方法将 JSON 数据写入到流中。 
            jsonSerializer.WriteObject(ms, t);
            // 流转字符串
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            //替换Json的Date字符串  
            string p = @"\\/Date\((\d+)\+\d+\)\\/";   
            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);  
            Regex reg = new Regex(p);   
            jsonString = reg.Replace(jsonString, matchEvaluator);
            return jsonString;
        }
        public static T JsonDeserialize<T>(string  jsonString)
        {
            //将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式  
            string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";   
            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);   
            Regex reg = new Regex(p);  
            jsonString = reg.Replace(jsonString, matchEvaluator);
            DataContractJsonSerializer jsonSerializer=new DataContractJsonSerializer(typeof(T));
            // 字符串转流
            MemoryStream ms=new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            // 通过使用 DataContractJsonSerializer 的 ReadObject 方法,将 JSON 编码数据反序列化为T 
            T obj = (T) jsonSerializer.ReadObject(ms);
            return obj;
        }
        public static string ConvertJsonDateToDateString(Match match)
        {
            string result = string.Empty;
            DateTime dateTime=new DateTime(1970,1,1);
            dateTime = dateTime.AddMilliseconds(long.Parse(match.Groups[1].Value));
            dateTime = dateTime.ToLocalTime();
            result = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
            return result;
        }
        private static string ConvertDateStringToJsonDate(Match m)
        {
            string result = string.Empty;   
            DateTime dt = DateTime.Parse(m.Groups[0].Value); 
            dt = dt.ToUniversalTime();   
            TimeSpan ts = dt - DateTime.Parse("1970-01-01");  
            result = string.Format("\\/Date({0}+0800)\\/",ts.TotalMilliseconds);   
            return result;
        }
        #endregion

        // 对象转换为Json
        public static  string  ObjectToJson(object obj)
        {
            JavaScriptSerializer js=new JavaScriptSerializer();
            try
            {
                return js.Serialize(obj);
            }
            catch (Exception exception)
            {
                
                throw new Exception(exception.Message);
            }
        }
        // 数据表转化为集合
        public static List<Dictionary<string,object>> DataTableToList(DataTable dt)
        {
            List<Dictionary<string ,object>> list=new List<Dictionary<string, object>>();
            foreach (DataRow dataRow in dt.Rows)
            {
                Dictionary<string,object> dic=new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    dic.Add(dc.ColumnName,dataRow[dc.ColumnName]);
                }
                list.Add(dic);
            }
            return list;
        }
        // 表转换为Json
        public static string DataTableToJson(DataTable dt)
        {
            return ObjectToJson(DataTableToList(dt));
        }
    }


 3. 添加ashx代码文件

  1. public class GetData : IHttpHandler  
  2.    {  
  3.   
  4.        public void ProcessRequest(HttpContext context)  
  5.        {  
  6.            context.Response.ContentType = "text/plain";  
  7.            if (context.Request["action"]=="display")  
  8.            {  
  9.                context.Response.Write(JsonHelper.DataTableToJson(GetAllUsers()));  
  10.            }           
  11.        }  
  12.   
  13.        static SqlConnection conn = new SqlConnection("server=.;database=Test;uid=sa;pwd=123456");  
  14.        public static DataTable GetAllUsers()  
  15.        {  
  16.            string sql = "select * from users";  
  17.            SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);  
  18.            DataTable dt = new DataTable();  
  19.            adapter.Fill(dt);  
  20.            return dt;  
  21.        }  
  22.        public bool IsReusable  
  23.        {  
  24.            get  
  25.            {  
  26.                return false;  
  27.            }  
  28.        }  
  29.    }  
 public class GetData : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (context.Request["action"]=="display")
            {
                context.Response.Write(JsonHelper.DataTableToJson(GetAllUsers()));
            }         
        }

        static SqlConnection conn = new SqlConnection("server=.;database=Test;uid=sa;pwd=123456");
        public static DataTable GetAllUsers()
        {
            string sql = "select * from users";
            SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            return dt;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

 

4. 前端调用

  1. <html xmlns="http://www.w3.org/1999/xhtml" >  
  2. <head runat="server">  
  3.     <title></title>  
  4.     <script src="js/jquery-1.6.js" type="text/javascript"></script>  
  5.     <script type="text/javascript">  
  6.         $(function() {  
  7.             var options = {  
  8.                 type: 'post',  
  9.                 url: "/GetData.ashx",  
  10.                 dataType: "json",  
  11.                 data: { action: "display" },  
  12.                 success: function(data) {  
  13.                     var html = "<table border='2px' style='text-align:center;border-style:solid;border-width:2px;border-color:#00ff00;'><tr><td>UserId</td><td>UserName</td></tr>";  
  14.                     $.each(data, function(i, result) {  
  15.                         html += "<tr><td>" + result["UserId"] + "</td><td>" + result["UserName"] + "</td></tr>";  
  16.                     })  
  17.                     html += "</table>";  
  18.                     $("#divData").html(html);  
  19.                 }  
  20.             };  
  21.             $.ajax(options);  
  22.         });  
  23.     </script>  
  24. </head>  
  25. <body>  
  26.     <form id="form1" runat="server">  
  27.     <div id="divData">  
  28.       
  29.     </div>  
  30.     </form>  
  31. </body>  
  32. </html>  
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <script src="js/jquery-1.6.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            var options = {
                type: 'post',
                url: "/GetData.ashx",
                dataType: "json",
                data: { action: "display" },
                success: function(data) {
                    var html = "<table border='2px' style='text-align:center;border-style:solid;border-width:2px;border-color:#00ff00;'><tr><td>UserId</td><td>UserName</td></tr>";
                    $.each(data, function(i, result) {
                        html += "<tr><td>" + result["UserId"] + "</td><td>" + result["UserName"] + "</td></tr>";
                    })
                    html += "</table>";
                    $("#divData").html(html);
                }
            };
            $.ajax(options);
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="divData">
    
    </div>
    </form>
</body>
</html>


5. 效果图

 Image

6. 同样可以通过getJSON方法读取数据

  1. $.getJSON("/GetData.ashx",{ action: "display" },function(data) {  
  2.      var html = "<table border='2px' style='text-align:center;border-style:solid;border-width:2px;border-color:#00ff00;'><tr><td>UserId</td><td>UserName</td></tr>";  
  3.      $.each(data, function(i, result) {  
  4.          html += "<tr><td>" + result["UserId"] + "</td><td>" + result["UserName"] + "</td></tr>";  
  5.      })  
  6.      html += "</table>";  
  7.      $("#divData").html(html);  
  8.      })  
       $.getJSON("/GetData.ashx",{ action: "display" },function(data) {
            var html = "<table border='2px' style='text-align:center;border-style:solid;border-width:2px;border-color:#00ff00;'><tr><td>UserId</td><td>UserName</td></tr>";
            $.each(data, function(i, result) {
                html += "<tr><td>" + result["UserId"] + "</td><td>" + result["UserName"] + "</td></tr>";
            })
            html += "</table>";
            $("#divData").html(html);
            })


 

 转自:http://blog.csdn.net/bradleydan/article/details/7927862



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值