26

我正在通过 jQuery 的ajaxpost 方法通过 web 方法加载选项卡内容数据,其中包含大约 200-300 条记录。并在控制台中出现以下错误:

错误:Sys.Net.WebServiceFailedException:Sys.Net.WebServiceFailedException:System.InvalidOperationException-- 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了 maxJsonLength 属性上设置的值。

像这样更改 Web.config 中属性的长度maxJsonLength并没有帮助。

<configuration> 
   <system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="2147483644" />
           </webServices>
       </scripting>
   </system.web.extensions>
</configuration>

谁能帮我解决这个问题?

4

3 回答 3

36

JavaScriptSerialzer has a public property named MaxJsonLength according to

http://msdn.microsoft.com/en-us/library/system.web.configuration.scriptingjsonserializationsection.maxjsonlength.aspx

Now, where you are deserializing your json, use this

JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue; //Or any size you want to use, basically int maxValue is 2GB, you shouldn't need this big json string to deserialize, else you are doing it wrong.
myObject obj = serializer.Deserialize<myObject>(yourJsonString);

And this should work perfectly, I recently figured this out through msdn and solved a problem that was bugging me for long.

于 2013-03-26T20:52:02.737 回答
6

我知道在我阅读时这是一个非常古老的线程,并且 WebMethod 在 ASP.NET MVC 中并不是真正的东西,所以这有点切题。但是,如果有人碰到它——

如果你使用 ASP.NET MVC 直接调用还有一个替代方法JavaScriptSerializer,那就是初始化JsonResult并设置MaxJsonLength结果本身的属性:

    private JsonResult GetReallyBigJsonResult(object data, JsonRequestBehavior requestBehavior)
    {
            return new JsonResult()
            {
                ContentEncoding = Encoding.Default,
                ContentType = "application/json",
                Data = data,
                JsonRequestBehavior = requestBehavior,
                MaxJsonLength = int.MaxValue
            };

    }
于 2016-06-23T18:39:49.777 回答
0

不知道您的字符串的大小,但也许它仍然超过您设置的最大限制?

理想情况下,ajax 场景仅适用于中小型服务器端调用,而不是获取大量数据,如果您使用异步请求获取大量数据,那么您就是在自找麻烦。

请参阅此处以获取替代方案

于 2012-08-09T10:37:35.557 回答