json序列化数据超出最大值(maxJsonLength)

时间:2016-04-12 12:56:22   收藏:0   阅读:5194

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                 }

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!