Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 783
kind_robot Avatar asked Aug 15 '11 20:08

kind_robot


People also ask

Are double quotes allowed in JSON?

JSON names require double quotes.

Does JSON care about single or double quotes?

Strings in JSON are specified using double quotes, i.e., " . If the strings are enclosed using single quotes, then the JSON is an invalid JSON .

What characters should be escaped in JSON?

In JSON the only characters you must escape are \, ", and control codes. Thus in order to escape your structure, you'll need a JSON specific function.

Do JSON keys need double quotes?

JSON (requires double-quotes around keys, also called property names, and requires double-quotes around string data values).


1 Answers

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)

like image 97
Jordão Avatar answered Sep 28 '22 04:09

Jordão