Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I enumerate through a JsonElement Array and then convert it to a List?

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<JsonElement> to List<JsonElement?>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading