如何在C#中将Linq to SQL数据序列化为JSON

问题描述 投票:-1回答:1

我正在尝试生成JSON。数据存在,但我的理解是我需要序列化它才能工作。我是C#的初学者,所以关于newtonsoft网站的文档对我来说有点陌生。这是我的C#代码。

public partial class Pages_ChartTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static IEnumerable<procReportSalesCountsResult> jsonData()
    {
        using (OpsDBDataContext dc = new OpsDBDataContext())
        {     
            return dc.ReportSalesCounts().ToList();          
        }   
    }
}

我序列化的最后一步是什么?我在ASP中使用Linq To SQL来提取这些数据。谢谢你们。

c# json serialization
1个回答
1
投票

直到4.5,.NET本身不支持JSON。从VS包管理器直接下载Newtonsoft的Nuget package JSON.net

http://james.newtonking.com/json

public static string jsonData() {
    var buffer = null;
    using (OpsDBDataContext dc = new OpsDBDataContext()) {
        buffer = dc.ReportSalesCounts().ToList();
    } 
    return JsonConvert.SerializeObject(buffer);
}
© www.soinside.com 2019 - 2024. All rights reserved.