JSONNode.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace ZenFulcrum.EmbeddedBrowser {
  5. /**
  6. * Stand-in class for a JavaScript value that can be one of many different types.
  7. *
  8. * Bad lookups are safe. That is, if you try to look up something that doesn't exist you will not get an exception,
  9. * but an "invalid" node. Use Check() if you want an exception on invalid lookups:
  10. *
  11. * var node = JSONNode.Parse(@"{""a"":1}");
  12. * node["a"].IsValid == true;
  13. * node["bob"].IsValid == false
  14. * node["bob"]["foo"].IsValid == false //but doesn't throw an exception
  15. * node["a"].Check() //okay
  16. * node["bob"].Check() //throw exception
  17. *
  18. * Values can be implicitly converted to JSONNodes and back. That means you don't have to use properties like
  19. * "IntValue" and "StringValue". Simply try to use the node as that type and it will convert to the value
  20. * if it's that type or return a default value if it isn't:
  21. *
  22. * var node = JSONNode.Parse(@"{""a"":1, ""b"": ""apples""}");
  23. * int a = node["a"];
  24. * a == 1;
  25. * string b = node["b"];
  26. * b == "apples";
  27. * string str = node["a"];
  28. * str == null; //null is the default value for a string.
  29. *
  30. * You can also use new JSONNode(value) for many different types, though often it's easier to just assign a
  31. * value and let it auto-convert.
  32. *
  33. * Because they act a little special, use node.IsNull and node.IsValid to check for null and invalid values.
  34. * Real null still acts like null, though, so use JSONNode.NullNode to create a "null" JSONNode.
  35. * You can also use JSONNode.InvalidNode to get an invalid JSONNode outright.
  36. *
  37. * Note that, while reading blind is safe, assignment is not. Attempting to assign object keys to an integer, for example,
  38. * will throw an exception. To append to an array, call .Add() or assign to -1. To remove an object key or array element,
  39. * assign JSONNode.InvalidNode to it.
  40. *
  41. */
  42. public class JSONNode {
  43. /** Parses the given JSON document to a JSONNode. Throws a SerializationException on parse error. */
  44. public static JSONNode Parse(string json) {
  45. return JSONParser.Parse(json);
  46. }
  47. public static readonly JSONNode InvalidNode = new JSONNode(NodeType.Invalid);
  48. public static readonly JSONNode NullNode = new JSONNode(NodeType.Null);
  49. public enum NodeType {
  50. /** Getting this value would result in undefined or ordinarily throw some type of exception trying to fetch it. */
  51. Invalid,
  52. String,
  53. Number,
  54. Object,
  55. Array,
  56. Bool,
  57. Null,
  58. }
  59. public NodeType _type = NodeType.Invalid;
  60. private string _stringValue;
  61. private double _numberValue;
  62. private Dictionary<string, JSONNode> _objectValue;
  63. private List<JSONNode> _arrayValue;
  64. private bool _boolValue;
  65. public JSONNode(NodeType type = NodeType.Null) {
  66. this._type = type;
  67. if (type == NodeType.Object) _objectValue = new Dictionary<string, JSONNode>();
  68. else if (type == NodeType.Array) _arrayValue = new List<JSONNode>();
  69. }
  70. public JSONNode(string value) {
  71. this._type = NodeType.String;
  72. _stringValue = value;
  73. }
  74. public JSONNode(double value) {
  75. this._type = NodeType.Number;
  76. _numberValue = value;
  77. }
  78. public JSONNode(Dictionary<string, JSONNode> value) {
  79. this._type = NodeType.Object;
  80. _objectValue = value;
  81. }
  82. public JSONNode(List<JSONNode> value) {
  83. this._type = NodeType.Array;
  84. _arrayValue = value;
  85. }
  86. public JSONNode(bool value) {
  87. this._type = NodeType.Bool;
  88. _boolValue = value;
  89. }
  90. public NodeType Type { get { return _type; } }
  91. public bool IsValid {
  92. get { return _type != NodeType.Invalid; }
  93. }
  94. /**
  95. * Checks if the node is valid. If not, throws an exception.
  96. * Returns {this}, which allows you to add this statement inline in you expressions.
  97. *
  98. * Example:
  99. * var node = data["key1"][1].Check();
  100. * int val = data["maxSize"].Check()["elements"][3];
  101. */
  102. public JSONNode Check() {
  103. if (_type == NodeType.Invalid) throw new InvalidJSONNodeException();
  104. return this;
  105. }
  106. public static implicit operator string(JSONNode n) {
  107. return n._type == NodeType.String ? n._stringValue : null;
  108. }
  109. public static implicit operator JSONNode(string v) {
  110. return new JSONNode(v);
  111. }
  112. public static implicit operator int(JSONNode n) {
  113. return n._type == NodeType.Number ? (int)n._numberValue : 0;
  114. }
  115. public static implicit operator JSONNode(int v) {
  116. return new JSONNode(v);
  117. }
  118. public static implicit operator float(JSONNode n) {
  119. return n._type == NodeType.Number ? (float)n._numberValue : 0;
  120. }
  121. public static implicit operator JSONNode(float v) {
  122. return new JSONNode(v);
  123. }
  124. public static implicit operator double(JSONNode n) {
  125. return n._type == NodeType.Number ? n._numberValue : 0;
  126. }
  127. public static implicit operator JSONNode(double v) {
  128. return new JSONNode(v);
  129. }
  130. /**
  131. * Setter/getter for keys on an object. All keys are strings.
  132. * Assign JSONNode.InvalidValue to delete a key.
  133. */
  134. public JSONNode this[string k] {
  135. get {
  136. if (_type == NodeType.Object) {
  137. JSONNode ret;
  138. if (_objectValue.TryGetValue(k, out ret)) return ret;
  139. }
  140. return InvalidNode;
  141. }
  142. set {
  143. if (_type != NodeType.Object) throw new InvalidJSONNodeException();
  144. if (value._type == NodeType.Invalid) _objectValue.Remove(k);
  145. else _objectValue[k] = value;
  146. }
  147. }
  148. public static implicit operator Dictionary<string, JSONNode>(JSONNode n) {
  149. return n._type == NodeType.Object ? n._objectValue : null;
  150. }
  151. /**
  152. * Setter/getter for indicies on an array.
  153. * Assign JSONNode.InvalidValue to delete a key.
  154. * Assign to "-1" to append to the end.
  155. */
  156. public JSONNode this[int idx] {
  157. get {
  158. if (_type == NodeType.Array && idx >= 0 && idx < _arrayValue.Count) {
  159. return _arrayValue[idx];
  160. }
  161. return InvalidNode;
  162. }
  163. set {
  164. if (_type != NodeType.Array) throw new InvalidJSONNodeException();
  165. if (idx == -1) {
  166. if (value._type == NodeType.Invalid) {
  167. _arrayValue.RemoveAt(_arrayValue.Count - 1);
  168. } else {
  169. _arrayValue.Add(value);
  170. }
  171. } else {
  172. if (value._type == NodeType.Invalid) {
  173. _arrayValue.RemoveAt(idx);
  174. } else {
  175. _arrayValue[idx] = value;
  176. }
  177. }
  178. }
  179. }
  180. public static implicit operator List<JSONNode>(JSONNode n) {
  181. return n._type == NodeType.Array ? n._arrayValue : null;
  182. }
  183. /** Adds an items if the node is an array. */
  184. public void Add(JSONNode item) {
  185. if (_type != NodeType.Array) throw new InvalidJSONNodeException();
  186. _arrayValue.Add(item);
  187. }
  188. /** If we are an array or object, returns the size, otherwise returns 0. */
  189. public int Count {
  190. get {
  191. switch (_type) {
  192. case NodeType.Array: return _arrayValue.Count;
  193. case NodeType.Object: return _objectValue.Count;
  194. default: return 0;
  195. }
  196. }
  197. }
  198. /** True if the value of this node is exactly null. */
  199. public bool IsNull {
  200. get { return _type == NodeType.Null; }
  201. }
  202. public static implicit operator bool(JSONNode n) {
  203. return n._type == NodeType.Bool ? n._boolValue : false;
  204. }
  205. public static implicit operator JSONNode(bool v) {
  206. return new JSONNode(v);
  207. }
  208. /** Returns a native value representation of our value. */
  209. public object Value {
  210. get {
  211. switch (_type) {
  212. case NodeType.Invalid:
  213. Check();
  214. return null;//we don't get here.
  215. case NodeType.String:
  216. return _stringValue;
  217. case NodeType.Number:
  218. return _numberValue;
  219. case NodeType.Object:
  220. return _objectValue;
  221. case NodeType.Array:
  222. return _arrayValue;
  223. case NodeType.Bool:
  224. return _boolValue;
  225. case NodeType.Null:
  226. return null;
  227. default:
  228. throw new ArgumentOutOfRangeException();
  229. }
  230. }
  231. }
  232. /** Serializes the JSON node and returns a JSON string. */
  233. public string AsJSON {
  234. get {
  235. return JSONParser.Serialize(this);
  236. }
  237. }
  238. }
  239. public class InvalidJSONNodeException : Exception {}
  240. }