在返回的JSON双引号 [英] double quotes in returned json

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

问题描述

我有一个动作返回一个简单的JSON。出于演示的目的,我将粘贴示例code。简单的类序列化:

I have an action returning a simple json. For demonstration purposes I will paste sample code. Simple class to serialize:

public class Employee
{
    public string FullName { get; set; }
}

返回的JSON的操作:

The action which returns the json:

public JsonResult Test()
{
    var employee = new Employee { FullName = "Homer Simpson" };
    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(employee);

    return Json(json, JsonRequestBehavior.AllowGet);
}

下面是我很困惑。当我打电话从浏览器这一行动,并期待在与小提琴手的反应,这是结果:

Here is where I am confused. When I call this action from the browser and look at the response with Fiddler, this is the result:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Mon, 15 Aug 2011 20:52:34 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 3.0
Cache-Control: private
Content-Type: application/json; charset=utf-8
Content-Length: 34
Connection: Close

"{\"FullName\":\"Homer Simpson\"}"

在Fiddler中JSON标签上写着选定的响应不包含有效的JSON文本。
有效的反应应该是这样的:

The "JSON" tab in Fiddler reads "The selected response does not contain valid JSON text". The valid response should be like this:

"{"FullName":"Homer Simpson"}"

这是怎么回事?
谢谢

What is going on here? Thanks

推荐答案

您不需要序列化为JSON自己,这应该做的:

You don't need to serialize into JSON yourself, this should do:

public JsonResult Test() {
  var employee = new Employee { FullName = "Homer Simpson" };
  return Json(employee, JsonRequestBehavior.AllowGet);
}

您code有效连载了两次,它给你一个字符串结果。

Your code effectively serializes it twice, which gives you a string result.

有效的反应实际上应该是这样的:

The valid response should actually be this:

{"FullName":"Homer Simpson"}

(不带引号周围)

(without the surrounding quotes)

这篇关于在返回的JSON双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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