簡體   English   中英

C#字符串到數據集

[英]C# String to Dataset

我試圖找到答案,但是沒有成功。 如果有可能,如何將字符串轉換為C#中的數據集,以便我可以從數據庫表中的數據生成JSON文件。

這是我的asmx文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Data;
using System.Data.SqlClient;

namespace Book
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class Service : System.Web.Services.WebService
    {
        SqlConnection con;
        SqlDataAdapter adap;
        DataSet ds;

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public DataSet GetBookList()
        {
            con = new SqlConnection(@"Data Source=server;Initial Catalog=database;Persist Security Info=True;User ID=username;pwd=password;");
            adap = new SqlDataAdapter("SELECT * FROM tblBookList", con);
            ds = new DataSet();
            adap.Fill(ds, "tblBookList");

            var jsonString = new JavaScriptSerializer().Serialize(ds);
            return jsonString;
        }
    }
}

還是有一種更聰明的方法將數據導出到JSON文件?

編輯
我收到的錯誤是

Error: cannot implicitly convert type 'string' to 'System.Data.DataSet'

錯誤出現在“ return jsonString;”上 聲明。

您的函數定義為返回數據集。

您正在返回一個字符串。

更改函數定義以返回字符串。

public String GetBookList()

如果要返回數據集,只需返回“ ds”變量。 否則,您只是返回一個字符串,該字符串是ds變量的序列化版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM