How to return JSON from a 2.0 asmx web service

Solution 1:

It's no problem to return JSON from ASMX services in ASP.NET 2.0. You just need the ASP.NET AJAX Extensions installed.

Do be sure to add the [ScriptService] decoration to your web service. That's what instructs the server side portion of the ASP.NET AJAX framework to return JSON for a properly formed request.

Also, you'll need to drop the ".d" from "msg.d" in my example, if you're using it with 2.0. The ".d" is a security feature that came with 3.5.

Solution 2:

The response is wrapped in a element because you're method says it will return a string. You could use this to be able to send plain json, but your wsdl will be fooled (the function is void but does respond data).

[WebMethod(Description="return pure JSON")]
public void retrieveByIdToPureJSON( int id )
{
  Context.Response.Write( JsonConvert.SerializeObject( mydbtable.getById(id) );
}

Good luck, tom

Btw: see Newtonsoft.Json for JsonConvert