AnalyzeJSON.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using Newtonsoft.Json;
  5. using Newtonsoft.Json.Linq;
  6. namespace analyzeJSON
  7. {
  8. public record Status(bool Success = false, string Message = "");
  9. public class AnalyzeJSON
  10. {
  11. private readonly JObject json;
  12. public AnalyzeJSON(string path)
  13. {
  14. if (!File.Exists(path))
  15. throw new ArgumentNullException(nameof(path));
  16. using var sr = new StreamReader(path);
  17. var jsonString = sr.ReadToEnd();
  18. json = JsonConvert.DeserializeObject<JObject>(jsonString);
  19. }
  20. public AnalyzeJSON(JObject jObject)
  21. {
  22. json = jObject ?? throw new ArgumentNullException(nameof(jObject));
  23. }
  24. public static string GetNameFromPath(string tokenPath)
  25. {
  26. return string.IsNullOrWhiteSpace(tokenPath) ? string.Empty : tokenPath.Split(".").Last();
  27. }
  28. private void Traverse(IJEnumerable<JToken> tokens, Action<JToken> action)
  29. {
  30. foreach (var token in tokens)
  31. {
  32. action.Invoke(token);
  33. if (token.HasValues)
  34. Traverse(token.Children(), action);
  35. }
  36. }
  37. public Status Traverse(Action<JToken> action)
  38. {
  39. if (!json.HasValues)
  40. return new(false, "JSON is empty!");
  41. if (action == null)
  42. return new(false, "Action can't be null!");
  43. Traverse(json.Children(), action);
  44. return new(true, string.Empty);
  45. }
  46. }
  47. }