System.InvalidOperationException – The length of the string exceeds the value set on the maxJsonLength property.

Yesterday I got a problem from one of my friend; he is getting a Javascript exception from some Ajax Page methods. The exception occurred when he tried to return a very long string from web method. The exception was like this.

Error: Sys.Net.WebServiceFailedException: The server method ‘WebServiceMethod’ failed with the following error: System.InvalidOperationException– Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

After doing some searching we resolved it. You can resolve this error by modifying the web.config file, and add / modify the Configuring JSON Serialization.

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

The default length is 102400.
You can get more information about this from MSDN : http://msdn.microsoft.com/en-us/library/bb763183.aspx