AnalyzeJSON.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 class AnalyzeJSON
  9. {
  10. private readonly JObject json;
  11. public AnalyzeJSON(string path)
  12. {
  13. if (!File.Exists(path))
  14. throw new ArgumentNullException("path");
  15. using StreamReader sr = new StreamReader(path);
  16. var jsonString = sr.ReadToEnd();
  17. json = JsonConvert.DeserializeObject<JObject>(jsonString);
  18. }
  19. public static string GetNameFromPath(string tokenPath)
  20. {
  21. if (string.IsNullOrWhiteSpace(tokenPath))
  22. return string.Empty;
  23. return tokenPath.Split(".").Last();
  24. }
  25. private void Traverse(IJEnumerable<JToken> tokens, Action<JToken> action)
  26. {
  27. foreach (var token in tokens)
  28. {
  29. action.Invoke(token);
  30. if (token.HasValues)
  31. Traverse(token.Children(), action);
  32. }
  33. }
  34. public void Traverse(Action<JToken> action)
  35. {
  36. if (!json.HasValues)
  37. return;
  38. Traverse(json.Children(), action);
  39. }
  40. }
  41. }