Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c# - double quotes in returned json

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

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...