…meie igapäevast IT’d anna meile igapäev…


ASP.NET MVC: JSON string too long – a solution

Filed under: ASP.NET MVC — Sander @ 11:33:53
Tags: , ,


If you get the InvalidOperationException:

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

when trying to serialize data to JSON representation, then most likely you are doing something wrong. AJAX is not meant to move large amounts of data – rethink your application!

However, sometimes the limit is too low – in my case, a web service test application for the client, so they could test their own web services before claiming they are ready. One of the services gives quite a lot of data – and the test app needed to show the data as XML as well, so the actual JSON size was 26MB (as a sidenote, both Chrome and Firefox 4 crashed while parsing the data – surprisingly, IE9 was the only browser which didn’t).

I tried the Web.config approach described on various pages (1, 2), but that didn’t help. Then I realized – they are talking about “plain” ASP.NET, not ASP.NET MVC. So, I tried not returning Json(myBigData), but created my own serializer, setting the data size limit to int.MaxValue (var serializer = new JavaScriptSerializer {MaxJsonLength = Int32.MaxValue};) and then used it to serialize the return data: return new JsonResult { Data = serializer.Serialize(myBigData) };

But I still got the same exception. Apparently the JsonResult does checking of its own – so, the actual solution is not to return JsonResult, but ContentResult:

public ActionResult MyFancyMethod()
	var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
	var result = new ContentResult
		Content = serializer.Serialize(myBigData),
		ContentType = "application/json"
	return result;

And there, 26MB returned as JSON without any issues. An alternative approach would be to write the JSON directly to the output (Response.Clear(); Response.ContentType = “application/json”; Response.Write(serializer.Serialize(myBigData);).

Blog at WordPress.com.