[英]double quotes in returned json
I have an action returning a simple JSON.我有一个动作返回一个简单的 JSON。 For demonstration purposes, I will paste the sample code.
出于演示目的,我将粘贴示例代码。 Simple class to serialize:
简单的 class 序列化:
public class Employee
{
public string FullName { get; set; }
}
The action which returns the json:返回 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:
当我从浏览器调用此操作并使用 Fiddler 查看响应时,结果如下:
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\"}"
The "JSON" tab in Fiddler reads "The selected-response does not contain valid JSON text". Fiddler 中的“JSON”选项卡显示“所选响应不包含有效的 JSON 文本”。 The valid response should be like this:
有效的响应应该是这样的:
"{"FullName":"Homer Simpson"}"
What is going on here?这里发生了什么? Thanks
谢谢
You don't need to serialize into JSON yourself, this should do:您不需要自己序列化为 JSON ,应该这样做:
public JsonResult Test() {
var employee = new Employee { FullName = "Homer Simpson" };
return Json(employee, JsonRequestBehavior.AllowGet);
}
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) (没有周围的引号)
I got on this issue because another error, it could be useful for someone: Just using serialize, using in Model property i was getting the line below.我遇到了这个问题,因为另一个错误,它可能对某人有用: 只是使用序列化,在 Model 属性中使用我得到下面的行。
My serialize line return of my class return JsonConvert.SerializeObject(playlists)
--> server side我的 class 的序列化行返回
return JsonConvert.SerializeObject(playlists)
--> 服务器端
My Js line gettin serialized var JsonString = '@Model.PlaylistModelList'
我的 Js 行开始序列化
var JsonString = '@Model.PlaylistModelList'
Output: '[{"name":"Bastard_01.mp4","duration"...}]
Output:
'[{"name":"Bastard_01.mp4","duration"...}]
My corret Js Line: var JsonStrin2 = '@Html.Raw(Model.PlaylistModelList)'
我正确的 Js 行:
var JsonStrin2 = '@Html.Raw(Model.PlaylistModelList)'
Output: '[{"name":"Bastard_01.mp4","duration":45..."}]
Output:
'[{"name":"Bastard_01.mp4","duration":45..."}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.