Suppose you have json text which changes it’s name each time ? but depth level remains same, What would you do ?

Here is one way you can solve it 😁.

Since json can have name and Several children so we can create Tree like node

1
2
3
4
5
public class JsonNode
{
    public string Name {get;set;}
    public List<JsonNode> Child {get;set;} = [];
}

Below code generate tree using Recursion

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.Collections.Generic;
using System.Text.Json;

public static JsonNode BuildTree(JsonElement element, string nodeName)
{
    var node = new JsonNode { Name = nodeName };

    if (element.ValueKind == JsonValueKind.Object)
    {
        foreach (var property in element.EnumerateObject())
        {
            node.Child.Add(BuildTree(property.Value, property.Name));
        }
    }
    else if (element.ValueKind == JsonValueKind.Array)
    {
        int index = 0;
        foreach (var item in element.EnumerateArray())
        {
            node.Child.Add(BuildTree(item, $"[{index}]") );
            index++;
        }
    }
    else
    {
        node.Child.Add(new JsonNode { Name = element.ToString() });
    }

    return node;
}

Here we we have sample code to initialize/ use the above code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
string jsonString = @"
        {
            ""12345"": {
                ""name"": ""Test Business"",
                ""policies"": {
                    ""checkin"": ""12:00 PM"",
                    ""checkout"": ""10:00 AM"",
                    ""cancellation"": {
                        ""before"": ""24 hours"",
                        ""fee"": ""10%""
                    }
                }
            }
        }";
JsonDocument doc = JsonDocument.Parse(jsonString);
JsonElement rootElement = doc.RootElement;
JsonNode rootNode = BuildTree(rootElement, "Root"); 

var parent = rootNode.Child[0];

Example

Image