Tapan kumar
Tapan kumar

Reputation: 6999

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. Any help will be appreciated.

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

Upvotes: 1

Views: 2593

Answers (1)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131374

First of all, that Json string is invalid. 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

Upvotes: 3

Related Questions