-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSONKeySearch.cs
113 lines (104 loc) · 3.35 KB
/
JSONKeySearch.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
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JSONSearch
{
public static class JsonExtensions
{
public static List<JToken> FindTokens(this JToken containerToken, string name)
{
List<JToken> matches = new List<JToken>();
FindTokens(containerToken, name, matches);
return matches;
}
private static void FindTokens(JToken containerToken, string name, List<JToken> matches)
{
if (containerToken.Type == JTokenType.Object)
{
foreach (JProperty child in containerToken.Children<JProperty>())
{
if (child.Name == name)
{
matches.Add(child.Value);
}
FindTokens(child.Value, name, matches);
}
}
else if (containerToken.Type == JTokenType.Array)
{
foreach (JToken child in containerToken.Children())
{
FindTokens(child, name, matches);
}
}
}
}
class JSONKeySearch
{
static void Main(string[] args)
{
string json = @"{
""contact"": {
""name"": ""Vyshag"",
""title"": ""SE"",
""OtherDetails"": {
""Personal"": {
""ShortName"": ""Vys"",
""Hobby"": ""Reading""
},
""Professional"": {
""ID"": ""1234"",
""Experience"": ""4 years""
}
}
}
}";
JObject jo = JObject.Parse(json);
//Give search value here
string KeyToSearch = "contact";
foreach (JToken token in jo.FindTokens(KeyToSearch))
{
if (token.Children().Count() > 0)
{
PrintValuesFromJsonObject(((JObject)(token)));
}
else
{
PrintValueFromString(((JProperty)(token.Parent)));
}
}
Console.Read();
}
private static void PrintValuesFromJsonObject(JObject inner)
{
if (inner.Children().Count() > 0)
{
List<string> keys = inner.Properties().Select(p => p.Name).ToList();
foreach (string key in keys)
{
if (inner[key].Children().Count() > 0)
{
PrintValuesFromJsonObject((JObject)inner[key]);
}
else
{
PrintValueFromString(((JProperty)(inner[key].Parent)));
}
}
}
else
{
PrintValueFromString(((JProperty)(inner.Parent)));
}
}
private static void PrintValueFromString(JProperty JsonProperty)
{
string Key = JsonProperty.Name.ToString();
string Value = JsonProperty.Value.ToString();
Console.WriteLine(Key + " : " + Value);
}
}
}