Return JSON from ASMX web service, without XML wrapper?

Praneeta picture Praneeta · Dec 6, 2011 · Viewed 35.2k times · Source

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 further.

This is what I have done :

In my web service I have included : [System.Web.Script.Services.ScriptService] for the class & [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)] for the method

I have also used a JavaScriptSerializer() to convert my data to a string

I am calling this service using $.getJSON()

If I don't use that I get an Cross domain reference error.

To do this I had to setup m service to get the callback function name so I am passing this.Context.Request["callback"] + serialized Json Data;

But in the output I get it wrapped in

< string xmlns="http://XYZ...">  

The data within the tags is in the format I need

I also tried setting content type using : $.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8"});

But still no success.

Addded later: I accepted frenchie's anwser beacuse I know it is the correct approach but I stil cud not get it to work... I just put the webservice & website in the same domain & used xml, I know it wasnt the best way, but I had spent 2 days on it & could not afford to waste more.

Answer

frenchie picture frenchie · Dec 6, 2011

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.