简体   繁体   中英

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.

Here is my asmx file:

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?


The error that I am receiving is

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

The error appears on the '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. Otherwise you are just returning a string that is a serialized version of the ds variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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