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

本文关键字:javascript Json 字符串 二维数组 转换 | 更新日期: 2023-09-27 17:58:33

因此,我在调试javascript代码并最终使其他一切正常工作时遇到了一个意外问题。我从控制器得到的数据已经被压平了。

[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);
    }

如您所见,我有一个字符串[,],我想将其传递给调用此方法的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]);
            }
        }
    });
});

但根据调试器的数据,这是一个包含35个元素的数组,它们似乎是作为一维数组排列的。当我返回Json字符串时,我做错了什么吗?或者2dim数组在javascript中不是一个东西吗?

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

json或多或少是一个文本文件。我认为,您可以将数组编译为json。

只需在开头添加行,然后进行

while allarrayentries
{
 enter new line into json;
}

然后添加最后一行,以完成json。

使用类模型而不是数组来传递数据。

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

在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"]);
    }
}

使用JSON.NET进行序列化,而不是内置的序列化程序。似乎内置程序对这些数组的序列化很糟糕(而且JSON.NET也快得多)。

这里有一个基本的实现:

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();
        }
    }
}

并覆盖控制器的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
        };
    }

阅读更多:http://www.newtonsoft.com/json