JavaScriptSerializer.MaxJsonLength属性用于获取或设置接受的JSON字符串的最大长度,超出设定值时序列化或反序列化会失败。常见的出错的场景有:
1、序列化:
以下代码在对象过大时会报错:进行序列化或反序列化时出错。字符串的长度超过了为 maxJsonLength 属性设置的值。
1. //jsonObj比较大的时候会报错
2. var serializer = new JavaScriptSerializer();
3. return serializer.Serialize(jsonObj);
使用Newtonsoft.Json也有此问题,解决方案是设置MaxJsonLength:
1. var serializer = new JavaScriptSerializer();
2. serializer.MaxJsonLength = Int32.MaxValue; //设置为int的最大值
3. return serializer.Serialize(jsonObj);
2、ajax访问WebService:
以jQuery方式访问WebService,如果POST的数据过大,也会收到HTTP500错误,解决方法是在Web.config中设置一下maxJsonLength:
1. <system.web.extensions>
2. <scripting>
3. <webServices>
4. <!--单位为字节-->
5. <jsonSerializationmaxJsonLength="1024000"/>
6. </webServices>
7. </scripting>
8. </system.web.extensions>
//访问调用方法
JavaScriptSerializer serializer = new JavaScriptSerializer();
32
33 ScriptingJsonSerializationSection section = ConfigurationManager.GetSection("system.web.extensions/scripting/webServices/jsonSerialization") as ScriptingJsonSerializationSection;
34
35 if (section != null)
36 {
37 serializer.MaxJsonLength = section.MaxJsonLength;
38 serializer.RecursionLimit = section.RecursionLimit;
39 }