Category Archives: Uncategorized

How To Returning JSON from a .Net 4.0 WebService

I lose a lot of time to understand why my web service didn’t return me a JSON but an XML instead.
After many searches if find the answer and I want to share it.

With Framework 4.0 when you specify this:

1:  [WebMethod]  
2: [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
It isn’t enough for retrieve a JSON answer.
In order to retrieve a JSON you must use this code:
1:  Context.Response.Write(serializer.Serialize(jsonData));   

So an example of a WebMethod will be:

1:  [WebMethod]  
2: [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
3: public void MyWebMethod()
4: {
5: try
6: {
7: var retval = JsonConvert.SerializeObject(new MyObject());
8: Context.Response.Write(retval);
9: }
10: catch (Exception ex)
11: {
12: Context.Response.Write(string.Format("[ERROR: {0}]", ex.Message));
13: }
14: }