Home > front end >  How do I enumerate through a JsonElement Array and then convert it to a List?
How do I enumerate through a JsonElement Array and then convert it to a List?

Time:12-22

Note that JsonElement is nullable (for a reason elsewhere in my project):

JsonElement? json = JsonSerializer.Deserialize<JsonElement?>(jsonData);
List<JsonElement?> itemsArray = json?.EnumerateArray().ToList();

The error in this code says:

Cannot convert from List to List<JsonElement?>

CodePudding user response:

Working with .Select() from System.Linq to casting each element to Nullable<JsonElement> type.

using System.Linq;

List<JsonElement?> itemsArray = json?.EnumerateArray()
    .Select(x => x as Nullable<JsonElement>)
    .ToList();

Or with .Cast<T>().

List<JsonElement?> itemsArray = json?.EnumerateArray()
    .Cast<JsonElement?>()
    .ToList();
  • Related