Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScriptSerializer.MaxJsonLength exceeded. What's the best practice for handling this?

I've got a large amound of data I'm sending down to the client using jQuery's $.ajax() function. I'm calling a method in a ASP.NET web service that returns the JSON data. Everything is great for most searches, but when I've got a large data set to return I run into a issue with the JavaScriptSerializer MaxJsonLength property. What's the best practice for handling this? I don't want to just arbitrarily set a max length. Can I set the MaxJsonLength in the web service if the data being returned is larger than the current max or should I re-write and send down chucks of data to the client?

Here's the relevant snippet from the web service:

Dictionary<string, object> jsonValuePairs = new Dictionary<string, object>();
//add some data to the dictionary...
return System.Web.Script.Serialization.JavaScriptSerializer.Serialize(jsonValuePairs);
like image 671
Tim Scarborough Avatar asked Jun 25 '09 20:06

Tim Scarborough


People also ask

What is the maximum MaxJsonLength?

The maximum length of JSON strings. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data.

Can I set an unlimited length for MaxJsonLength?

The MaxJsonLength property cannot be unlimited, is an integer property that defaults to 102400 (100k).


2 Answers

The only way to set the maximum length for web methods that are called from client script is through the web.config file (below). What is your issue with setting this? I would do this every time over multiple xhr calls to stream parts of the data.

<system.web.extensions>
  <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="500000">
        </jsonSerialization>
      </webServices>
  </scripting>
</system.web.extensions>

UPDATE: The default size is 2097152 which is equivalent to 4 MB of Unicode string data. Are you really going to send that much data back to the client? If so ouch and you prob need to look at the app design as the user experience will be slow and cumbersome.

like image 166
redsquare Avatar answered Oct 07 '22 17:10

redsquare


2147483647 is the correct value to use. Just to avoid confusion in the code you can use something like

var JsonSerializer = new JavaScriptSerializer();
JsonSerializer.MaxJsonLength = Int32.MaxValue;
like image 35
DJ' Avatar answered Oct 07 '22 19:10

DJ'