El servicio web Asmx ¿cómo devolver JSON y no XML?

Mi método de servicio:

[WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string getDataFromTrainingMaster() { List results = new DAL().GetDataFromTrainingMaster(); JavaScriptSerializer js = new JavaScriptSerializer(); return js.Serialize(results).ToString(); } 

Mi servicio web .net devuelve JSON envuelto en XML de la siguiente manera:

   [{"Training_Code":"1234 ","Training_Duration":"2hrs ","Training_Startdate":"2/14/2013 3:00:00 PM","Training_Enddate":"2/14/2013 5:00:00 PM","Trainer_ID":1,"Training_Location":"B-Wing Training room-4","Comments":"C# training","Keyword":"C#1234","NumberofDays":1},{"Training_Code":"4321 ","Training_Duration":"16 ","Training_Startdate":"2/17/2013 10:30:00 AM","Training_Enddate":"2/17/2013 5:30:00 PM","Trainer_ID":2,"Training_Location":"A-Wing Training Room-6","Comments":"Objective-C","Keyword":"Obj-C4321","NumberofDays":2}] 

Lo necesito en el siguiente formato:

 "Training":[{"Training_Code":"1234 ","Training_Duration":"2hrs ","Training_Startdate":"2/14/2013 3:00:00 PM","Training_Enddate":"2/14/2013 5:00:00 PM","Trainer_ID":1,"Training_Location":"B-Wing Training room-4","Comments":"C# training","Keyword":"C#1234","NumberofDays":1},{"Training_Code":"4321 ","Training_Duration":"16 ","Training_Startdate":"2/17/2013 10:30:00 AM","Training_Enddate":"2/17/2013 5:30:00 PM","Trainer_ID":2,"Training_Location":"A-Wing Training Room-6","Comments":"Objective-C","Keyword":"Obj-C4321","NumberofDays":2}] 

¿Cómo puedo hacer esto?

No es necesario crear la cadena JSON usted mismo. Devuelva la List y deje que .NET la serialice sobre la marcha:

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

En segundo lugar, las firmas de métodos no estáticos sugieren que se trata de un archivo asmx (los métodos de página son estáticos). De forma predeterminada, se serializan en xml, por lo que deberá descomentar o agregar el atributo System.Web.Script.Services.ScriptService a la clase de servicio web:

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

Esto le permite devolver JSON. Un problema: el serializador JSON parece ser capaz de serializar más tipos que XML, así que tenga cuidado aquí si quiere generar / o – use listas y matrices aquí en lugar de colecciones.

En tercer lugar y muy importante , el CLIENTE debe indicar al servidor que desea una respuesta JSON.

Para probar y verificar este tercer punto, le sugiero que siga los pasos anteriores y luego realice una llamada al servicio web desde una página web de prueba utilizando jQuery y controle el tráfico en Fiddler . Algo como:

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

Esto es lo que parece una solicitud / respuesta JSON: preste especial atención a los encabezados POST, Accept y Content-Type:

 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": 

Intente cambiar su tipo de devolución a List y devolver ” results “. No necesita serializar la cadena usted mismo, ASP.NET con el atributo WebMethod se encargará de eso por usted.

Puedes intentar esto:

 var data = [{"Training_Code":"1234 ","Training_Duration":"2hrs ","Training_Startdate":"2/14/2013 3:00:00 PM","Training_Enddate":"2/14/2013 5:00:00 PM","Trainer_ID":1,"Training_Location":"B-Wing Training room-4","Comments":"C# training","Keyword":"C#1234","NumberofDays":1},{"Training_Code":"4321 ","Training_Duration":"16 ","Training_Startdate":"2/17/2013 10:30:00 AM","Training_Enddate":"2/17/2013 5:30:00 PM","Trainer_ID":2,"Training_Location":"A-Wing Training Room-6","Comments":"Objective-C","Keyword":"Obj-C4321","NumberofDays":2}] var result = JSON.stringify({ Training: data }) 

result le dará el resultado deseado.