AnalyzeStructure.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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, bool IsLeaf = false)
  7. {
  8. public int Count;
  9. }
  10. public class AnalyzeStructure
  11. {
  12. private Dictionary<string, Token> nodes = new Dictionary<string, Token>();
  13. private Dictionary<string, Token> leafs = new Dictionary<string, Token>();
  14. public AnalyzeStructure()
  15. {
  16. }
  17. public void AnalyzeToken(JToken token)
  18. {
  19. if (token.Type == JTokenType.Object || token.Type == JTokenType.Array)
  20. return;
  21. var tokenName = AnalyzeJSON.GetNameFromPath(token.Path);
  22. if (token.HasValues)
  23. {
  24. var nodeToken = new Token(tokenName, token.Type);
  25. if (token.First.Equals(token.Last) &&
  26. token.First.Type != JTokenType.Array &&
  27. token.First.Type != JTokenType.Property &&
  28. token.First.Type != JTokenType.Object)
  29. return;
  30. if (nodes.ContainsKey(tokenName))
  31. nodes[tokenName].Count++;
  32. else
  33. {
  34. nodeToken.Count++;
  35. nodes.Add(tokenName, nodeToken);
  36. }
  37. }
  38. else
  39. {
  40. var leafToken = new Token(tokenName, token.Type, true);
  41. if (leafs.ContainsKey(tokenName))
  42. leafs[tokenName].Count++;
  43. else
  44. {
  45. leafToken.Count++;
  46. leafs.Add(tokenName, leafToken);
  47. }
  48. }
  49. }
  50. public AnalysisResult<Dictionary<string, Token>> Result
  51. {
  52. get
  53. {
  54. return new(nodes, leafs);
  55. }
  56. }
  57. }
  58. }