本文介绍了反序列化在C#中嵌套的JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON数组与嵌套的对象,再presenting菜单,就象这样:

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

和我想用的JavaScriptSerializer反序列化它。我有一些code如下图所示,但不工作。

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

我得到的错误是类型菜单,不支持反序列化矩阵。
我想AP preciate如何申报自定义对象的任何帮助。

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.

干杯。

推荐答案

您根对象是一个2D的对象。属性孩子也2D交错数组。因此,你的菜单类必须是:

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

和反序列化JSON如下:

And deserialize your JSON as follows:

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

另外,如果你preFER名单数组,这样做:

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

然后

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

这篇关于反序列化在C#中嵌套的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:36