Asmx web service how to return JSON and not XML?

There’s no need to create the JSON string yourself. Return the List<TrainingMasterDataStruct> and let .NET serialise it for you on the fly:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<TrainingMasterDataStruct> getDataFromTrainingMaster()
{
   List<TrainingMasterDataStruct> list = doStuff();
   return list;
}

Secondly, the non-static method signatures suggest this is an asmx file (page methods are static). By default these serialise to xml so you will need to uncomment or add the System.Web.Script.Services.ScriptService attribute to the web service class:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

This allows it to return JSON. One issue: The JSON serialiser seems to be able to serialise more types than XML so be careful here if you want to output either/or – use Lists and arrays here rather than collections.

Thirdly and very importantly, the CLIENT must indicate to the server that it desires a JSON response.

To test and verify this third point, I suggest you follow the above steps and then make a call to the web service from a test web page using jQuery and monitor the traffic in Fiddler. Something like:

$.ajax({
        type: "POST",
        url: "WebService.asmx/getDataFromTrainingMaster",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "",
        success: function (msg) { }
    });

This is what a JSON request/response looks like – pay particular attention to the POST, Accept and Content-Type headers:

POST http://scrubbed/GetVehicles HTTP/1.1
x-requested-with: XMLHttpRequest
Accept-Language: en-gb
Accept: application/json, text/javascript, */*
Content-Type: application/json; charset=utf-8
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E; InfoPath.2)
Host: scrubbed
Content-Length: 0
Connection: Keep-Alive
Pragma: no-cache

HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Mon, 04 Oct 2010 10:49:12 GMT
Content-Length: 1417

{"d":{"Data":[{"Key":1,"Value":[{"VehicleId":15036,"VehicleAlias":"Whatever","Expiry":"\/Date(1915983035043)\/","Expired":false},{"VehicleId":

Leave a Comment