JsonNetValueSystem.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections;
  3. using System.Linq;
  4. using Newtonsoft.Json.Linq;
  5. namespace WebTest.JsonPath
  6. {
  7. public class JsonNetValueSystem : IJsonPathValueSystem
  8. {
  9. public bool HasMember(object value, string member)
  10. {
  11. if (value is JObject)
  12. {
  13. return (value as JObject).Properties().Any(property => property.Name == member);
  14. }
  15. if (value is JArray)
  16. {
  17. var index = ParseInt(member, -1);
  18. return index >= 0 && index < (value as JArray).Count;
  19. }
  20. return false;
  21. }
  22. public object GetMemberValue(object value, string member)
  23. {
  24. if (value is JObject)
  25. {
  26. var memberValue = (value as JObject)[member];
  27. return memberValue;
  28. }
  29. if (value is JArray)
  30. {
  31. var index = ParseInt(member, -1);
  32. return (value as JArray)[index];
  33. }
  34. return null;
  35. }
  36. public IEnumerable GetMembers(object value)
  37. {
  38. var jobject = value as JObject;
  39. return jobject?.Properties().Select(property => property.Name);
  40. }
  41. public bool IsObject(object value) => value is JObject;
  42. public bool IsArray(object value) => value is JArray;
  43. public bool IsPrimitive(object value)
  44. {
  45. if (value == null)
  46. {
  47. throw new ArgumentNullException("value");
  48. }
  49. return !(value is JObject) && !(value is JArray);
  50. }
  51. int ParseInt(string s, int defaultValue) => int.TryParse(s, out int result) ? result : defaultValue;
  52. }
  53. }