AnalyzeStructure.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System.Collections.Generic;
  2. using Newtonsoft.Json.Linq;
  3. namespace analyzeJSON
  4. {
  5. public record AnalysisResult<T>(T Nodes, T Leafs);
  6. public record Token(string Name, JTokenType Type);
  7. public class AnalyzeStructure
  8. {
  9. private Dictionary<Token, int> nodes = new Dictionary<Token, int>();
  10. private Dictionary<Token, int> leafs = new Dictionary<Token, int>();
  11. public AnalyzeStructure()
  12. {
  13. }
  14. public void AnalyzeToken(JToken token)
  15. {
  16. if (token.Type == JTokenType.Object || token.Type == JTokenType.Array)
  17. return;
  18. var tokenName = AnalyzeJSON.GetNameFromPath(token.Path);
  19. var currentToken = new Token(tokenName, token.Type);
  20. if (token.HasValues)
  21. {
  22. if (token.First.Equals(token.Last) &&
  23. token.First.Type != JTokenType.Array &&
  24. token.First.Type != JTokenType.Property &&
  25. token.First.Type != JTokenType.Object)
  26. return;
  27. if (nodes.ContainsKey(currentToken))
  28. nodes[currentToken]++;
  29. else
  30. nodes.Add(currentToken, 1);
  31. }
  32. else
  33. {
  34. if (leafs.ContainsKey(currentToken))
  35. leafs[currentToken]++;
  36. else
  37. leafs.Add(currentToken, 1);
  38. }
  39. }
  40. public AnalysisResult<Dictionary<Token, int>> Result => new(nodes, leafs);
  41. }
  42. }