Search code examples
c#asp.netjsonjson-deserializationjavascriptserializer

Deserialize nested JSON array in C#


I have a JSON array with nested objects, representing a menu, as this:

[
    [
      {
       "name": "Item 1",
       "id": 1
      },
      {
       "name": "Item 2",
       "id": 2,
       "children": [
        [
         {
          "name": "Item 21",
          "id": 21
         }
        ]
       ]
      },
      {
       "name": "Item 3",
       "id": 3,
       "children": [
        [
         {
          "name": "Item 31",
          "id": 31,
          "children": [
           [
            {
             "name": "Item 311",
             "id": 311
            },
            {
             "name": "Item 312",
             "id": 312
            }
           ]
          ]
         },
         {
          "name": "Item 32",
          "id": 32
         },
...

And I want to deserialize it using JavaScriptSerializer. I have some code as shown below but is not working.

var serializer = new JavaScriptSerializer();
var objects = serializer.Deserialize<Menu>(jsonData); 
...


public class Menu
    {
        public int id { get; set; }
        public string name { get; set; }
        public Menu[] children { get; set; }
    }

The error I get is "The type 'Menu' is not supported to deserialize a matrix". I would appreciate any help on how to declare the custom object.

Cheers.


Solution

  • Your root object is a 2d jagged array of objects. The properties "children" are also 2d jagged arrays. Thus your Menu class needs to be:

    public class Menu
    {
        public int id { get; set; }
        public string name { get; set; }
        public Menu [][] children { get; set; }
    }
    

    And deserialize your JSON as follows:

    var serializer = new JavaScriptSerializer();
    var objects = serializer.Deserialize<Menu [][]>(jsonData);
    

    Alternatively, if you prefer lists to arrays, do:

    public class Menu
    {
        public int id { get; set; }
        public string name { get; set; }
        public List<List<Menu>> children { get; set; }
    }
    

    And then

    var objects = serializer.Deserialize<List<List<Menu>>>(jsonData);