Question

I want to return a 2d-matrix from an MVC controller as json using return Json(myObject). At the moment I do it this way: return Json(myObject.ToJaggedArray()).

ToJaggedArray method looks like this:

public Field[][] ToJaggedArray()
{
    var jaggedArray = new Field[Rows][];

    for (int i = 0; i < Rows; ++i)
    {
        jaggedArray[i] = new Field[Columns];

        for (int j = 0; j < Columns; j++)
        {
            jaggedArray[i][j] = this[i, j];
        }
    }

    return jaggedArray;
}

I make js call this way:

var data = {};

$.getJSON("/Game/GetBoard", function (json) {
    data = json;
});

It all works well except for the fact, that I would like to avoid calling ToJaggedArray() on myObject. Is there anything that I can implement (interface or something) to make it work out of the box? It is important to retrieve two-dimensional array, so implementing IEnumerable is not an option...

Was it helpful?

Solution

implementing IEnumerable is not an option

Judging from the description you've given, sure it is - although I'm not quite sure what you're trying to do. But if it's just getting rid of the ToJaggedArray() call:

public class YourClass : IEnumerable
{
    // ...

    public IEnumerator GetEnumerator()
    {
        for (int i = 0; i < Rows; i++)
        {
            Field[] result = new Field[Columns];
            for (int j = 0; j < Columns; j++)
            {
                result[j] = this[i, j];
            }
            yield return result;
        }
    }
}

An example of output (using int[3,3] instead of Field[,]):

[[2,4,6],[1,2,3],[3,7,9]]

Each iteration over the IEnumerable simply yields the current row as a 1-dimensional array, Field[] (or in the example, int[]).

Update: Another option

More work required, but you could also implement your own JsonResult that adds a custom converter to the serializer using JavascriptSerializer.RegisterConverters, but that seems a bit over the top just to get rid of a direct method call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top