How to return JSON from a 2.0 asmx web service How to return JSON from a 2.0 asmx web service ajax ajax

How to return JSON from a 2.0 asmx web service


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.


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


You need to decorate your web method with the following:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

You've got the rest right :)

More info at Encosia and Andrew Roland's Blog

EDIT: As noted below this is .NET 3.5 only (I was unaware of this, my bad).