0

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?

dbc
  • 104,963
  • 20
  • 228
  • 340
Szyszka947
  • 473
  • 2
  • 5
  • 21
  • 1
    What are you really trying to do? In most cases you would deserialize json to an object. There are even tools available to generate c# classes from a json file. Traversing the tree by hand should be rare, and mostly done to handle special cases. – JonasH Feb 28 '23 at 15:47
  • 1
    *"because JsonNode is only value and there is no something like JsonProperty [...] but it has key-value format for properties instead of simple JSON"* - It's not clear to me what you're trying to describe. Can you provide a [mcve] which includes input data and indicate specifically what you're trying to do and specifically what isn't working as expected? – David Feb 28 '23 at 15:47
  • I recommend you to forget that Text.Json even exists, till you learn how to use all the features of Newtonsoft.Json. Text.Json needs custom converters for every even quite simple json and it doesn't make any sense to use it for the tasks like this. – Serge Feb 28 '23 at 15:58
  • System.Text.Json has no equivalent to `JProperty` so your `Descendants()` method won't find them. Instead, you could use `public static IEnumerable<(JsonNode? node, int? index, string? name, JsonNode? parent)> DescendantItemsAndSelf(this JsonNode? root, bool includeSelf = true)` from [this answer](https://stackoverflow.com/a/73887518/3744182) to [How to recursively descend a System.Text.Json JsonNode hierarchy (equivalent to Json.NET's JToken.DescendantsAndSelf())?`](https://stackoverflow.com/q/73887517/3744182). In fact this looks like a duplicate. – dbc Feb 28 '23 at 16:08

0 Answers0