6

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.

9
  • Are you using WCF, ASMX? You could very easily return JSON data using ASP .NET MVC as well. Commented Dec 6, 2011 at 19:21
  • Have you considering using a RESTful service? That might work better for you in this case. Commented Dec 6, 2011 at 19:22
  • I am using ASMX... Very new to C# web services....I generally use PHP & its done so easily. Commented Dec 6, 2011 at 19:22
  • ASMX is the old, legacy technology, and should not be used for new development. You should use WCF instead. Commented Dec 6, 2011 at 19:23
  • @Zoidberg: can u please give me some pointers to restful... I believe i am using that.. <webServices> <protocols> <add name="HttpSoap"/> <add name="HttpPost"/> <add name="HttpGet"/> <add name="HttpPostLocalhost"/> <add name="Documentation"/> </protocols> </webServices> Commented Dec 6, 2011 at 19:24

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

20 Comments

Do I need to serialize the data using JavaScriptSerializer() before sending or do I just send the data as it is?
yes, you need to serialize it. You can either use straight serialization or use a custom serializer. Updating code.
Just updated the code. This is verbatim what I use and it works. Let me know if this helps.
I was doing it this way: JavaScriptSerializer js = new JavaScriptSerializer(); string strJSON = js.Serialize(locs); locs is an array of objects.. Is this an acceptable way?
Yes, if you have an array of objects the serializer will do the job just fine. I really recommend using a custom converter because the property names you have can be shortened when you're serializing the objects for the web. You got your thing working?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.