1、序列化:
以下代碼在對象過大時會報錯:進行序列化或反序列化時出錯。字符串的長度超過了為 maxJsonLength 屬性設置的值。
- //jsonObj比較大的時候會報錯
- var serializer = new JavaScriptSerializer();
- return serializer.Serialize(jsonObj);
使用Newtonsoft.Json也有此問題,解決方案是設置MaxJsonLength:
- var serializer = new JavaScriptSerializer();
- serializer.MaxJsonLength = Int32.MaxValue; //設置為int的最大值
- return serializer.Serialize(jsonObj);
2、ajax訪問WebService:
以jQuery方式訪問WebService,如果POST的數據過大,也會收到HTTP500錯誤,解決方法是在Web.config中設置一下maxJsonLength:
- <system.web.extensions>
- <scripting>
- <webServices>
- <!--單位為字節-->
- <jsonSerializationmaxJsonLength="1024000"/>
- </webServices>
- </scripting>
- </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 }