Search code examples
c#jsonforeachiteration

How do I iterate over a JsonObject with foreach in C#


I'm trying to foreach through a JsonObject, but unfortunately it gives me an error on the "in productSizes"

foreach statement cannot operate on variables of type 'JsonNode' because 'JsonNode' does not contain a public definition for 'GetEnumerator'

Any idea what I might be doing wrong?

var productSizes = siteJson["api"]["productDetails"]["getDetails"]["data"]["sizes"];

foreach (var size in productSizes)
{
    Console.WriteLine(size);
    Console.WriteLine();
}

Solution

  • As you found in your comment, JsonNode has a .AsArray() method which internally uses pattern matching to return a JsonArray. This isn't super safe, however, since it will throw an exception if productSizes isn't deserialized as a JsonArray.

    For better safety, you are probably better off either using a try-catch or implementing the pattern matching yourself, like in the following:

    if (productSizes is JsonArray jArray)
    {
        foreach (var size in jArray)
        {
          Console.WriteLine(size);
          Console.WriteLine();
        }
    } else {
        Console.WriteLine("Error: productSizes is not an array!");
    }