
JSON to tree in C#
Handling Dynamic JSON with Variable Property Names 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 ...