Javascriptserializer. maxjsonlength exception

Source: Internet
Author: User

The javascriptserializer. maxjsonlength attribute is used to obtain or set the maximum length of the received JSON string. serialization or deserialization fails when the specified value is exceeded. Common error scenarios include:

1. serialization:

The following code reports an error when the object is too large: an error occurs during serialization or deserialization. The length of the string exceeds the value set for the maxjsonlength attribute.

 
 
  1. // If jsonobj is large, an error is returned.
  2. VaR serializer = new javascriptserializer ();
  3. Return serializer. serialize (jsonobj );

This problem also exists when newtonsoft. JSON is used. The solution is to set maxjsonlength:

 
 
  1. VaR serializer = new javascriptserializer ();
  2. Serializer. maxjsonlength = int32.maxvalue; // set it to the maximum value of Int.
  3. Return serializer. serialize (jsonobj );

2. Access WebService through Ajax:

When you access WebService in jquery mode, if the post data is too large, you will also receive an http500 error. The solution is to set maxjsonlength in Web. config:

  1. <System. Web. Extensions>
  2. <Scripting>
  3. <WebServices>
  4. <! -- Unit: byte -->
  5. <Jsonserialization maxjsonlength = "1024000" type = "codeph" text = "/codeph"/>
  6. </WebServices>
  7. </Scripting>
  8. </System. Web. Extensions>
 
 public static string SerializeObjToJson<T>(T data)        {            JavaScriptSerializer js = new JavaScriptSerializer();            js.MaxJsonLength = Int32.MaxValue;            return js.Serialize(data);        }
 
 public static T DeserializeJsonToObj<T>(string json)        {            JavaScriptSerializer js = new JavaScriptSerializer();            js.MaxJsonLength = Int32.MaxValue;            return js.Deserialize<T>(json);        }
 
Set the maxjsonlength attribute of javascriptserializer during compression and decompression.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.