Handling Larger JSON String Values In .NET And Avoiding Exceptions

Working with JSON within Web Services recently has become the latest and greatest simply because it plays so nicely with others and can often be very easily serialized and deserialized to fit your needs.
 
There is just something rewarding about having a massive collection of complex objects that can be thrown into a simple string and passed across however you see fit and then completely regenerated in its original collection in just a handful of code.
 
However sometimes these strings can get big and I mean really big, like exceeding default values big, and when this happens, exceptions happen. This post will cover a few ways that you can prevent a nasty InvalidOperationException that may look something like this with ease:
 
error
 
The Problem
 
You decide that paging data is for losers and decide to pull a graph of all of the data within your database, which will hypothetically contain thousands of complex objects, each with additional properties of their own. If your dataset is large enough, you’ll find yourself quickly exceeding the bounds that your Serializer can handle and you’ll be met with an exception and no data.
 
The Solution
 
There are three basic methods of handling this depending on your current environment:
  1. Setting the MaxJsonLength property default value within your web.config. (This will only apply to web-services that handle JSON).
     
  2. Setting the MaxJsonLength property of a JavascriptSerializer object to perform your serialization.
     
  3. If you are using MVC4 to handle returning your JSON values, you may want to override the default JsonResult() ActionResult and change the maximum size manually.
     
    Either of these changes will help you avoid any bumps in the road when passing across your large JSON values.

Option I: The MaxJsonLength Property for handling JSON in Web Services

 
The MaxJsonLength property which can be set within the web.config of your application controls the maximum size of the JSON strings that are accepted by the JsonSerializerclass. The default value is 102400 characters.
 
In order to increase the size of this value – you can just add the following code to your web.config file and set it to the value that you desire:
  1. <configuration>    
  2.    <system.web.extensions>  
  3.        <scripting>  
  4.            <webServices>  
  5.                <!-- Update this value to change the value to   
  6.                     a larger value that can accommodate your JSON   
  7.                     strings -->  
  8.                <jsonSerialization maxJsonLength="86753090" />  
  9.            </webServices>  
  10.        </scripting>  
  11.    </system.web.extensions>  
  12. </configuration>    
It is important to know that this setting within the web.config will only apply to actual Web Services that handle your JSON strings using the internal JsonSerializer. If you are still encountering issues after applying this change, you will likely want to continue reading and consider using an instance of the JsonSerializer class to handle setting this value.
 

Option II: Using the JavaScriptSerialzier and the MaxJsonLength Property to Handle Serializing JSON Values

 
Using an instance of a JavascriptSerializer will not actually inherit the previously defined within the web.config (as the web.config only applies to Web Services that handle the JSON) so you can easily just create an instance of the serializer and set the property accordingly:
  1. // Creates an instance of your JavaScriptSerializer   
  2. // and Setting the MaxJsonLength  
  3. var serializer = new JavaScriptSerializer() { MaxJsonLength = 86753090 };  
  4.   
  5. // Perform your serialization  
  6. serializer.Serialize("Your JSON Contents");   
This will allow you to easily your larger data and adjust your maximum size easily.
 

Option III: Overriding the MVC4 JsonResult Action Result to Handle the Maximum Size

 
Much like the previous examples, every time that you are going to return a JsonResultyou can simply add the MaxJsonLength property to a specific value depending on the context of your specific action:
  1. return new JsonResult() {   
  2.    Data = "Your Data",   
  3.    MaxJsonLength = 86753090   
  4. };  
Or using the Json() method:
  1. JsonResult result = Json("Your Data");   
  2. result.MaxJsonLength = 8675309;   
However, if you want a more widespread solution that you could use within a single area of your application, you may want to consider overriding the JsonResult class and set your value within this newer class:
  1. // This ActionResult will override the existing JsonResult   
  2. // and will automatically set the maximum JSON length  
  3. protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)    
  4. {  
  5.     return new JsonResult()  
  6.     {  
  7.         Data = data,  
  8.         ContentType = contentType,  
  9.         ContentEncoding = contentEncoding,  
  10.         JsonRequestBehavior = behavior,  
  11.         MaxJsonLength = Int32.MaxValue // Use this value to set your maximum size for all of your Requests  
  12.     };  
  13. }  

From a JSON to a JMAN

 
Those are just a few methods that you should be able to use if you ever encounter an issue when passing larger JSON strings across your Controllers or through the use of Web Services. I am sure that there are likely several other ways to handle these same problems, but hopefully one of these will help you out if you are in a tight spot.