Asmx Web服务如何返回JSON而不是XML? [英] Asmx web service how to return JSON and not XML?

查看:473
本文介绍了Asmx Web服务如何返回JSON而不是XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务方法:

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

我的.net Web服务返回以XML包装的JSON,如下所示:

My .net web service returns JSON wrapped in XML as follows:

<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://tempuri.org/">   [{"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}]

我需要以下格式:

"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}]</string>

我该怎么做?

推荐答案

无需自己创建JSON字符串。返回 List< TrainingMasterDataStruct> 并让.NET对其进行即时序列化:

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;
}

第二,非静态方法签名表明这是一个asmx文件(页面方法是静态的)。默认情况下,这些序列化为xml,因此您需要取消注释或将 System.Web.Script.Services.ScriptService 属性添加到Web服务类:

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 {

这允许它返回JSON。一个问题:JSON序列化程序似乎可以比XML序列化更多类型,因此如果要输出或/-请在此处小心-在此处使用列表和数组而不是集合。

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.

第三次,并且非常重要,客户端必须向服务器表明它需要JSON响应。

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

要测试并验证这第三个要点,建议您按照上述步骤操作,然后使用jQuery从测试网页中调用该Web服务,并在提琴手。像这样的东西:

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) { }
    });

这是JSON请求/响应的样子-特别注意POST,Accept和Content -类型标头:

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

这篇关于Asmx Web服务如何返回JSON而不是XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆