Andiih
Andiih

Reputation: 12423

How to return datatable / dataset from c# web service as JSON

I have web services returning strings as JSON by dint of using

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

and calling them from the client with headers Content-type = application/json

this was all going well until I needed to return a table of results.

I have tried using the code here http://www.west-wind.com/Weblog/posts/471835.aspx which succesfully encodes my dataset as JSON and returns a string, but this is in turn then encoded with escapes as part of the return from the .net service which is not what is wanted at all. What type should my WebMethod return in order to get a datatable or dataset properly encoded as JSON ?

Upvotes: 4

Views: 12357

Answers (2)

Andiih
Andiih

Reputation: 12423

I have solved this by creating a custom class which represents the data I need to return, and then setting the return type of the service to a List . This does involve an extra step to iterate through the datatable and build the list, but in the end I think I am happier returning the list of objects rather than the raw data - its probably a better practice anyway.

Upvotes: 1

user154901
user154901

Reputation:

Short answer, use eval on the string like: var ds = eval(responseText);.

I use Microsoft.Web.Preview.dll instead of Newtonsoft. I feel Newtonsoft is a bit more code than Microsoft. And it sends you a string, not a JSON object. Whereas in Microsoft you don't need to write all that extra code. Download Microsoft.Web.Preview.dll (called ASP.NET Futures). Add the following to your web.config:

<system.web.extensions>
    <scripting>
        <webServices>
            <jsonSerialization maxJsonLength="33554432">
                <converters>
                    <add name="DataSetConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataSetConverter, Microsoft.Web.Preview"/>
                    <add name="DataRowConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataRowConverter, Microsoft.Web.Preview"/>
                    <add name="DataTableConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataTableConverter, Microsoft.Web.Preview"/>
                </converters>
            </jsonSerialization>
        </webServices>
    </scripting>
</system.web.extensions>

Upvotes: 3

Related Questions