以JSON格式序列化数据库中的数据

本文关键字:数据 数据库 序列化 JSON 格式 | 更新日期: 2023-09-27 17:53:14

我正在asp.net中创建一个以JSON格式序列化数据的web服务,并通过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;
                       }
                   }
               }
           }
       }
    }
}

请帮我完成这个解决方案,因为我不知道如何完成它希望你们!

以JSON格式序列化数据库中的数据

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

那么你最好使用Data Reader来解决这个问题,然后转换为一个列表,这个列表将被序列化为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);

就这样了