How does one return unescaped Json, using Json.Net in an MVC project?
So far, I serialize a basic object, and get Json.Net to serialize it:
public JsonResult GetTimelineJson()
{
var result = new MyGraph([some data...]);
return Json(JsonConvert.SerializeObject(result), JsonRequestBehavior.AllowGet);
}
Result:
"{\r\n \"id\": \"myGraph\",\r\n \"title\": \"Graph title\",\r\n [...]
Any attempts to wrap it an an HtmlString, etc, result in an empty set being passed across the wire (though the debug point shows it correctly un-escaped). I’ve checked that the content-type is set correctly in the HTTP headers.
The object is already serialized by Json.NET, and when you pass it to Json() it gets encoded twice. If you must use Json.NET instead of the built in encoder, then the ideal way to handle this would be to create a custom ActionResult accepts the object and calls Json.net internally to serialize the object and return it as an application/json result.
EDIT
This code is for the solution mentioned above. It’s untested, but should work.
and in your controller just do: