简体   繁体   English

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

[英]Deserialize nested(n-level) json to C# objects using Newtonsoft dll

I am consuming an API that gives me a multi level JSON, I want to convert it into C# object. 我正在使用一个API,它给了我一个多级JSON,我想将它转换为C#对象。 Any help will be appreciated. 任何帮助将不胜感激。

JSON 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"
        }
    }]
}

First of all, that Json string is invalid. 首先,Json字符串无效。 It's missing the array termination character for the first category's Children. 它缺少第一类儿童的阵列终止字符。 The string should end like this: 字符串应该像这样结束:

        }]
    }]
}

After fixing this typo, you can use any classes that match the string's structure, eg: 修复此错误后,您可以使用与字符串结构匹配的任何类,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM