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

I have web services returning strings as JSON using

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

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

everything went well until I needed to return a table of results.

I tried using the code here http://www.west-wind.com/Weblog/posts/471835.aspx which successfully encodes my dataset as JSON and returns a string, but this in turn is encoded with screens as part of the return from the service. net, which is not needed at all. What type should my WebMethod return to get data or a dataset correctly encoded as JSON?

+4
source share
2 answers

Short answer, use eval in a line like: var ds = eval (responseText) ;.

I am using 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. If at Microsoft you do not need to write all this additional 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> 
+3
source

I solved this by creating a custom class that represents the data I need to return, and then setting the return type of the service to a list. This involves an extra step to iterate through the datatable and compile the list, but in the end, I think I'm happier returning a list of objects, rather than raw data - this is probably best practice.

0
source

All Articles