简体   繁体   English

C#字符串到数据集

[英]C# String to Dataset

I've tried to find the answer to this but I've found no success. 我试图找到答案,但是没有成功。 If it is possible how do you convert a string to a data set in C# so I can generate a JSON file from the data in my database table. 如果有可能,如何将字符串转换为C#中的数据集,以便我可以从数据库表中的数据生成JSON文件。

Here is my asmx file: 这是我的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;
        }
    }
}

Or is there a smarter way to export the data into a JSON file? 还是有一种更聪明的方法将数据导出到JSON文件?

EDIT 编辑
The error that I am receiving is 我收到的错误是

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

The error appears on the 'return jsonString;' 错误出现在“ return jsonString;”上 statement. 声明。

Your function is defined as returning a DataSet. 您的函数定义为返回数据集。

You are returning a string. 您正在返回一个字符串。

Change the function definition to return a string. 更改函数定义以返回字符串。

public String GetBookList()

If you want to return the DataSet, just return the "ds" variable. 如果要返回数据集,只需返回“ ds”变量。 Otherwise you are just returning a string that is a serialized version of the ds variable. 否则,您只是返回一个字符串,该字符串是ds变量的序列化版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM