views:

287

answers:

2

Hi, I have an asp.net page with a WebMethod on it to pass JSON back to my javascript.

Bellow is the web method:

[WebMethod]
public static string getData(Dictionary<string, string> d) {

    string response = "{ \"firstname\": \"John\", \"lastname\": \"Smith\" }";

    return response;

}

When this is returned to the client it is formatted as follows:

{ \"d\": \"{ \"firstname\": \"John\", \"lastname\": \"Smith\" }\" }

The problem is the double quotes wrapping everything under 'd'. Is there something I've missed in the web method or some other means of returning the data without the quotes? I don't really want to be stripping it out on the client everytime. Also I've seen other articles where this doesn't happen.

Any help would be appreciated thanks.

A: 

If you speak about JSON, all strings MUST be quoted. See http://www.json.org/ for description of JSON format.

Oleg
Yes I understand that but the inner JSON of the 'd' argument doesn't need to be wrapped in quotes too.
CL4NCY
I don't really understand your example. If you want return a free formatted string from the Web Method you can do this. If you want to use a use somewhere JSON format you should follow JSON specification.
Oleg
+3  A: 

I assume that you want to return the JSON representation of the object

 {
    firstname:"John",
    lastname:"Smith"
 }

but your method signature is returning a string. The ASP.Net framework serialisation is correctly serialising the string response. Put another way, if your function was

string response = "foo";
return response; 

You would not be surprised if the output was

{"d":{"foo"}}

It just happens that response has double quotes that need to be escaped.

You obviously just want to get at the object. You have 2 options: -

1) use eval in your javascript to turn the string into an object e.g.

function onSuccessCallback(retval) {
     var obj = eval(retval.d);
}`

2) or (and this is my prefered solution) have your method return an actual object and let the JSON serialisationof the framework do the heavy lifting for you

[WebMethod]
public static object getData(Dictionary<string, string> d) {
    var response = new { firstname = "John", lastname="Smith" };
    return response;
}

You will see that this generates the response that you probably originally expected (e.g. {"d":{"firstname":"John", "lastname":"Smith"}}

Chris F
PS. If you want to keep your function returning a string containing the JSON, then I suggest using something like Risk Strahl's ToJson extension function [http://www.west-wind.com/weblog/posts/442969.aspx]. Your method body can then be new {firstname="John"}.ToJson().
Chris F
Thanks for your response, this is very interesting. I didn't realise you could create objects that way in c#. However I have already created a framework for building json strings from objects so will have to use the client-side option. I'll look into the server-side option in future projects. Thanks.
CL4NCY