Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

今天嘗試便用 JavaScriptSerializer 把公司一個資料庫的資料轉成 Json 放在公司的另一個程式上做Performance Test的時候出現以下的錯誤信

An unhandled exception of type ‘System.InvalidOperationException’ occurred in System.Web.Extensions.dll

Additional information: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

原因是因為我有太多資料..而預設的Json 字串大小是2097152個字元… 我的數據..文字比較多..
便所以出現這個錯誤信息..
解決方法 十分簡單..只是把 SerializerMaxJsonLength 的值比你的 資料更大便可以了

解決方法:

E.G.

// 建立 JavascriptSerializer Object
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
// 查看 JavascriptSerializer Object的 Default MaxJsonLength 是什麼
Console.WriteLine("Default MaxJsonLength value: " + serializer.MaxJsonLength.ToString());
// 更新 JavascriptSerializer Object的 MaxJsonLength 大小... 為Integer的最大值..因為他是Int32的 DataType
serializer.MaxJsonLength = Int32.MaxValue;
Console.WriteLine("Updated MaxJsonLength value: " + serializer.MaxJsonLength.ToString());

這應該可以解決這個問題

Hope you find it useful

Leave a Reply