Solving the .NET JavaScriptSerializer problem with large datasets

Posted: (EET/GMT+2)

 

If you are working with large datasets in ASP.NET MVC applications and you are regularly returning JsonContent from your controller action methods, you might run into the following exception:

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

By default, Microsoft's own JSON serializer maxes out at 100 KiB of data, which can be too low a value for your needs. Luckily, you can easily solve this in two ways: either, setting a new larger default value in web.config, or serializing the JSON data by hand in those controller action methods that need to support large datasets.

To edit web.config, set the value on the "jsonSerialization" element under "system.web.extensions". Alternativelt, here's a C# example that sets the limit to 10 MiB:

JavaScriptSerializer serializer = new JavaScriptSerializer()
{
    MaxJsonLength = 10 * 1024 * 1024 // 10 MiB
};
ContentResult jsonContent = new ContentResult
{
    Content = serializer.Serialize(result),
    ContentType = "application/json"
};

return jsonContent;

Hope this helps!