使用JSON JavaScriptSerializer序列化或反序列化时出错
本文关键字:反序列化 出错 序列化 JSON JavaScriptSerializer 使用 | 更新日期: 2023-09-27 18:16:55
当尝试创建json时,我一直得到这个错误。这是完整的错误
Error during serialization or deserialization using the JSON
JavaScriptSerializer. The length of the string exceeds
the value set on the maxJsonLength property.
我的代码如下
public ActionResult ChangeRequests_Read([DataSourceRequest] DataSourceRequest request)
{
var data = GetRequests();
var serializer = new JavaScriptSerializer();
var result = new ContentResult();
serializer.MaxJsonLength = Int32.MaxValue; // Whatever max length you want here
result.Content = serializer.Serialize(data.ToDataSourceResult(request));
result.ContentType = "application/json";
return result;
//return Json(GetRequests().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
这个从这里拉过来
public static IEnumerable<ChangeRequestsVM> GetRequests()
{
var model = CompanyContextFactory.GetContextPerRequest();
var chrwVM = model.ChangeRequestsHDRs.Where(ch=> ch.CompanyID == GlobalVariables.CompanyID).Select(ch=> new ChangeRequestsVM
{
RequestID = ch.RequestID,
CompanyID = ch.CompanyID,
ClientID = ch.ClientID,
EmployeeID = (string.IsNullOrEmpty(ch.EmployeeID)) ? "NA" : ch.EmployeeID,
AssignmentType = ch.AssignmentType,
Key1 = ch.Key1,
Key2 = ch.Key2,
LogonID = ch.LogonID,
ProcessDate = ch.ProcessDate,
ProcessTime = ch.ProcessTime,
ProcessUserID = ch.ProcessUserID,
RequestDate = ch.RequestDate,
RequestExport = ch.RequestExport,
RequestNote = ch.RequestNote,
RequestOrigin = Convert.ToChar(ch.RequestOrigin),
RequestProcess = ch.RequestProcess,
RequestStatus = ch.RequestStatus,
RequestTime = ch.RequestTime,
RequestType = Convert.ToChar(ch.RequestType),
ResponseNote = ch.ResponseNote,
TableName = ch.TableName,
TransferDate = ch.TransferDate,
TransferTime = ch.TransferTime,
TransferUserID = ch.TransferUserID,
dispOrigin = (Convert.ToChar(ch.RequestOrigin) == ChangeRequestOrigin.System) ? "System" : (Convert.ToChar(ch.RequestOrigin) == ChangeRequestOrigin.Client) ? "Client" : "Employee",
dispRequestType = (Convert.ToChar(ch.RequestType) == ChangeRequestType.Insert) ? "Insert" : (Convert.ToChar(ch.RequestType) == ChangeRequestType.Alter) ? "Change" : "Delete",
dispStatus = FieldTranslation.GetEnumDescription(typeof(enChangeRequestStatus), ch.RequestStatus ?? 0)
}).OrderByDescending(ch=> ch.RequestID);
return chrwVM;
}
为什么我的json超过长度?我已经这样做了,所以方法只从数据库中提取一个项目,仍然得到错误。
你需要增加MaxJsonLength属性的大小:
https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.maxjsonlength.aspx这在配置文件中完成。详情请看上面的链接。
更新:
既然你正在使用MVC,你可以使用以下应用程序设置:
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="123456789" />
...
</appSettings>
但是,要注意这是一个潜在的安全风险。阅读更多:
https://msdn.microsoft.com/en-us/library/hh975440 (v = vs.120) . aspx