Browse Source

Trying to analyze JSON

Piotr Czajkowski 2 years ago
parent
commit
b39aed6267
3 changed files with 75 additions and 0 deletions
  1. 18 0
      AnalyzeJSON.cs
  2. 39 0
      AnalyzeStructure.cs
  3. 18 0
      analyzeJSONTests/AnalyzeStructureIntegrationTests.cs

+ 18 - 0
AnalyzeJSON.cs

@@ -18,5 +18,23 @@ namespace analyzeJSON
             var jsonString = sr.ReadToEnd();
             json = JsonConvert.DeserializeObject<JObject>(jsonString);
         }
+
+        private void Traverse(IJEnumerable<JToken> tokens, Action<JToken> action)
+        {
+            foreach (var token in tokens)
+            {
+                action.Invoke(token);
+                if (token.HasValues)
+                    Traverse(token.Children(), action);
+            }
+        }
+
+        public void Traverse(Action<JToken> action)
+        {
+            if (!json.HasValues)
+                return;
+
+            Traverse(json.Children(), action);
+        }
     }
 }

+ 39 - 0
AnalyzeStructure.cs

@@ -0,0 +1,39 @@
+using System.Collections.Generic;
+using Newtonsoft.Json.Linq;
+
+namespace analyzeJSON
+{
+    public class AnalyzeStructure
+    {
+        private Dictionary<string, int> nodes = new Dictionary<string, int>();
+        private Dictionary<string, int> leafs = new Dictionary<string, int>();
+
+        public AnalyzeStructure()
+        {
+        }
+
+        public void AnalyzeToken(JToken token)
+        {
+            if (token.HasValues)
+            {
+                if (token.First.Equals(token.Last) &&
+                    token.First.Type != JTokenType.Array && token.First.Type != JTokenType.Property && token.First.Type != JTokenType.Object)
+                {
+                    return;
+                }
+
+                if (nodes.ContainsKey(token.Path))
+                    nodes[token.Path]++;
+                else
+                    nodes.Add(token.Path, 1);
+            }
+            else
+            {
+                if (leafs.ContainsKey(token.Path))
+                    leafs[token.Path]++;
+                else
+                    leafs.Add(token.Path, 1);
+            }
+        }
+    }
+}

+ 18 - 0
analyzeJSONTests/AnalyzeStructureIntegrationTests.cs

@@ -0,0 +1,18 @@
+using Xunit;
+using analyzeJSON;
+
+namespace analyzeJSONTests
+{
+    public class AnalyzeStructureIntegrationTests
+    {
+        private static readonly string testFile = @"testFiles/complex.json";
+
+        [Fact]
+        public void AnalyzeToken_withTraverse()
+        {
+            var test = new AnalyzeJSON(testFile);
+            var analyze = new AnalyzeStructure();
+            test.Traverse((token) => analyze.AnalyzeToken(token));
+        }
+    }
+}