AnalyzeJSON.cs 1.7 KB

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