Problems serializing multidimentional arrays

Our WebMap product generates code that serializes objects using JSON.
In order to transform the objects to JSON we rely on Newtonsoft.Json which is an excellent library.

However at some point you might encounter an exception with a message like:

"Unable to cast object of type 'System.Object[]' to type 'System.Object[,]'."   System.Exception {System.InvalidCastException}

Don't panic. There is a simple explanation :)

Javascript doesn't have the notion of a 2D array in the same sense that C# does. In order to get a multidimensional array or jagged array, it has to be expressed as an array of arrays instead.

This problem has been fixed on Newtonsoft.Json from version 4.5.8 (see http://james.newtonking.com/archive/2012/08/06/json-net-4-5-release-8-multidimensional-array-support-unicode-improvements for more information)

However our current WebMap product output uses version 4.5.6 by default. Just update your version to 4.5.8

Fixing the issue

To update your reference go to Tools\Nuget Package Manager Console\Package Manager Console

And run a command like:

Update-Package Newtonsoft.Json -version 4.5.8

And for the curious mind, this is a small test to reproduce the issue:

Test Program


using System;

namespace Test1  
{
    public class Class1
    {
        public object[,] values;
    }

    class Program
    {
        static void Main(string[] args)
        {
            var class1 = new Class1();
            class1.values = new object[2, 2];
            class1.values[0,0] = "Have";
            class1.values[0,1] = "a";
            class1.values[1,0] = "Nice";
            class1.values[1, 1] = "Day";

            var result = Newtonsoft.Json.JsonConvert.SerializeObject(class1);
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}

Using version 4.5.6

{"values":["Have","a","Nice","Day"]}

Using version 4.5.8

You get this output

{"values":[["Have","a"],["Nice","Day"]]}