我正在使用jQuery的自动完成功能。当我试图检索超过17000条记录的列表(每个记录不会超过10个字符长度)时,它超过了长度并抛出错误:
异常信息: 异常类型:InvalidOperationException 异常消息:使用JSON JavaScriptSerializer进行序列化或反序列化时出错。字符串的长度超过maxJsonLength属性设置的值。
我可以在web.config中设置maxJsonLength的无限长度吗?如果不是,我可以设置的最大长度是多少?
我正在使用jQuery的自动完成功能。当我试图检索超过17000条记录的列表(每个记录不会超过10个字符长度)时,它超过了长度并抛出错误:
异常信息: 异常类型:InvalidOperationException 异常消息:使用JSON JavaScriptSerializer进行序列化或反序列化时出错。字符串的长度超过maxJsonLength属性设置的值。
我可以在web.config中设置maxJsonLength的无限长度吗?如果不是,我可以设置的最大长度是多少?
当前回答
我遵循了vestial的答案,得到了这个解决方案:
当我需要将一个大的json发送到控制器中的一个动作时,我会得到著名的“使用json JavaScriptSerializer进行反序列化期间错误”。字符串的长度超过maxJsonLength属性设置的值。\r\n参数名称:输入值提供程序”。
我所做的是创建一个新的ValueProviderFactory, LargeJsonValueProviderFactory,并设置MaxJsonLength = Int32。GetDeserializedObject方法中的MaxValue
public sealed class LargeJsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(LargeJsonValueProviderFactory.EntryLimitedDictionary backingStore, string prefix, object value)
{
IDictionary<string, object> dictionary = value as IDictionary<string, object>;
if (dictionary != null)
{
foreach (KeyValuePair<string, object> keyValuePair in (IEnumerable<KeyValuePair<string, object>>) dictionary)
LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value);
}
else
{
IList list = value as IList;
if (list != null)
{
for (int index = 0; index < list.Count; ++index)
LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakeArrayKey(prefix, index), list[index]);
}
else
backingStore.Add(prefix, value);
}
}
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
return (object) null;
string end = new StreamReader(controllerContext.HttpContext.Request.InputStream).ReadToEnd();
if (string.IsNullOrEmpty(end))
return (object) null;
var serializer = new JavaScriptSerializer {MaxJsonLength = Int32.MaxValue};
return serializer.DeserializeObject(end);
}
/// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
/// <returns>A JSON value-provider object for the specified controller context.</returns>
/// <param name="controllerContext">The controller context.</param>
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
object deserializedObject = LargeJsonValueProviderFactory.GetDeserializedObject(controllerContext);
if (deserializedObject == null)
return (IValueProvider) null;
Dictionary<string, object> dictionary = new Dictionary<string, object>((IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase);
LargeJsonValueProviderFactory.AddToBackingStore(new LargeJsonValueProviderFactory.EntryLimitedDictionary((IDictionary<string, object>) dictionary), string.Empty, deserializedObject);
return (IValueProvider) new DictionaryValueProvider<object>((IDictionary<string, object>) dictionary, CultureInfo.CurrentCulture);
}
private static string MakeArrayKey(string prefix, int index)
{
return prefix + "[" + index.ToString((IFormatProvider) CultureInfo.InvariantCulture) + "]";
}
private static string MakePropertyKey(string prefix, string propertyName)
{
if (!string.IsNullOrEmpty(prefix))
return prefix + "." + propertyName;
return propertyName;
}
private class EntryLimitedDictionary
{
private static int _maximumDepth = LargeJsonValueProviderFactory.EntryLimitedDictionary.GetMaximumDepth();
private readonly IDictionary<string, object> _innerDictionary;
private int _itemCount;
public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
{
this._innerDictionary = innerDictionary;
}
public void Add(string key, object value)
{
if (++this._itemCount > LargeJsonValueProviderFactory.EntryLimitedDictionary._maximumDepth)
throw new InvalidOperationException("JsonValueProviderFactory_RequestTooLarge");
this._innerDictionary.Add(key, value);
}
private static int GetMaximumDepth()
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
if (appSettings != null)
{
string[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
int result;
if (values != null && values.Length > 0 && int.TryParse(values[0], out result))
return result;
}
return 1000;
}
}
}
然后,在Global.asax.cs中的Application_Start方法中,用新的ValueProviderFactory替换ValueProviderFactory:
protected void Application_Start()
{
...
//Add LargeJsonValueProviderFactory
ValueProviderFactory jsonFactory = null;
foreach (var factory in ValueProviderFactories.Factories)
{
if (factory.GetType().FullName == "System.Web.Mvc.JsonValueProviderFactory")
{
jsonFactory = factory;
break;
}
}
if (jsonFactory != null)
{
ValueProviderFactories.Factories.Remove(jsonFactory);
}
var largeJsonValueProviderFactory = new LargeJsonValueProviderFactory();
ValueProviderFactories.Factories.Add(largeJsonValueProviderFactory);
}
其他回答
修复ASP。NET MVC如果你想只修复导致问题的特定操作,请更改以下代码:
public JsonResult GetBigJson()
{
var someBigObject = GetBigObject();
return Json(someBigObject);
}
:
public JsonResult GetBigJson()
{
var someBigObject = GetBigObject();
return new JsonResult()
{
Data = someBigObject,
JsonRequestBehavior = JsonRequestBehavior.DenyGet,
MaxJsonLength = int.MaxValue
};
}
功能应该是一样的,你可以返回更大的JSON作为响应。
基于ASP的解释。NET MVC源代码:你可以检查什么控制器。Json方法在ASP。NET MVC源代码
protected internal JsonResult Json(object data)
{
return Json(data, null /* contentType */, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
}
它正在调用其他控制器。Json方法:
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}
其中传递的contentType和contentEncoding对象为空。所以基本上在控制器中调用return Json(object)相当于调用return new JsonResult {Data = object, JsonRequestBehavior = sonRequestBehavior。DenyGet}。您可以使用第二种形式并参数化JsonResult。
那么当你设置MaxJsonLength属性(默认为null)时会发生什么? 它传递给JavaScriptSerializer。MaxJsonLength属性,然后是JavaScriptSerializer。Serialize方法被调用:
JavaScriptSerializer serializer = new JavaScriptSerializer();
if (MaxJsonLength.HasValue)
{
serializer.MaxJsonLength = MaxJsonLength.Value;
}
if (RecursionLimit.HasValue)
{
serializer.RecursionLimit = RecursionLimit.Value;
}
response.Write(serializer.Serialize(Data));
当你不设置serializer的maxjsonlengt属性时,它会取默认值,也就是2MB。
我修好了。
//your Json data here
string json_object="........";
JavaScriptSerializer jsJson = new JavaScriptSerializer();
jsJson.MaxJsonLength = 2147483644;
MyClass obj = jsJson.Deserialize<MyClass>(json_object);
它工作得很好。
问题是你是否真的需要返回17k条记录?您打算如何处理浏览器中的所有数据?用户无论如何都不会滚动17000行。
更好的方法是只检索“前几条”记录,并根据需要加载更多记录。
JsonResult result = Json(r);
result.MaxJsonLength = Int32.MaxValue;
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result;
如果你在视图中遇到这类问题,你可以使用下面的方法来解决。这里我用的是牛顿软包装。
@using Newtonsoft.Json
<script type="text/javascript">
var partData = @Html.Raw(JsonConvert.SerializeObject(ViewBag.Part));
</script>