views:

2279

answers:

2

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 ?

+2  A: 

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>
Abibaby
the short answer assumes I am using JavaScript as the client. Its actually an iPhone application. Something similar might work, but JSON encoded JSON sounds like a bad idea anyway. I will try the ASP.NET Futures technique and see what I get out of that.
Andiih
I suspect this would work, but I am not sure of the stability of relying on Futures.
Andiih
I've marked this as the correct answer, because although in the end I chose to go another route I think this probably best answers the question. Thanks Abibaby
Andiih
A: 

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.

Andiih