Return JSON from ASMX web service, without XML wrapper?

后端 未结 1 1496
长情又很酷
长情又很酷 2020-11-27 08:36

I need to get Json data from a C# web service.

I know there are several questions based on this, trust me I have read through quite a few but only to confuse me furt

相关标签:
1条回答
  • 2020-11-27 08:51

    Use this:

    var JsonString = ....;
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "YourWebServiceName.asmx/yourmethodname",
        data: "{'TheData':'" + JsonString + "'}",
        dataType: "json",
        success: function (msg) {
            var data = msg.hasOwnProperty("d") ? msg.d : msg;
            OnSucessCallBack(data);
        },
        error: function (xhr, status, error) {
            alert(xhr.statusText);
        }
    });
    
    function OnSuccessCallData(DataFromServer) {
     // your handler for success    
    }
    

    and then on the server side, in the code behind file that's auto-generated in your AppCode folder, you write something like this:

    using System.Web.Services;
    using System.Web.Script.Serialization;
    
        [System.Web.Script.Services.ScriptService]
        public class YourWebServiceName : System.Web.Services.WebService
        {
            [WebMethod]
            public string yourmethodname(string TheData)
            {
              JavascriptSerializer YourSerializer = new JavascriptSerializer();
              // custom serializer if you need one 
              YourSerializer.RegisterConverters(new JavascriptConverter  [] { new YourCustomConverter() });
    
              //deserialization
              TheData.Deserialize(TheData);
    
              //serialization  
              TheData.Serialize(TheData);
            }
        }
    

    If you don't use a custom converter, the properties between the json string and the c# class definition of your server-side object must match for the deserialization to work. For the serialization, if you don't have a custom converter, the json string will include every property of your c# class. You can add [ScriptIgnore] just before a property definition in your c# class and that property will be ignored by the serializer if you don't specify a custom converter.

    0 讨论(0)
提交回复
热议问题