IDictionaryExtensions.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Topten.JsonKit
  7. {
  8. public static class IDictionaryExtensions
  9. {
  10. public static bool WalkPath(this IDictionary<string, object> This, string Path, bool create, Func<IDictionary<string,object>,string, bool> leafCallback)
  11. {
  12. // Walk the path
  13. var parts = Path.Split('.');
  14. for (int i = 0; i < parts.Length-1; i++)
  15. {
  16. object val;
  17. if (!This.TryGetValue(parts[i], out val))
  18. {
  19. if (!create)
  20. return false;
  21. val = new Dictionary<string, object>();
  22. This[parts[i]] = val;
  23. }
  24. This = (IDictionary<string,object>)val;
  25. }
  26. // Process the leaf
  27. return leafCallback(This, parts[parts.Length-1]);
  28. }
  29. public static bool PathExists(this IDictionary<string, object> This, string Path)
  30. {
  31. return This.WalkPath(Path, false, (dict, key) => dict.ContainsKey(key));
  32. }
  33. public static object GetPath(this IDictionary<string, object> This, Type type, string Path, object def)
  34. {
  35. This.WalkPath(Path, false, (dict, key) =>
  36. {
  37. object val;
  38. if (dict.TryGetValue(key, out val))
  39. {
  40. if (val == null)
  41. def = val;
  42. else if (type.IsAssignableFrom(val.GetType()))
  43. def = val;
  44. else
  45. def = Json.Reparse(type, val);
  46. }
  47. return true;
  48. });
  49. return def;
  50. }
  51. // Ensure there's an object of type T at specified path
  52. public static T GetObjectAtPath<T>(this IDictionary<string, object> This, string Path) where T:class,new()
  53. {
  54. T retVal = null;
  55. This.WalkPath(Path, true, (dict, key) =>
  56. {
  57. object val;
  58. dict.TryGetValue(key, out val);
  59. retVal = val as T;
  60. if (retVal == null)
  61. {
  62. retVal = val == null ? new T() : Json.Reparse<T>(val);
  63. dict[key] = retVal;
  64. }
  65. return true;
  66. });
  67. return retVal;
  68. }
  69. public static T GetPath<T>(this IDictionary<string, object> This, string Path, T def = default(T))
  70. {
  71. return (T)This.GetPath(typeof(T), Path, def);
  72. }
  73. public static void SetPath(this IDictionary<string, object> This, string Path, object value)
  74. {
  75. This.WalkPath(Path, true, (dict, key) => { dict[key] = value; return true; });
  76. }
  77. }
  78. }