Andy Andy - 1 month ago 10
C# Question

How can I loop through child nodes using Json.NET?

I'm trying to loop through some JSON data and print it to the screen. Here's what the JSON looks like:

JSON data

Using this code, I'm able to loop through the list of category names without any issues:

dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

foreach (var obj in jsonObj.categories)
{
<p> <strong> @obj.name </strong> </p>
}


I can't figure out how to loop through subcategories though. I tried this, but I just get Error - Object reference not set to an instance of an object.

foreach (var obj in jsonObj.categories)
{
<p> <strong> @obj.name </strong> </p>

foreach (var subcat in jsonObj.subcategories)
{
<p> <strong> @obj.name </strong> </p>
}
}

Answer

You are trying to get the subcategories from the parent object instead of the child one:

foreach (var category in jsonObj.categories)
{
    <p> <strong> @category.name </strong> </p>

    foreach (var subcategory in category.subcategories) // <= here is the key.
    {
         <p> <strong> @subcategory.name </strong> </p>
    }
}