ASP.NET的WebMethod返回JSON裹报价 [英] ASP.NET WebMethod Returns JSON wrapped in quotes

查看:154
本文介绍了ASP.NET的WebMethod返回JSON裹报价的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有它一个WebMethod一个asp.net页面传递JSON回到我的JavaScript。

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

贝娄是Web方法:

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

问题是双引号包裹下的D的一切。有件事情我已经在Web方法或返回数据不带引号的一些其他手段错过了什么?我真的不希望被剥离出来的客户端每次。此外,我见过的其他文章的地方不会发生这种情况。

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.

任何帮助将是AP preciated感谢。

Any help would be appreciated thanks.

推荐答案

我假设你想返回对象的JSON重新presentation

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

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

但你的方法签名返回一个字符串。在ASP.Net框架序列化的是正确连载字符串响应。换句话说,如果你的函数是

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

这只是碰巧响应有需要转义双引号。

您明明只是想获得的对象。你有2个选择: -

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

1)使用评估在JavaScript把串入一个对象如

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

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

2)或(这是我的prefered解决方案)有你的方法返回一个实际的对象,并让JSON serialisationof框架为你做的繁重

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

您将看到这个生成你可能原先预期的响应(例如
{D:{名字:约翰,姓氏:史密斯}}

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

这篇关于ASP.NET的WebMethod返回JSON裹报价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆