Anders G. Nordby

Senior Systems Consultant at CGI

Returning JSON from a .Net 4.0 web service

Even when specifying this

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]

my web service insisted on wrapping the JSON inside an XML with a single element, like so:

<string>{"one":"One","two":"Two","three":"Three"}</string>

I searched the web for a long time, trying various non-working suggestions, and was on the verge of giving up.
Then I found the answer (on StackOverflow, obviously):
http://stackoverflow.com/questions/2058454/asp-net-webservice-is-wrapping-my-json-reponse-with-xml-tags

Not in the accepted solution, but a bit further down, the true solution can be found:

In your code, don’t “return” the json. Use instead:
Context.Response.Write(ser.Serialize(jsonData));
Then you’ll be good.

In other words, do this:

        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void MyMethod(... params ...)
        {
            try
            {
                var retval = new JavaScriptSerializer()
                    .Serialize(new MyObject());

                Context.Response.Write(retval);
            }
            catch (Exception ex)
            {
                Context.Response.Write(string.Format("[ERROR: {0}]", ex.Message));
            }
        }
Advertisements

12 responses to “Returning JSON from a .Net 4.0 web service

  1. Gavin Rice 2013-08-27 at 11:39

    Hi, I wonder whether an HTTPHandler would be better solution to the problem considering that you had to use a Response.Write to get the JSON out?

    Thanks,

    Gav

  2. Stephen Kennedy 2013-10-08 at 10:11

    Sorry but you’re still on the wrong track. You do NOT need to do any manual serialisation whatsoever.

    [System.Web.Script.Services.ScriptService] // allows it to return JSON
    public TypeOf MyObject MyMethod(… params …) {
    return new new MyObject();
    }

    POST with a contentType of “application/json” and asp.net will automatically return the response as Json too. You might need some wrapper class to return exceptions. Unusually a lot of folks on StackOverflow haven’t grasped this. Please see my answer here http://stackoverflow.com/a/16335022/397817

  3. Stephen Kennedy 2013-10-08 at 10:12

    Correction, fat fingers:

    [System.Web.Script.Services.ScriptService] // allows it to return JSON
    public TypeOfMyObject MyMethod(… params …) {
    return new MyObject();
    }

  4. Stephen Kennedy 2013-10-08 at 10:38

    Here’s an example:

    ASMX:

    using System;
    using System.Collections.Generic;
    using System.Web.Services;

    [WebService(Namespace = “http://tempuri.org/”)]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]
    public class WebService : System.Web.Services.WebService {
    [WebMethod]
    public MyClass Example()
    {
    return new MyClass();
    }

    public class MyClass
    {
    public string Message { get { return “Hi”; } }
    public int Number { get { return 123; } }
    public List List { get { return new List { “Item1”, “Item2”, “Item3” }; } }
    }
    }

    HTML:

    Test

    $.ajax({
    type: “POST”,
    url: “WebService.asmx/Example”,
    contentType: “application/json; charset=utf-8”,
    dataType: “json”,
    data: “{ }”,
    error: function (XMLHttpRequest, textStatus, errorThrown) { alert(langError + ” ” + textStatus); },
    success: function (msg) {
    alert(msg.d.Message);
    }
    });

    Result:
    A JavaScript alert pops up with the message “Hi”.

  5. Anders G. Nordby 2013-10-10 at 09:20

    Thanks, Stephen! I really appreciate your feedback. This is my number one posting in terms of views – obviously because this is something a lot of people struggle with. Glad you could help out!

  6. Tyler Jones 2013-10-14 at 16:45

    http://mikesknowledgebase.com/pages/Services/WebServices.htm

    check out this article. really explains it very well super easy.

  7. dmb 2014-05-27 at 17:51

    Thank you! Solved my problem!!

  8. Fulano 2014-10-31 at 15:16

    Thank you! It was the best an more easier solution.

  9. Santosh 2014-11-04 at 07:38

    Thanx.. it is the perfect solution for me…

  10. Abdul Amin Khan 2016-09-22 at 10:33

    Thank you it is healpful for me

  11. Priscilla Haskin 2017-03-03 at 07:30

    Hi there very nice site!! Guy .. Beautiful .. Amazing .. I will bookmark your web site and take the feeds additionally…I am glad to find numerous useful info right here in the submit, we’d like work out more strategies in this regard, thanks for sharing.

  12. thanhluan 2017-03-14 at 09:19

    Thank very much! it’s work for me

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: