简体   繁体   中英

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.

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

问题可能是实际数据是一个数组,但是您告诉它只期望一个菜单吗?

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