0

我有一个问题,我从服务器接收大量数据,然后将其转换为 Json 格式,然后在 JqGrid 中查看。它适用于少量数据,例如 200 行,但是当对 10000 行执行此操作时,它会引发以下错误

System.InvalidOperationException:使用 JSON JavaScriptSerializer 进行序列化或反序列化期间出错。字符串长度超过 maxJsonLength 属性设置的值

我尝试使用 javascript 序列化程序并将其设置为 maxjsonLenght = int32.MaxValue 但仍然没有运气

以下是我的代码,请给我一些建议,例如如何解决这个问题?谢谢大家!

网格配置

 public JqGridConfig(String db, String jobGroup, String jobName, String detailTable,       String filterBatchControl, String filterDate, String filterTime, int page)
    {
        var entityhelper = new EntityHelper();
        var s = new JsonSerializer();

        try
        {
            //Populate Grid Model, Column Names, Grid Column Model, Grid Data
            entityhelper.PopulateDetailGridInit(db, jobGroup, jobName, detailTable, filterBatchControl, filterDate, filterTime);

            JqGridDetailAttributes = entityhelper.GridDetailAttributes;
            JqGridDetailColumnNames = entityhelper.GridDetailColumnNames;
            //JqGridDetailsColumnNamesForExport = entityhelper.GridDetailColumnNamesForExport;
            JqGridDetailColumnModel = entityhelper.GridDetailColumnModel;

            //Dynamic Data
            JqGridDynamicDetailData = entityhelper.GridDetailData;


            #region Column Model
            foreach (KeyValuePair<String, JqGridColModel> kvp in entityhelper.GridDetailColumnModel)
            {
                s.Serialize(kvp.Key, kvp.Value.Attributes);
            }

            JqGridDetailColumnModelJson = s.Json();
            #endregion

            #region Concrete data.  1. List<dynamic> populated, 2. Convert to Json String, 3: Convert back to List<Detail>
            JqGridDetailData = JsonSerializer.ConvertDynamicDetailsToJson(JqGridDynamicDetailData); // this is where the error occurs

            }
        catch (Exception ex)
        {
            //TODO: Logging
            System.Diagnostics.Debug.WriteLine(ex.Message);
        }
    }

Json 序列化器

  public static IList<Detail> ConvertDynamicDetailsToJson(IList<dynamic> list)
    {
        if (list.Count == 0)
            return new List<Detail>();

        var sb = new StringBuilder();
        var contents = new List<String>();

        sb.Append("[");

        foreach (var item in list)
        {
            var d = item as IDictionary<String, Object>;

            sb.Append("{");
            foreach (KeyValuePair<String, Object> kvp in d)
            {    
                contents.Add(String.Format("{0}: {1}", "\"" + kvp.Key + "\"", JsonConvert.SerializeObject(kvp.Value))); 
            }
            sb.Append(String.Join(",", contents.ToArray()));
            sb.Append("},");
        }

        sb.Append("]");

        //remove trailing comma
        sb.Remove(sb.Length - 2, 1);
        var jarray = JsonConvert.DeserializeObject<List<Detail>>(sb.ToString());

        return jarray;
    }

从服务器返回 Json 结果的控制器

  public JsonResult DetailGridData(TheParams param)
    {






        dynamic config= "";
        switch (param.JobGroup)
        {
            case "a":
                config = new BLL.abcBLL().GetDetailGridData("rid", "desc", 1, 20, null,
                                                                             param.FilterBatchControl,
                                                                             param.JobName, param.DetailTable,
                                                                             param.JobGroup, param.BatchDate,
                                                                             param.Source);
                break;
        }




        return Json(config, JsonRequestBehavior.AllowGet);  // this reurns successfully json result
    }

查看 Jqgrid 存在且不填充网格的位置

 <script type="text/javascript">

var jobGroup = '@ViewBag.JobGroup';
var jobName  = '@ViewBag.JobName';
var detailTable = '@ViewBag.DetailTable';
var filterBatchControl = '@ViewBag.FilterBatchControl';
var controlDate = '@ViewBag.ControlDate';
var controlTime = '@ViewBag.ControlTime';
var source = '@ViewBag.DetailSource';
var page = '@ViewBag.page';



function loadDetailData() {
    var param = new Object();
    param.BatchDate = controlDate;
    param.BatchTime = controlTime;
    param.JobGroup = jobGroup;
    param.JobName = jobName;
    param.DetailTable = detailTable;
    param.FilterBatchControl = filterBatchControl;
    param.Source = source;
    param.page = page;

    window.parent.loadingDetailsHeader();        

    $.ajax({
        url: "/control/detailgriddata",
        dataType: 'json',
        type: 'POST',
        data: param,
        async: false,
        success: function (response) {
            try {
                jgGridDetailColumnNames = response.JqGridDetailColumnNames;
                //jqGridDetailColumnData = response.JqGridDetailData;
                jqGridDetailColumnData = response.config;
                $('#detailGrid').jqGrid('setGridParam', {colNames: jgGridDetailColumnNames});
                $('#detailGrid').jqGrid('setGridParam', {data: jqGridDetailColumnData}).trigger('reloadGrid');
                parent.loadingDetailsHeaderComplete();
            }
            catch(e) {
                window.parent.loadingDetailsHeaderException(e.Message);
            }
            return false;
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
}

function exportdetails(date) {
    var param = new Object();
    param.db = source;
    param.jobGroup = jobGroup;
    param.jobName = jobName;
    param.detailTable = detailTable;
    param.filterBatchControl = filterBatchControl;          
    param.filterDate = date;
    param.filterTime = "NULL";

    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: '@Url.Action("ExportDetailsCsv", "Control")',
        dataType: 'json',
        data: $.toJSON(param),
        async: false,
        success: function (response) {
            window.location.assign(response.fileName);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("Details Export Exception: " + xhr.status);
        }
    });
}

//<![CDATA[
$(document).ready(function () {
    'use strict';

    $(window).resize(function () {
        $("#detailGrid").setGridWidth($(window).width());
    }).trigger('resize');

    var dgrid = $("#detailGrid");

    $('#detailGrid').jqGrid('clearGridData');
    loadDetailData();

    dgrid.jqGrid({
        datatype: 'json',
        data: jqGridDetailColumnData,
        colNames: jgGridDetailColumnNames,
        colModel: [ @Html.Raw(@ViewBag.ColModelDetail) ],
        rowNum: 25,
        rowList: [25, 50, 100],
        pager: '#detailPager',
        gridview: true,
        autoencode: false,
        ignoreCase: true,
        viewrecords: true,
        altrows: false,
        autowidth: true,
        shrinkToFit: true,
        headertitles: true,
        hoverrows: true,
        height: 300,
        onSelectRow: function (rowId) {
            //This is a demo dialog with a jqGrid embedded
            //use this as the base for viewing detail data of details
            //$('#dialogGrid').dialog();
            //gridDialog();
        },
        loadComplete: function (data) {},
        gridComplete: function (data) {
            //if (parseInt(data.records,10) < 50) {
            $('#detailPager').show();
            //} else {
            //$('#detailPager').show();
            //}
        }
    }).jqGrid('navGrid', '#detailPager', { edit: false, add: false, del: false, search: false }, {});
});
 //]]>
 </script>
 <table id="detailGrid">
<tr>
    <td />
</tr>
</table>

 <div id="detailPager"></div>

 <div id="dialogGrid"></div>
4

1 回答 1

0

也许您应该考虑使用服务器端分页而不是向客户端返回 10000 行?SQL 数据的服务器端分页可以更有效地实现为客户端分页(在 JavaScript 程序中对大型非索引数据进行排序)。

您还有一个选择是使用另一个JSON 序列化程序。例如,它可以是protobuf-netServiceStack.Text(也请参见此处)、Json.NET等。与JavaScriptSerializer.

于 2013-01-09T17:41:13.113 回答