views:

1340

answers:

2

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

My webmethod is like this:

    [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}

The from JS:

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

The problem is that in HTTP response header I can see that the JSON response is wrongly (?) escaped in the following way:

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

The strange is that the console print is fine (but not yet encapsulated in {d: ...}

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

Whit similare code if I call a [WebMethod] that returns basic types (no object) the JSON response is ok. Like:

{"d":8080}

+3  A: 

Why are you calling JavaScriptConvert.SerializeObject?

Can't you just change the return type of your method to be the type returned by pu.getMyObject() and the framework 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're serializing your object into a JSON format and then, when you return from the method, the framework is serializing that string (which contains JASON formatted data) into a JSON format.

Martin Peck
Now the response is an empty {}
+3  A: 
[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 dont need a JSON serializer, tagging it with the ScriptService attribute gives it tie ability to serialize JSON out. You were pre serializing the JSON and then serializing it again :(

Chad Grant
Now the response is an empty {}
your object actually have properties? And have installed the System.Web.Extensions ? 3.5 sp1 adds alot of stuff
Chad Grant
your names field1, leads me to believe they are fields, change to Property and give it a go
Chad Grant