AnalyzeJSON.cs 2.2 KB

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