AnalyzeJSON.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. if (string.IsNullOrWhiteSpace(tokenPath))
  27. return string.Empty;
  28. return tokenPath.Split(".").Last();
  29. }
  30. private void Traverse(IJEnumerable<JToken> tokens, Action<JToken> action)
  31. {
  32. foreach (var token in tokens)
  33. {
  34. action.Invoke(token);
  35. if (token.HasValues)
  36. Traverse(token.Children(), action);
  37. }
  38. }
  39. public Status Traverse(Action<JToken> action)
  40. {
  41. if (!json.HasValues)
  42. return new(false, "JSON is empty!");
  43. if (action == null)
  44. return new(false, "Action can't be null!");
  45. Traverse(json.Children(), action);
  46. return new(true, string.Empty);
  47. }
  48. }
  49. }