dynamic.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #if net4
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Dynamic;
  5. using System.Linq;
  6. namespace fastJSON
  7. {
  8. internal class DynamicJson : DynamicObject
  9. {
  10. private IDictionary<string, object> _dictionary { get; set; }
  11. private List<object> _list { get; set; }
  12. public DynamicJson(string json)
  13. {
  14. var parse = fastJSON.JSON.Parse(json);
  15. if (parse is IDictionary<string, object>)
  16. _dictionary = (IDictionary<string, object>)parse;
  17. else
  18. _list = (List<object>)parse;
  19. }
  20. private DynamicJson(object dictionary)
  21. {
  22. if (dictionary is IDictionary<string, object>)
  23. _dictionary = (IDictionary<string, object>)dictionary;
  24. }
  25. public override IEnumerable<string> GetDynamicMemberNames()
  26. {
  27. return _dictionary.Keys.ToList();
  28. }
  29. public override bool TryGetIndex(GetIndexBinder binder, Object[] indexes, out Object result)
  30. {
  31. var index = indexes[0];
  32. if (index is int)
  33. {
  34. result = _list[(int) index];
  35. }
  36. else
  37. {
  38. result = _dictionary[(string) index];
  39. }
  40. if (result is IDictionary<string, object>)
  41. result = new DynamicJson(result as IDictionary<string, object>);
  42. return true;
  43. }
  44. public override bool TryGetMember(GetMemberBinder binder, out object result)
  45. {
  46. if (_dictionary.TryGetValue(binder.Name, out result) == false)
  47. if (_dictionary.TryGetValue(binder.Name.ToLower(), out result) == false)
  48. return false;// throw new Exception("property not found " + binder.Name);
  49. if (result is IDictionary<string, object>)
  50. {
  51. result = new DynamicJson(result as IDictionary<string, object>);
  52. }
  53. else if (result is List<object>)
  54. {
  55. List<object> list = new List<object>();
  56. foreach (object item in (List<object>)result)
  57. {
  58. if (item is IDictionary<string, object>)
  59. list.Add(new DynamicJson(item as IDictionary<string, object>));
  60. else
  61. list.Add(item);
  62. }
  63. result = list;
  64. }
  65. return _dictionary.ContainsKey(binder.Name);
  66. }
  67. }
  68. }
  69. #endif