使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了为 maxJsonLength 属性设置的值。

2019年12月09日 16:11 · 阅读(314) ·

参考

http://www.uwenku.com/question/p-bmjemgrh-oa.html

https://www.codenong.com/1151987/

开发环境

名称 版本
操作系统 Windows 10 X64
VS Visual Studio 2010
MVC MVC3

问题描述

在一个 Controller 中返回 Json 数据时,页面报错

  1. Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
  2. 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了为 maxJsonLength 属性设置的值。

原因分析

是因为 Json() 方法默认的返回值大小是 默认值为102400(100k)

问题解决

接口-设置 MaxJsonLength

  1. //获取 Excel 数据
  2. IList<IList<object>> listData = GetExcelData(worksheet);
  3. //构造返回到前端的数据
  4. var result = new
  5. {
  6. ColNames = listData[0],
  7. ColModel = listData[1],
  8. rows = listData[2],
  9. fileName = fileName
  10. };
  11. //modify by 20191209 - return Json 默认值为102400(100k),获取截止当前期间会报错-Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.这里使用 string
  12. var serializer = new JavaScriptSerializer();
  13. serializer.MaxJsonLength = int.MaxValue;
  14. string json = serializer.Serialize(result);
  15. return json;
  16. //return Json(result, JsonRequestBehavior.AllowGet);

前端-字符转 Json-JSON.parse

由于返回的是字符串,因此需要把字符转为 Json

  1. function (data) {
  2. data = JSON.parse(data);
  3. $("#fileName").val(data.fileName);
  4. $("#tbTaxCollectionList").GridUnload();
  5. var opts = global_Options.jqGridOptions();
  6. }