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

Error during serialization or deserialization using the JSON JavaScriptSerializer

If you are encountering an error that states "Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property." then this means that you have exceeded the maximum JSON length allowed by the JavaScriptSerializer.

What is JSON?

JSON stands for JavaScript Object Notation and is a lightweight format for storing and exchanging data. It is often used as a data interchange format between web services and client-side code.

What is JavaScriptSerializer?

JavaScriptSerializer is a class in .NET that is used to serialize and deserialize JSON data. It is commonly used in ASP.NET web applications to serialize data and return it to the client-side code.

How to fix the "maxJsonLength" error?

The "maxJsonLength" property in the JavaScriptSerializer class specifies the maximum length of JSON data that can be serialized or deserialized. By default, this value is set to 2097152 characters, which is equivalent to 4 MB.

To fix the "maxJsonLength" error, you can increase the value of the "maxJsonLength" property to a higher value. This can be done in two ways:

  • Method 1: Update the value in the web.config file
  • Method 2: Update the value in the code

Method 1: Update the value in the web.config file

You can increase the value of the "maxJsonLength" property by updating the web.config file of your ASP.NET application. The following code snippet shows how to update the value:


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

In this code snippet, we have updated the "maxJsonLength" property to the maximum value that is allowed by .NET, which is 2147483647 characters.

Method 2: Update the value in the code

You can also increase the value of the "maxJsonLength" property in your code. The following code snippet shows how to update the value:


JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;

In this code snippet, we have created an instance of the JavaScriptSerializer class and updated the "MaxJsonLength" property to the maximum value that is allowed by .NET, which is Int32.MaxValue.

After updating the "maxJsonLength" property, you should be able to serialize or deserialize JSON data without encountering the "maxJsonLength" error.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe