I have written following method to get JSON descendants using System.Text.Json
:
public static IEnumerable<JsonNode> GetDescendants(this JsonNode jsonNode)
{
switch (jsonNode)
{
case JsonObject jsonObject:
foreach (var propertyValue in jsonObject.Where(p => p.Value is not null).Select(p => p.Value))
{
yield return propertyValue!;
foreach (var descendant in propertyValue!.GetDescendants()) yield return descendant;
}
break;
case JsonArray jsonArray:
foreach (var element in jsonArray.Where(p => p is not null))
{
yield return element!;
foreach (var descendant in element!.GetDescendants()) yield return descendant;
}
break;
default:
yield break;
}
}
Seems fine, but it omits one step. E.g for JSON array, it doesn't return first propertyName: array
, but array value. The same problem with objects. It's because JsonNode is only value and there is no something like JsonProperty.
Also tried with JsonElement
but it has key-value format for properties instead of simple JSON. Do you have any ideas how to get JSON descendants from JSON using System.Text.Json
?