以JSON格式从数据库序列化数据

时间:2015-06-03 08:07:10

标签: c# asp.net json web-services asmx

我在asp.net中创建了一个Web服务,它以JSON格式序列化数据,并通过JQuery访问这个Web服务

using System;
using System.IO;
using System.Net;
using System.Web;
using System.Linq;
using System.Web.Hosting;
using System.Web.Services;
using System.Web.Script.Services;
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace Chart_WebService
{
    /// <summary>
    /// Summary description for Service
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public DataTable GetData()
        {
           string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
           using (SqlConnection con = new SqlConnection(constr))
           {
               using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
               {
                   using (SqlDataAdapter sda = new SqlDataAdapter())
                   {
                       cmd.Connection = con;
                       sda.SelectCommand = cmd;
                       using (DataTable dt = new DataTable())
                       {
                           dt.TableName = "Customers";
                           sda.Fill(dt);
                           return dt;
                       }
                   }
               }
           }
       }
    }
}

请帮我完成此解决方案,因为我无意完成此解决方案 希望你们好!

2 个答案:

答案 0 :(得分:3)

我不会返回DataTable。您可以使用原始ADO.NET并将结果填充到简单的Dictionary<string, object>中。使用Newtonsoft.Json,您可以序列化字典并将其返回。

答案 1 :(得分:0)

那么你最好使用Data Reader来获得这个解决方案然后转换为List,这个List将被序列化为JSON,代码将如下所示:

using (var conn = new SqlConnection(ConnectionString))
        {
            conn.Open();
            using (var comm = new SqlCommand(command, conn))
            {
                using (var reader = comm.ExecuteReader())
                {
                       Customers= reader.Cast<IDataRecord>().Select(x=>
                        new Customer
                        {
                            ID = (int)x["ID"],
                            name = x["name"].ToString(),

                        }).ToList();
                }
            }
        }
var json = JsonConvert.SerializeObject(Customers);

就是这样