使用Newtonsoft dll将嵌套(n级)json反序列化为C#对象

时间:2017-07-17 12:15:32

标签: c# json json.net

我正在使用一个API,它给了我一个多级JSON,我想把它转换成C#对象。任何帮助将不胜感激。

JSON

{
  "Categories": [
    {
      "Code": "2984",
      "Name": "Baby",
      "Children": [
        {
          "Code": "100978",
          "Name": "Christening & Gifts",
          "Children": [
            {
              "Code": "100980",
              "Name": "Baby Jewellery"
            },
            {
              "Code": "100981",
              "Name": "Ornaments"
            },
            {
              "Code": "121628",
              "Name": "Gift Baskets"
            },
            {
              "Code": "139760",
              "Name": "Christening",
              "Children": [
                {
                  "Code": "100979",
                  "Name": "Gifts"
                },
                {
                  "Code": "139764",
                  "Name": "Silverware"
                },
                {
                  "Code": "139765",
                  "Name": "Other Christening"
                }
              ]
            },
            {
              "Code": "32871",
              "Name": "Other Gifts"
            }
          ]
        },
        {
          "Code": "100982",
          "Name": "Baby Carriers/Backpacks"
        },
        {
          "Code": "1261",
          "Name": "Other Baby"
        },
        {
          "Code": "134282",
          "Name": "Walkers"
        }
    }]
}

1 个答案:

答案 0 :(得分:3)

首先,Json字符串无效。它缺少第一类儿童的阵列终止字符。字符串应该像这样结束:

        }]
    }]
}

修正此错字后,您可以使用符合字符串结构的任何类,例如:

class MyRoot
{
    public Node[] Categories {get;set;}
}

class Node
{
    public string Code{get;set;}
    public string Name {get;set;}
    public Node[] Children{get;set;}
}

var myRoot=JsonConvert.DeserializeObject<MyRoot>(someString);
Console.WriteLine(myroot.Categories[0].Children[3].Name);

------
Walkers