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

Time:12-28

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();
}

CodePudding user response:

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!");
}

CodePudding user response:

Check if productSizes is a JsonArray and iterate it:

if (productSizes is JsonArray jArr)
{
    foreach (var node in jArr)
    {
        // ...
    }
}

Read more:

  1. Type-testing operators and cast expressions
  2. JSON DOM choices
  • Related