4 asp.net json web-services asmx
来自以下代码的JSON响应被错误地转义,如下所述.
我的网络方法是这样的:
[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;
}
Run Code Online (Sandbox Code Playgroud)
从控制台我得到:
{"field1":vaule1,"field2":value2}
Run Code Online (Sandbox Code Playgroud)
来自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);
}
});
Run Code Online (Sandbox Code Playgroud)
问题是在HTTP响应头中我可以看到JSON响应以下列方式被错误地(?)转义:
{"d":"{\"field1\":value1,\"field2\":value2}"}
Run Code Online (Sandbox Code Playgroud)
奇怪的是控制台打印很好(但还没有封装在{d:...}中
{"field1":value1,"field2":value2}
Run Code Online (Sandbox Code Playgroud)
使用类似的代码,如果我调用返回基本类型(无对象)的[WebMethod],JSON响应就可以了.喜欢:
{ "d":8080}
[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();
}
}
Run Code Online (Sandbox Code Playgroud)
您不需要JSON序列化程序,使用ScriptService属性对其进行标记可以使其具有序列化JSON的能力.你正在序列化JSON,然后再次序列化:(
| 归档时间: |
|
| 查看次数: |
6990 次 |
| 最近记录: |