Escaped from a JSON response using [WebMethod]

The JSON response from the following code is erroneously escaped as described below.

My web method is as follows:

[WebMethod (Description="doc here")] [ScriptMethod(ResponseFormat=ResponseFormat.Json)] public string responseMyObject() { if (!Setup()) return ""; ... Proxy pu = new Proxy(...); ... string toReturn = JavaScriptConvert.SerializeObject(pu.getMyObject()); Console.WriteLine(toReturn); return toReturn; } 

from the console I get:

 {"field1":vaule1,"field2":value2} 

from JS:

 $.ajax({ type: "POST", url: "/myapi/myClass.asmx/responseMyObject", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { var object = msg.d; alert(object.field1); } }); 

The problem is that in the header of the HTTP response, I see that the JSON response is erroneous (?) Escaped as follows:

 {"d":"{\"field1\":value1,\"field2\":value2}"} 

What is strange is that console printing is fine (but not yet encapsulated in {d: ...}

 {"field1":value1,"field2":value2} 

With similar code, if I call [WebMethod], which returns the base types (without an object), the JSON response is fine. How:

{"d": 8080}

+4
source share
2 answers
 [WebService] [ScriptService] public class MyWebService : WebService { [WebMethod (Description="doc here")] [ScriptMethod( UseHttpGet=false, ResponseFormat=ResponseFormat.Json)] public MyObjectType responseMyObject() { Proxy pu = new Proxy(...); return pu.GetMyObject(); } } 

You do not need a JSON serializer marking it with the ScriptService attribute, which makes it possible to associate JSON with serialization. You pre-serialized JSON and then serialized it again :(

+6
source

Why are you calling JavaScriptConvert.SerializeObject?

Can you change the return type of your method to the type returned by pu.getMyObject (), and the structure will do the rest?

In other words...

 [WebMethod (Description="doc here")] [ScriptMethod(ResponseFormat=ResponseFormat.Json)] public MyObjectType responseMyObject() { Proxy pu = new Proxy(...); ... return pu.GetMyObject(); } 

At the moment, I think you serialize your object in JSON format, and then when you return from the method, the structure serializes this string (which contains JASON formatted data) in JSON format.

+3
source

All Articles