简体   繁体   English

将C#中的二维数组转换为javascript的Json字符串

[英]Converting a 2dimensional array in c# to Json string for javascript

So, I ran into an unexpected problem when debugging my javascript code and finally getting everything else to work. 因此,在调试javascript代码并最终使其他所有功能正常工作时,我遇到了意外问题。 the data I get from the controller has been flattened. 我从控制器获得的数据已被拉平。

[HttpPost]
    public JsonResult CalendarCellClasses(DateTime date)
    {
        DateTime firstOfMonth = date.AddDays(-(date.Day - 1));
        DateTime lastOfMonth = firstOfMonth.AddMonths(1).AddDays(-1);

        int additionalDaysBefore = firstOfMonth.DayOfWeek == DayOfWeek.Sunday ? 0 : (int)firstOfMonth.DayOfWeek - 1;
        int additionalDaysAfter = lastOfMonth.DayOfWeek == DayOfWeek.Sunday ? 0 : 7 - (int)lastOfMonth.DayOfWeek;
        int daysInMonth = lastOfMonth.Day;
        int totalDays = additionalDaysBefore + additionalDaysAfter + daysInMonth;
        int numWeeks = totalDays/7;

        DateTime firstDayInSeries = firstOfMonth.AddDays(-additionalDaysBefore);
        DateTime lastDayInSeries = lastOfMonth.AddDays(additionalDaysAfter);

        DateTime current = firstDayInSeries;

        string[,] dates = new string[numWeeks,7];

        for (int week = 0; week < numWeeks; week++)
        {
            for (int day = 0; day < 7; day++)
            {
                dates[week, day] = TrafficData.GetTrafficDate(current).CSSClass;
                current = current.AddDays(1);
            }
        }

        return Json(dates);
    }

as you see I have a string[,] which I want to pass down to the javascript function that calls this method. 如您所见,我有一个字符串[,],我想将其传递给调用此方法的javascript函数。

jQuery(document).ready(function() {
    var calendar = $('#Trafikkalender');
    var date = $('#selectedDate').val();
    var param = { date: date }
    var url = $('#calArrayPostUrl').data('url');
    $.post(url, param, function(data) {
        var body = calendar.find('tbody');

        //var rows = body.getElementsByTagName('tr');
        var rows = body.find('tr');

        for (var i = 0; i < rows.length; i++) {
            //var cols = rows[i].getElementsByTagName('td');
            var cols = $(rows[i]).find('td');
            for (var j = 0; j < cols.length; j++) {
                var col = $(cols[j]);
                col.addClass(data[i][j]);
            }
        }
    });
});

but according to the debugger data is an array with 35 elements, and they seem to be ordered as a single dimension array. 但是根据调试器的数据,它是一个包含35个元素的数组,它们似乎是按一维数组排序的。 did I do something wrong when I return the Json string or is 2dim arrays just not a thing in javascript? 返回Json字符串时我做错什么了吗?还是2dim数组在javascript中不是问题?

json is more or less a Text-File. json或多或少是一个文本文件。 I think, you could just Compile your array to a json. 我认为,您可以将数组编译为json。

just add the lines at the start, then do 只需在开始处添加行,然后执行

while allarrayentries
{
 enter new line into json;
}

and then add the last lines, to complete the json. 然后添加最后几行,以完成json。

Use a Class Model instead an array to pass data. 使用类模型代替数组来传递数据。

public class Dates{
   public DateTime current { get; set; }
   public int number { get; set; }
}

And in Javascript you can access it like this: 在Javascript中,您可以像这样访问它:

for (var i = 0; i < rows.length; i++) {
    var cols = $(rows[i]).find('td');
    for (var j = 0; j < cols.length; j++) {
        var col = $(cols[j]);
        col.addClass(data[i]["current"]);
        col.addClass(data[i]["number"]);
    }
}

Use JSON.NET for serializing instead of the built in serializer. 使用JSON.NET而不是内置的序列化程序进行序列化。 It seems the built in one serializes these arrays badly(and JSON.NET is also much faster). 似乎内置的数组对这些数组的序列化很差(并且JSON.NET也更快)。

Here is a basic implementation for this: 这是一个基本的实现:

public class JsonNetResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");
        if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            throw new InvalidOperationException("JSON GET is not allowed");

        HttpResponseBase response = context.HttpContext.Response;
        response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

        if (this.ContentEncoding != null)
            response.ContentEncoding = this.ContentEncoding;
        if (this.Data == null)
            return;

        if (Data != null)
        {
            var writer = new JsonTextWriter(response.Output);

            var serializer = JsonSerializer.Create(new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                DateFormatHandling = DateFormatHandling.IsoDateFormat
            });

            serializer.Serialize(writer, Data);

            writer.Flush();
        }
    }
}

And override the controllers's Json functions: 并重写控制器的Json函数:

    protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
    {

        return new JsonNetResult
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding,
            JsonRequestBehavior = behavior
        };
    }

    protected override JsonResult Json(object data, string contentType, Encoding contentEncoding)
    {
        return new JsonNetResult
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding
        };
    }

Read more: http://www.newtonsoft.com/json 了解更多: http : //www.newtonsoft.com/json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM