Ajax无法正确读取Serialized Json字典

时间:2014-10-22 17:39:59

标签: c# jquery ajax json dictionary

这就是我在c#code

中的内容
using Newtonsoft.Json;
.....
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("id", id.ToString());
d.Add("type", "error");
d.Add("msg", pex.Message);
.....
return JsonConvert.SerializeObject(d);

我的AJAX

......
$.ajax({
                    type: "POST",
                    url: "Service1.svc/MyCall",
                    data: JSON.stringify(parameters),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: true,

                    beforeSend: function () {
                        $("#lblResult").html("loading");
                    },
                    success: function (data) {
                        $("#lblResult").html(data['id']);
                    },
......

这是Firebug中的回复

"{\"id\":\"1\",\"type\":\"error\",\"msg\":\"An exception occurred during a Ping request.\"}"

这是Firebug中的JSON

0       "{"
1       """ 
2       "i"
3       "d"
4       """
5       ":"
6       """
7       "1"
8       """
9       ","
10      """
11      "t"
ETC

问题:我无法获取数据['id']或任何数据['SOMETHING']。

我如何根据收到的回复得到它? 还有其他办法吗?

1 个答案:

答案 0 :(得分:1)

这看起来好像没有正确地将JSON转换回JavaScript对象。试试这个

success: function (data) { 
if (data.hasOwnProperty("d"))
            {
                var response = JSON.parse(data.d);
                $("#lblResult").html(response["id"]);
            }
            else
            {
                var response = JSON.parse(data);
                $("#lblResult").html(response["id"]);
            }
}

.d是必需的。因为出于安全原因,.Net添加了这个,在Why do ASP.NET JSON web services return the result in 'd'?可以找到比我能给出的更好的解释。

然后由于返回的值是JSON字符串,因此需要将其解析为Javascript对象