AnalyzeStructure.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 IsNode = false)
  7. {
  8. public int Count;
  9. }
  10. public class AnalyzeStructure
  11. {
  12. private readonly Dictionary<string, Token> nodes = new();
  13. private readonly Dictionary<string, Token> leafs = new();
  14. public void AnalyzeToken(JToken token)
  15. {
  16. if (token.Type is JTokenType.Object or JTokenType.Array)
  17. return;
  18. var tokenName = AnalyzeJSON.GetNameFromPath(token.Path);
  19. if (token.HasValues)
  20. {
  21. var nodeToken = new Token(tokenName, token.Type, true);
  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(tokenName))
  28. nodes[tokenName].Count++;
  29. else
  30. {
  31. nodeToken.Count++;
  32. nodes.Add(tokenName, nodeToken);
  33. }
  34. }
  35. else
  36. {
  37. var leafToken = new Token(tokenName, token.Type);
  38. if (leafs.ContainsKey(tokenName))
  39. leafs[tokenName].Count++;
  40. else
  41. {
  42. leafToken.Count++;
  43. leafs.Add(tokenName, leafToken);
  44. }
  45. }
  46. }
  47. public AnalysisResult<Dictionary<string, Token>> Result
  48. {
  49. get
  50. {
  51. foreach (var leaf in leafs)
  52. {
  53. if (nodes.ContainsKey(leaf.Key))
  54. leafs[leaf.Key] = leaf.Value with { IsNode = true };
  55. }
  56. return new(nodes, leafs);
  57. }
  58. }
  59. }
  60. }