JavaScriptSerializer.MaxJsonLength異常

來源:互聯網
上載者:User

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.       <jsonSerialization maxJsonLength="1024000" /> 
  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);        }
 
在壓縮與解壓縮的時候設定其JavaScriptSerializer的MaxJsonLength的屬性即可

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.