Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
928 views
in Technique[技术] by (71.8m points)

asp.net - Escaped JSON response with [WebMethod]

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}

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 HTTP response header I can see that the JSON response is wrongly (?) escaped in the following way:

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

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

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

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

{"d":8080}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
[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 :(


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...