I’m returning a JSON structure from an MVC action that looks something like this:
[HttpPost]
public ActionResult GetStudents(string name)
{
//
// Filter list of students...
//
return Json(new {
aaData = students.ToList().Select(s => new [] {
String.Format(@"<span style='display:none;'>{0}</span>{1}", s.Id, s.StudentNumber),
String.Format(@"<a href='../../Student/Details/{0}'>{1}</a>", s.Id, s.FullName),
String.Format(@"<a href='../../Student/Edit/{0}'>Edit</a>", s.Id)
})
}, JsonRequestBehavior.DenyGet);
}
The resulting JSON is coming out looking like this:
{"aaData":
[
["\u003cspan style=\u0027display:none;\u0027\u003e3\u003c/span\u003e009165",
"\u003ca href=\u0027../../Student/Details/3\u0027\u003eJohn Smith\u003c/a\u003e",
"\u003ca href=\u0027../../Student/Edit/3\u0027\u003eEdit\u003c/a\u003e"],
... Lots more ...
]
}
Which works fine. But the full JSON comes out to be around 1.7 MB. I think that this could be trimmed down significantly if the HTML tags within the JSON weren’t all unicode encoded. According to the JSON spec, it doesn’t look like these would need to be encoded:
any-Unicode-character-
except-“-or-\-or-
control-character
Is there any way keep .NET from writing out the JSON this way, or is there any other way to trim down the amount of data that I need to transmit?
The first thing to do is replace the JSON serializer, by creating your own result class and controller extension methods for producing it.
Something along the lines of:
And the controller extension method:
Allowing you to use your own serialization code like so:
You’ll need to plug in a serializer that formats your JSON response appropriately. I can strongly recommend using ServiceStack.Text for this (on NuGet), as it is extremely fast, easy to get up and running and supports most common scenarios. Another popular alternative to Microsoft’s built-in offering is NewtonSoft’s JsonSerializer (also on NuGet).
The benefit of this approach is that you get better control over how your result is rendered. If you have large amounts of data to send, having a fast serializer can make quite a difference.
That said, you really ought to only use JSON for sending data across the wire (as opposed to markup). Frameworks such as knockout make it very easy to do client-side rendering of JSON data retrieved from a server. Going in this direction should be your long term goal, but using a custom serializer will be a benefit to either solution.