Double quotes in returned json

I have an action returning plain json. For demo purposes, I will insert sample code. A simple class to serialize:

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

The action that json returns:

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

That's where I am confused. When I call this action from the browser and look at the response using 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." A valid answer should look like this:

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

What's going on here? Thanks

+7
source share
1 answer

You do not need to serialize to 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, giving a string result.

The valid answer should be like this:

 {"FullName":"Homer Simpson"} 

(no surrounding quotes)

+16
source

All Articles