获得从.NET Web服务上正确的JSON正确、NET、Web、JSON

由网友(╰”婯ㄦ藍つ)分享简介:我的服务方法:[WebMethod][ScriptMethod(ResponseFormat = ResponseFormat.Json)]public string getDataFromTrainingMaster(){string queryString = "select * from dbo.Trai...

我的服务方法:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getDataFromTrainingMaster()
{
    string queryString = "select * from dbo.Training_master";

    List<TrainingMasterDataStruct> results = new List<TrainingMasterDataStruct>();
    using (SqlConnection ObjConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconn"].ConnectionString))
    {
        using (SqlCommand Objcommand = new SqlCommand(queryString, ObjConnection))
        {
            try
            {
                ObjConnection.Open();
                using (SqlDataReader rd = Objcommand.ExecuteReader())
                {
                    while (rd.Read())
                    {
                        TrainingMasterDataStruct objDataStruct = new TrainingMasterDataStruct();
                        //objDataStruct.iOSCalender = "TrainingDetails".ToString();
                        objDataStruct.Training_Code = rd["Training_Code"].ToString();
                        objDataStruct.Training_Duration = rd["Training_Duration"].ToString();
                        objDataStruct.Training_Startdate = rd["Training_Startdate"].ToString();
                        objDataStruct.Training_Enddate = rd["Training_Enddate"].ToString();
                        objDataStruct.Trainer_ID = Convert.ToInt32(rd["Trainer_ID"].ToString());
                        objDataStruct.Training_Location = rd["Training_Location"].ToString();
                        objDataStruct.Comments = rd["Comments"].ToString();
                        objDataStruct.Keyword = rd["Keyword"].ToString();
                        objDataStruct.NumberofDays = Convert.ToInt32(rd["NumberofDays"].ToString());
                        results.Add(objDataStruct);
                        objDataStruct = null;
                    }
                }
                JavaScriptSerializer js = new JavaScriptSerializer();

                return js.Serialize(results).ToString(); 
            }
            catch (Exception ex)
            { 
                throw new Exception(ex+ "Error in opening database");
            }
        }
    }        
}

我的.NET Web服务返回的JSON如下:

My .net web service returns JSON 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}]

我需要它的格式如下:

I need it in the following format:

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

我怎样才能做到这一点?我需要这个格式,因为,我需要消耗这一个iPhone应用程序。

How can I do this? I need this format because, I need to consume this in an iPhone application.

推荐答案

您正试图有点太硬在这里 - 框架应该照顾编码为您

You're trying a little too hard here - the Framework should take care of the encoding for you.

首先,作为NEHA说,没有必要创建JSON字符串自己。返回列表,并让.NET连载为你的飞行。

First of all, as Neha says, there's no need to create the Json string yourself. Return the List and let .NET serialise it for you on the fly.

其次,非静态方法的签名表明这是一个ASMX文件(页面方法是静态的)。默认情况下,这些序列化到XML的,所以你必须解除或添加此属性:

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 this attribute:

[System.Web.Script.Services.ScriptService]

这使得它能够返回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响应的服务器。请参见 http://stackoverflow.com/a/6385489/397817 了解更多信息。

Thirdly and very importantly, the CLIENT must indicate to the server that it desires a JSON response. See http://stackoverflow.com/a/6385489/397817 for more info.

要测试和验证这第三点,而AP preciating你的目标是iPhone,我建议你按照上面的步骤,然后拨打电话到Web服务使用jQuery和监测的提琴手。是这样的:

To test and verify this third point, whilst appreciating your target is iPhone, I suggest you follow the above steps and then make a call to the web service 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请求/响应的样子 - 特别关注到了后,接受和内容类型头:

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

如果这个答案没有帮助,如果这仍然是一个活的问题(我想后者是不可能的),我认为你需要发布更多信息:.​​NET framework版本,iOS的code,这使得呼叫等等。

If this answer doesn't help and if this is still a live issue (I guess the latter is unlikely) I think you need to post more info: .NET framework version, the iOS code which makes the call etc.

阅读全文

相关推荐

最新文章