DataSnapshot.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. 
  2. using System.Collections.Generic;
  3. using System.Security;
  4. namespace SimpleFirebaseUnity
  5. {
  6. using MiniJSON;
  7. public class DataSnapshot
  8. {
  9. protected object val_obj;
  10. protected Dictionary<string, object> val_dict;
  11. protected List<string> keys;
  12. protected string json;
  13. protected DataSnapshot()
  14. {
  15. val_dict = null;
  16. val_obj = null;
  17. keys = null;
  18. json = null;
  19. }
  20. /// <summary>
  21. /// Creates snapshot from Json string
  22. /// </summary>
  23. /// <param name="json">Json string</param>
  24. public DataSnapshot(string _json = "")
  25. {
  26. object obj = (_json != null && _json.Length > 0)?Json.Deserialize(_json):null;
  27. if (obj is Dictionary<string, object>)
  28. val_dict = obj as Dictionary<string, object>;
  29. else
  30. val_obj = obj;
  31. keys = null;
  32. json = _json;
  33. }
  34. /// <summary>
  35. /// If snapshot is a Dictionary, returns keys of the snapshot , else null
  36. /// </summary>
  37. public List<string> Keys
  38. {
  39. get
  40. {
  41. if (keys == null && val_dict != null)
  42. keys = new List<string>(val_dict.Keys);
  43. return keys;
  44. }
  45. }
  46. /// <summary>
  47. /// If snapshot is a Dictionary, gives the first key founded on snapshot, else null
  48. /// </summary>
  49. public string FirstKey
  50. {
  51. get
  52. {
  53. return (val_dict == null) ? null : Keys[0];
  54. }
  55. }
  56. /// <summary>
  57. /// Raw json of snapshot
  58. /// </summary>
  59. public string RawJson
  60. {
  61. get
  62. {
  63. return json;
  64. }
  65. }
  66. /// <summary>
  67. /// Raw value of snapshot
  68. /// </summary>
  69. public object RawValue
  70. {
  71. get
  72. {
  73. return (val_dict == null) ? val_obj : val_dict;
  74. }
  75. }
  76. /// <summary>
  77. /// Gets value from snapshot
  78. /// </summary>
  79. /// <typeparam name="T">Desired type</typeparam>
  80. /// <returns>Value of snapshot as the defined type, null if typecasting failed</returns>
  81. [SecuritySafeCritical]
  82. public T Value<T>()
  83. {
  84. try
  85. {
  86. if (val_obj != null)
  87. return (T)val_obj;
  88. object obj = val_dict;
  89. return (T)obj;
  90. }
  91. catch {
  92. return default(T);
  93. }
  94. }
  95. }
  96. }