-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTreeViewJson.cs
121 lines (104 loc) · 3.66 KB
/
TreeViewJson.cs
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
using System;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace rtssh
{
public partial class TreeViewJson : Form
{
#region Constructor
public TreeViewJson(string path)
{
InitializeComponent();
try
{
using (var reader = new StreamReader(path))
using (var jsonReader = new JsonTextReader(reader))
{
var root = JToken.Load(jsonReader);
DisplayTreeView(root, Path.GetFileNameWithoutExtension(path));
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
#endregion
#region Events
private void jsonTreeView_DoubleClick(object sender, EventArgs e)
{
// Get temp's json path
if (jsonTreeView.SelectedNode.FirstNode != null ||
jsonTreeView.SelectedNode.ForeColor != Color.Green) return;
var jsonPath = JsonPathFormatter(jsonTreeView.SelectedNode.FullPath);
LaunchForm.MainForm.JsonPathTextBox = jsonPath;
Close();
}
#endregion
#region Methods
private static string JsonPathFormatter(string jsonPath)
{
// Remove characters before first comma and after last comma
jsonPath = jsonPath.Substring(jsonPath.IndexOf(',') + 1);
jsonPath = jsonPath.Substring(0, jsonPath.LastIndexOf(','));
return jsonPath;
}
private void DisplayTreeView(JToken root, string rootName)
{
jsonTreeView.BeginUpdate();
try
{
jsonTreeView.Nodes.Clear();
var tNode = jsonTreeView.Nodes[jsonTreeView.Nodes.Add(new TreeNode(rootName))];
tNode.Tag = root;
AddNode(root, tNode);
jsonTreeView.ExpandAll();
}
finally
{
jsonTreeView.EndUpdate();
}
}
private void AddNode(JToken token, TreeNode inTreeNode)
{
switch (token)
{
case null:
MessageBox.Show(@"Something went wrong upon constructing JSON");
Close();
return;
case JValue _:
{
var childNode = inTreeNode.Nodes[inTreeNode.Nodes.Add(new TreeNode(token.ToString()))];
childNode.Tag = token;
// Turn temp values to green
var errorCounter = Regex.Matches(childNode.Text,@"[a-zA-Z]").Count;
if (errorCounter <= 0)
{
childNode.ForeColor = Color.Green;
}
break;
}
case JObject jObject:
{
foreach (var property in jObject.Properties())
{
var childNode = inTreeNode.Nodes[inTreeNode.Nodes.Add(new TreeNode(property.Name))];
childNode.Tag = property;
AddNode(property.Value, childNode);
}
break;
}
default:
MessageBox.Show(@"Something went wrong upon constructing JSON");
Close();
return;
}
}
#endregion
}
}