Skip to content

Commit 6fe87cf

Browse files
committed
Json To Tree Build
1 parent 49c5c5b commit 6fe87cf

File tree

3 files changed

+96
-0
lines changed

3 files changed

+96
-0
lines changed
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
---
2+
title: "Json to C sharp class"
3+
author: "PrashantUnity"
4+
weight: 110
5+
date: 2025-01-01
6+
lastmod: 2025-01-01
7+
dateString: January 2025
8+
description: "Just a hack for json parsing to JsonDocument to Tree"
9+
#canonicalURL: "https://canonical.url/to/page"
10+
cover:
11+
image: "cover.jpg" # image path/url
12+
alt: "Download Logo" # alt text
13+
#caption: "Optical Character Recognition" display caption under cover
14+
15+
tags: [ "NET", "codefrydev", "C sharp", "CFD","JSON"]
16+
keywords: [ "NET", "codefrydev", "C sharp", "CFD","JSON"]
17+
---
18+
19+
20+
# Suppose you have json text which changes it's name each time ? but depth level remains same, What would you do ?
21+
22+
## Here is one way you can solve it 😁.
23+
24+
> Since json can have name and Several children so we can create Tree like node
25+
26+
```cs
27+
public class JsonNode
28+
{
29+
public string Name {get;set;}
30+
public List<JsonNode> Child {get;set;} = [];
31+
}
32+
```
33+
34+
> Below code generate tree using Recursion
35+
36+
37+
```cs
38+
using System;
39+
using System.Collections.Generic;
40+
using System.Text.Json;
41+
42+
public static JsonNode BuildTree(JsonElement element, string nodeName)
43+
{
44+
var node = new JsonNode { Name = nodeName };
45+
46+
if (element.ValueKind == JsonValueKind.Object)
47+
{
48+
foreach (var property in element.EnumerateObject())
49+
{
50+
node.Child.Add(BuildTree(property.Value, property.Name));
51+
}
52+
}
53+
else if (element.ValueKind == JsonValueKind.Array)
54+
{
55+
int index = 0;
56+
foreach (var item in element.EnumerateArray())
57+
{
58+
node.Child.Add(BuildTree(item, $"[{index}]") );
59+
index++;
60+
}
61+
}
62+
else
63+
{
64+
node.Child.Add(new JsonNode { Name = element.ToString() });
65+
}
66+
67+
return node;
68+
}
69+
```
70+
71+
> Here we we have sample code to initialize/ use the above code
72+
```cs
73+
string jsonString = @"
74+
{
75+
""12345"": {
76+
""name"": ""Test Business"",
77+
""policies"": {
78+
""checkin"": ""12:00 PM"",
79+
""checkout"": ""10:00 AM"",
80+
""cancellation"": {
81+
""before"": ""24 hours"",
82+
""fee"": ""10%""
83+
}
84+
}
85+
}
86+
}";
87+
JsonDocument doc = JsonDocument.Parse(jsonString);
88+
JsonElement rootElement = doc.RootElement;
89+
JsonNode rootNode = BuildTree(rootElement, "Root");
90+
91+
var parent = rootNode.Child[0];
92+
```
93+
94+
> Example
95+
96+
![Image](./example.png)
6.52 KB
Loading
92.2 KB
Loading

0 commit comments

Comments
 (0)