简体   繁体   中英

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. 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.

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. did I do something wrong when I return the Json string or is 2dim arrays just not a thing in javascript?

json is more or less a Text-File. I think, you could just Compile your array to a 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.

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:

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. It seems the built in one serializes these arrays badly(and JSON.NET is also much faster).

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:

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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