SimpleJson.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434
  1. /* * * * *
  2. * A simple JSON Parser / builder
  3. * ------------------------------
  4. *
  5. * It mainly has been written as a simple JSON parser. It can build a JSON string
  6. * from the node-tree, or generate a node tree from any valid JSON string.
  7. *
  8. * Written by Bunny83
  9. * 2012-06-09
  10. *
  11. * Changelog now external. See Changelog.txt
  12. *
  13. * The MIT License (MIT)
  14. *
  15. * Copyright (c) 2012-2019 Markus Göbel (Bunny83)
  16. *
  17. * Permission is hereby granted, free of charge, to any person obtaining a copy
  18. * of this software and associated documentation files (the "Software"), to deal
  19. * in the Software without restriction, including without limitation the rights
  20. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21. * copies of the Software, and to permit persons to whom the Software is
  22. * furnished to do so, subject to the following conditions:
  23. *
  24. * The above copyright notice and this permission notice shall be included in all
  25. * copies or substantial portions of the Software.
  26. *
  27. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  28. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  30. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  31. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  32. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  33. * SOFTWARE.
  34. *
  35. * * * * */
  36. using System;
  37. using System.Collections;
  38. using System.Collections.Generic;
  39. using System.Globalization;
  40. using System.Linq;
  41. using System.Text;
  42. namespace ARLocation.Vendor.SimpleJSON
  43. {
  44. public enum JSONNodeType
  45. {
  46. Array = 1,
  47. Object = 2,
  48. String = 3,
  49. Number = 4,
  50. NullValue = 5,
  51. Boolean = 6,
  52. None = 7,
  53. Custom = 0xFF,
  54. }
  55. public enum JSONTextMode
  56. {
  57. Compact,
  58. Indent
  59. }
  60. public abstract partial class JSONNode
  61. {
  62. #region Enumerators
  63. public struct Enumerator
  64. {
  65. private enum Type { None, Array, Object }
  66. private Type type;
  67. private Dictionary<string, JSONNode>.Enumerator m_Object;
  68. private List<JSONNode>.Enumerator m_Array;
  69. public bool IsValid { get { return type != Type.None; } }
  70. public Enumerator(List<JSONNode>.Enumerator aArrayEnum)
  71. {
  72. type = Type.Array;
  73. m_Object = default(Dictionary<string, JSONNode>.Enumerator);
  74. m_Array = aArrayEnum;
  75. }
  76. public Enumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum)
  77. {
  78. type = Type.Object;
  79. m_Object = aDictEnum;
  80. m_Array = default(List<JSONNode>.Enumerator);
  81. }
  82. public KeyValuePair<string, JSONNode> Current
  83. {
  84. get
  85. {
  86. if (type == Type.Array)
  87. return new KeyValuePair<string, JSONNode>(string.Empty, m_Array.Current);
  88. else if (type == Type.Object)
  89. return m_Object.Current;
  90. return new KeyValuePair<string, JSONNode>(string.Empty, null);
  91. }
  92. }
  93. public bool MoveNext()
  94. {
  95. if (type == Type.Array)
  96. return m_Array.MoveNext();
  97. else if (type == Type.Object)
  98. return m_Object.MoveNext();
  99. return false;
  100. }
  101. }
  102. public struct ValueEnumerator
  103. {
  104. private Enumerator m_Enumerator;
  105. public ValueEnumerator(List<JSONNode>.Enumerator aArrayEnum) : this(new Enumerator(aArrayEnum)) { }
  106. public ValueEnumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum) : this(new Enumerator(aDictEnum)) { }
  107. public ValueEnumerator(Enumerator aEnumerator) { m_Enumerator = aEnumerator; }
  108. public JSONNode Current { get { return m_Enumerator.Current.Value; } }
  109. public bool MoveNext() { return m_Enumerator.MoveNext(); }
  110. public ValueEnumerator GetEnumerator() { return this; }
  111. }
  112. public struct KeyEnumerator
  113. {
  114. private Enumerator m_Enumerator;
  115. public KeyEnumerator(List<JSONNode>.Enumerator aArrayEnum) : this(new Enumerator(aArrayEnum)) { }
  116. public KeyEnumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum) : this(new Enumerator(aDictEnum)) { }
  117. public KeyEnumerator(Enumerator aEnumerator) { m_Enumerator = aEnumerator; }
  118. public string Current { get { return m_Enumerator.Current.Key; } }
  119. public bool MoveNext() { return m_Enumerator.MoveNext(); }
  120. public KeyEnumerator GetEnumerator() { return this; }
  121. }
  122. public class LinqEnumerator : IEnumerator<KeyValuePair<string, JSONNode>>, IEnumerable<KeyValuePair<string, JSONNode>>
  123. {
  124. private JSONNode m_Node;
  125. private Enumerator m_Enumerator;
  126. internal LinqEnumerator(JSONNode aNode)
  127. {
  128. m_Node = aNode;
  129. if (m_Node != null)
  130. m_Enumerator = m_Node.GetEnumerator();
  131. }
  132. public KeyValuePair<string, JSONNode> Current { get { return m_Enumerator.Current; } }
  133. object IEnumerator.Current { get { return m_Enumerator.Current; } }
  134. public bool MoveNext() { return m_Enumerator.MoveNext(); }
  135. public void Dispose()
  136. {
  137. m_Node = null;
  138. m_Enumerator = new Enumerator();
  139. }
  140. public IEnumerator<KeyValuePair<string, JSONNode>> GetEnumerator()
  141. {
  142. return new LinqEnumerator(m_Node);
  143. }
  144. public void Reset()
  145. {
  146. if (m_Node != null)
  147. m_Enumerator = m_Node.GetEnumerator();
  148. }
  149. IEnumerator IEnumerable.GetEnumerator()
  150. {
  151. return new LinqEnumerator(m_Node);
  152. }
  153. }
  154. #endregion Enumerators
  155. #region common interface
  156. public static bool forceASCII = false; // Use Unicode by default
  157. public static bool longAsString = false; // lazy creator creates a JSONString instead of JSONNumber
  158. public static bool allowLineComments = true; // allow "//"-style comments at the end of a line
  159. public abstract JSONNodeType Tag { get; }
  160. public virtual JSONNode this[int aIndex] { get { return null; } set { } }
  161. public virtual JSONNode this[string aKey] { get { return null; } set { } }
  162. public virtual string Value { get { return ""; } set { } }
  163. public virtual int Count { get { return 0; } }
  164. public virtual bool IsNumber { get { return false; } }
  165. public virtual bool IsString { get { return false; } }
  166. public virtual bool IsBoolean { get { return false; } }
  167. public virtual bool IsNull { get { return false; } }
  168. public virtual bool IsArray { get { return false; } }
  169. public virtual bool IsObject { get { return false; } }
  170. public virtual bool Inline { get { return false; } set { } }
  171. public virtual void Add(string aKey, JSONNode aItem)
  172. {
  173. }
  174. public virtual void Add(JSONNode aItem)
  175. {
  176. Add("", aItem);
  177. }
  178. public virtual JSONNode Remove(string aKey)
  179. {
  180. return null;
  181. }
  182. public virtual JSONNode Remove(int aIndex)
  183. {
  184. return null;
  185. }
  186. public virtual JSONNode Remove(JSONNode aNode)
  187. {
  188. return aNode;
  189. }
  190. public virtual void Clear() { }
  191. public virtual JSONNode Clone()
  192. {
  193. return null;
  194. }
  195. public virtual IEnumerable<JSONNode> Children
  196. {
  197. get
  198. {
  199. yield break;
  200. }
  201. }
  202. public IEnumerable<JSONNode> DeepChildren
  203. {
  204. get
  205. {
  206. foreach (var C in Children)
  207. foreach (var D in C.DeepChildren)
  208. yield return D;
  209. }
  210. }
  211. public virtual bool HasKey(string aKey)
  212. {
  213. return false;
  214. }
  215. public virtual JSONNode GetValueOrDefault(string aKey, JSONNode aDefault)
  216. {
  217. return aDefault;
  218. }
  219. public override string ToString()
  220. {
  221. StringBuilder sb = new StringBuilder();
  222. WriteToStringBuilder(sb, 0, 0, JSONTextMode.Compact);
  223. return sb.ToString();
  224. }
  225. public virtual string ToString(int aIndent)
  226. {
  227. StringBuilder sb = new StringBuilder();
  228. WriteToStringBuilder(sb, 0, aIndent, JSONTextMode.Indent);
  229. return sb.ToString();
  230. }
  231. internal abstract void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode);
  232. public abstract Enumerator GetEnumerator();
  233. public IEnumerable<KeyValuePair<string, JSONNode>> Linq { get { return new LinqEnumerator(this); } }
  234. public KeyEnumerator Keys { get { return new KeyEnumerator(GetEnumerator()); } }
  235. public ValueEnumerator Values { get { return new ValueEnumerator(GetEnumerator()); } }
  236. #endregion common interface
  237. #region typecasting properties
  238. public virtual double AsDouble
  239. {
  240. get
  241. {
  242. double v = 0.0;
  243. if (double.TryParse(Value, NumberStyles.Float, CultureInfo.InvariantCulture, out v))
  244. return v;
  245. return 0.0;
  246. }
  247. set
  248. {
  249. Value = value.ToString(CultureInfo.InvariantCulture);
  250. }
  251. }
  252. public virtual int AsInt
  253. {
  254. get { return (int)AsDouble; }
  255. set { AsDouble = value; }
  256. }
  257. public virtual float AsFloat
  258. {
  259. get { return (float)AsDouble; }
  260. set { AsDouble = value; }
  261. }
  262. public virtual bool AsBool
  263. {
  264. get
  265. {
  266. bool v = false;
  267. if (bool.TryParse(Value, out v))
  268. return v;
  269. return !string.IsNullOrEmpty(Value);
  270. }
  271. set
  272. {
  273. Value = (value) ? "true" : "false";
  274. }
  275. }
  276. public virtual long AsLong
  277. {
  278. get
  279. {
  280. long val = 0;
  281. if (long.TryParse(Value, out val))
  282. return val;
  283. return 0L;
  284. }
  285. set
  286. {
  287. Value = value.ToString();
  288. }
  289. }
  290. public virtual ulong AsULong
  291. {
  292. get
  293. {
  294. ulong val = 0;
  295. if (ulong.TryParse(Value, out val))
  296. return val;
  297. return 0;
  298. }
  299. set
  300. {
  301. Value = value.ToString();
  302. }
  303. }
  304. public virtual JSONArray AsArray
  305. {
  306. get
  307. {
  308. return this as JSONArray;
  309. }
  310. }
  311. public virtual JSONObject AsObject
  312. {
  313. get
  314. {
  315. return this as JSONObject;
  316. }
  317. }
  318. #endregion typecasting properties
  319. #region operators
  320. public static implicit operator JSONNode(string s)
  321. {
  322. return (s == null) ? (JSONNode) JSONNull.CreateOrGet() : new JSONString(s);
  323. }
  324. public static implicit operator string(JSONNode d)
  325. {
  326. return (d == null) ? null : d.Value;
  327. }
  328. public static implicit operator JSONNode(double n)
  329. {
  330. return new JSONNumber(n);
  331. }
  332. public static implicit operator double(JSONNode d)
  333. {
  334. return (d == null) ? 0 : d.AsDouble;
  335. }
  336. public static implicit operator JSONNode(float n)
  337. {
  338. return new JSONNumber(n);
  339. }
  340. public static implicit operator float(JSONNode d)
  341. {
  342. return (d == null) ? 0 : d.AsFloat;
  343. }
  344. public static implicit operator JSONNode(int n)
  345. {
  346. return new JSONNumber(n);
  347. }
  348. public static implicit operator int(JSONNode d)
  349. {
  350. return (d == null) ? 0 : d.AsInt;
  351. }
  352. public static implicit operator JSONNode(long n)
  353. {
  354. if (longAsString)
  355. return new JSONString(n.ToString());
  356. return new JSONNumber(n);
  357. }
  358. public static implicit operator long(JSONNode d)
  359. {
  360. return (d == null) ? 0L : d.AsLong;
  361. }
  362. public static implicit operator JSONNode(ulong n)
  363. {
  364. if (longAsString)
  365. return new JSONString(n.ToString());
  366. return new JSONNumber(n);
  367. }
  368. public static implicit operator ulong(JSONNode d)
  369. {
  370. return (d == null) ? 0 : d.AsULong;
  371. }
  372. public static implicit operator JSONNode(bool b)
  373. {
  374. return new JSONBool(b);
  375. }
  376. public static implicit operator bool(JSONNode d)
  377. {
  378. return (d == null) ? false : d.AsBool;
  379. }
  380. public static implicit operator JSONNode(KeyValuePair<string, JSONNode> aKeyValue)
  381. {
  382. return aKeyValue.Value;
  383. }
  384. public static bool operator ==(JSONNode a, object b)
  385. {
  386. if (ReferenceEquals(a, b))
  387. return true;
  388. bool aIsNull = a is JSONNull || ReferenceEquals(a, null) || a is JSONLazyCreator;
  389. bool bIsNull = b is JSONNull || ReferenceEquals(b, null) || b is JSONLazyCreator;
  390. if (aIsNull && bIsNull)
  391. return true;
  392. return !aIsNull && a.Equals(b);
  393. }
  394. public static bool operator !=(JSONNode a, object b)
  395. {
  396. return !(a == b);
  397. }
  398. public override bool Equals(object obj)
  399. {
  400. return ReferenceEquals(this, obj);
  401. }
  402. public override int GetHashCode()
  403. {
  404. return base.GetHashCode();
  405. }
  406. #endregion operators
  407. [ThreadStatic]
  408. private static StringBuilder m_EscapeBuilder;
  409. internal static StringBuilder EscapeBuilder
  410. {
  411. get
  412. {
  413. if (m_EscapeBuilder == null)
  414. m_EscapeBuilder = new StringBuilder();
  415. return m_EscapeBuilder;
  416. }
  417. }
  418. internal static string Escape(string aText)
  419. {
  420. var sb = EscapeBuilder;
  421. sb.Length = 0;
  422. if (sb.Capacity < aText.Length + aText.Length / 10)
  423. sb.Capacity = aText.Length + aText.Length / 10;
  424. foreach (char c in aText)
  425. {
  426. switch (c)
  427. {
  428. case '\\':
  429. sb.Append("\\\\");
  430. break;
  431. case '\"':
  432. sb.Append("\\\"");
  433. break;
  434. case '\n':
  435. sb.Append("\\n");
  436. break;
  437. case '\r':
  438. sb.Append("\\r");
  439. break;
  440. case '\t':
  441. sb.Append("\\t");
  442. break;
  443. case '\b':
  444. sb.Append("\\b");
  445. break;
  446. case '\f':
  447. sb.Append("\\f");
  448. break;
  449. default:
  450. if (c < ' ' || (forceASCII && c > 127))
  451. {
  452. ushort val = c;
  453. sb.Append("\\u").Append(val.ToString("X4"));
  454. }
  455. else
  456. sb.Append(c);
  457. break;
  458. }
  459. }
  460. string result = sb.ToString();
  461. sb.Length = 0;
  462. return result;
  463. }
  464. private static JSONNode ParseElement(string token, bool quoted)
  465. {
  466. if (quoted)
  467. return token;
  468. if (token.Length <= 5)
  469. {
  470. string tmp = token.ToLower();
  471. if (tmp == "false" || tmp == "true")
  472. return tmp == "true";
  473. if (tmp == "null")
  474. return JSONNull.CreateOrGet();
  475. }
  476. double val;
  477. if (double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out val))
  478. return val;
  479. else
  480. return token;
  481. }
  482. public static JSONNode Parse(string aJSON)
  483. {
  484. Stack<JSONNode> stack = new Stack<JSONNode>();
  485. JSONNode ctx = null;
  486. int i = 0;
  487. StringBuilder Token = new StringBuilder();
  488. string TokenName = "";
  489. bool QuoteMode = false;
  490. bool TokenIsQuoted = false;
  491. bool HasNewlineChar = false;
  492. while (i < aJSON.Length)
  493. {
  494. switch (aJSON[i])
  495. {
  496. case '{':
  497. if (QuoteMode)
  498. {
  499. Token.Append(aJSON[i]);
  500. break;
  501. }
  502. stack.Push(new JSONObject());
  503. if (ctx != null)
  504. {
  505. ctx.Add(TokenName, stack.Peek());
  506. }
  507. TokenName = "";
  508. Token.Length = 0;
  509. ctx = stack.Peek();
  510. HasNewlineChar = false;
  511. break;
  512. case '[':
  513. if (QuoteMode)
  514. {
  515. Token.Append(aJSON[i]);
  516. break;
  517. }
  518. stack.Push(new JSONArray());
  519. if (ctx != null)
  520. {
  521. ctx.Add(TokenName, stack.Peek());
  522. }
  523. TokenName = "";
  524. Token.Length = 0;
  525. ctx = stack.Peek();
  526. HasNewlineChar = false;
  527. break;
  528. case '}':
  529. case ']':
  530. if (QuoteMode)
  531. {
  532. Token.Append(aJSON[i]);
  533. break;
  534. }
  535. if (stack.Count == 0)
  536. throw new Exception("JSON Parse: Too many closing brackets");
  537. stack.Pop();
  538. if (Token.Length > 0 || TokenIsQuoted)
  539. ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
  540. if (ctx != null)
  541. ctx.Inline = !HasNewlineChar;
  542. TokenIsQuoted = false;
  543. TokenName = "";
  544. Token.Length = 0;
  545. if (stack.Count > 0)
  546. ctx = stack.Peek();
  547. break;
  548. case ':':
  549. if (QuoteMode)
  550. {
  551. Token.Append(aJSON[i]);
  552. break;
  553. }
  554. TokenName = Token.ToString();
  555. Token.Length = 0;
  556. TokenIsQuoted = false;
  557. break;
  558. case '"':
  559. QuoteMode ^= true;
  560. TokenIsQuoted |= QuoteMode;
  561. break;
  562. case ',':
  563. if (QuoteMode)
  564. {
  565. Token.Append(aJSON[i]);
  566. break;
  567. }
  568. if (Token.Length > 0 || TokenIsQuoted)
  569. ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
  570. TokenIsQuoted = false;
  571. TokenName = "";
  572. Token.Length = 0;
  573. TokenIsQuoted = false;
  574. break;
  575. case '\r':
  576. case '\n':
  577. HasNewlineChar = true;
  578. break;
  579. case ' ':
  580. case '\t':
  581. if (QuoteMode)
  582. Token.Append(aJSON[i]);
  583. break;
  584. case '\\':
  585. ++i;
  586. if (QuoteMode)
  587. {
  588. char C = aJSON[i];
  589. switch (C)
  590. {
  591. case 't':
  592. Token.Append('\t');
  593. break;
  594. case 'r':
  595. Token.Append('\r');
  596. break;
  597. case 'n':
  598. Token.Append('\n');
  599. break;
  600. case 'b':
  601. Token.Append('\b');
  602. break;
  603. case 'f':
  604. Token.Append('\f');
  605. break;
  606. case 'u':
  607. {
  608. string s = aJSON.Substring(i + 1, 4);
  609. Token.Append((char)int.Parse(
  610. s,
  611. System.Globalization.NumberStyles.AllowHexSpecifier));
  612. i += 4;
  613. break;
  614. }
  615. default:
  616. Token.Append(C);
  617. break;
  618. }
  619. }
  620. break;
  621. case '/':
  622. if (allowLineComments && !QuoteMode && i + 1 < aJSON.Length && aJSON[i + 1] == '/')
  623. {
  624. while (++i < aJSON.Length && aJSON[i] != '\n' && aJSON[i] != '\r') ;
  625. break;
  626. }
  627. Token.Append(aJSON[i]);
  628. break;
  629. case '\uFEFF': // remove / ignore BOM (Byte Order Mark)
  630. break;
  631. default:
  632. Token.Append(aJSON[i]);
  633. break;
  634. }
  635. ++i;
  636. }
  637. if (QuoteMode)
  638. {
  639. throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
  640. }
  641. if (ctx == null)
  642. return ParseElement(Token.ToString(), TokenIsQuoted);
  643. return ctx;
  644. }
  645. }
  646. // End of JSONNode
  647. public partial class JSONArray : JSONNode
  648. {
  649. private List<JSONNode> m_List = new List<JSONNode>();
  650. private bool inline = false;
  651. public override bool Inline
  652. {
  653. get { return inline; }
  654. set { inline = value; }
  655. }
  656. public override JSONNodeType Tag { get { return JSONNodeType.Array; } }
  657. public override bool IsArray { get { return true; } }
  658. public override Enumerator GetEnumerator() { return new Enumerator(m_List.GetEnumerator()); }
  659. public override JSONNode this[int aIndex]
  660. {
  661. get
  662. {
  663. if (aIndex < 0 || aIndex >= m_List.Count)
  664. return new JSONLazyCreator(this);
  665. return m_List[aIndex];
  666. }
  667. set
  668. {
  669. if (value == null)
  670. value = JSONNull.CreateOrGet();
  671. if (aIndex < 0 || aIndex >= m_List.Count)
  672. m_List.Add(value);
  673. else
  674. m_List[aIndex] = value;
  675. }
  676. }
  677. public override JSONNode this[string aKey]
  678. {
  679. get { return new JSONLazyCreator(this); }
  680. set
  681. {
  682. if (value == null)
  683. value = JSONNull.CreateOrGet();
  684. m_List.Add(value);
  685. }
  686. }
  687. public override int Count
  688. {
  689. get { return m_List.Count; }
  690. }
  691. public override void Add(string aKey, JSONNode aItem)
  692. {
  693. if (aItem == null)
  694. aItem = JSONNull.CreateOrGet();
  695. m_List.Add(aItem);
  696. }
  697. public override JSONNode Remove(int aIndex)
  698. {
  699. if (aIndex < 0 || aIndex >= m_List.Count)
  700. return null;
  701. JSONNode tmp = m_List[aIndex];
  702. m_List.RemoveAt(aIndex);
  703. return tmp;
  704. }
  705. public override JSONNode Remove(JSONNode aNode)
  706. {
  707. m_List.Remove(aNode);
  708. return aNode;
  709. }
  710. public override void Clear()
  711. {
  712. m_List.Clear();
  713. }
  714. public override JSONNode Clone()
  715. {
  716. var node = new JSONArray();
  717. node.m_List.Capacity = m_List.Capacity;
  718. foreach(var n in m_List)
  719. {
  720. if (n != null)
  721. node.Add(n.Clone());
  722. else
  723. node.Add(null);
  724. }
  725. return node;
  726. }
  727. public override IEnumerable<JSONNode> Children
  728. {
  729. get
  730. {
  731. foreach (JSONNode N in m_List)
  732. yield return N;
  733. }
  734. }
  735. internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
  736. {
  737. aSB.Append('[');
  738. int count = m_List.Count;
  739. if (inline)
  740. aMode = JSONTextMode.Compact;
  741. for (int i = 0; i < count; i++)
  742. {
  743. if (i > 0)
  744. aSB.Append(',');
  745. if (aMode == JSONTextMode.Indent)
  746. aSB.AppendLine();
  747. if (aMode == JSONTextMode.Indent)
  748. aSB.Append(' ', aIndent + aIndentInc);
  749. m_List[i].WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode);
  750. }
  751. if (aMode == JSONTextMode.Indent)
  752. aSB.AppendLine().Append(' ', aIndent);
  753. aSB.Append(']');
  754. }
  755. }
  756. // End of JSONArray
  757. public partial class JSONObject : JSONNode
  758. {
  759. private Dictionary<string, JSONNode> m_Dict = new Dictionary<string, JSONNode>();
  760. private bool inline = false;
  761. public override bool Inline
  762. {
  763. get { return inline; }
  764. set { inline = value; }
  765. }
  766. public override JSONNodeType Tag { get { return JSONNodeType.Object; } }
  767. public override bool IsObject { get { return true; } }
  768. public override Enumerator GetEnumerator() { return new Enumerator(m_Dict.GetEnumerator()); }
  769. public override JSONNode this[string aKey]
  770. {
  771. get
  772. {
  773. if (m_Dict.ContainsKey(aKey))
  774. return m_Dict[aKey];
  775. else
  776. return new JSONLazyCreator(this, aKey);
  777. }
  778. set
  779. {
  780. if (value == null)
  781. value = JSONNull.CreateOrGet();
  782. if (m_Dict.ContainsKey(aKey))
  783. m_Dict[aKey] = value;
  784. else
  785. m_Dict.Add(aKey, value);
  786. }
  787. }
  788. public override JSONNode this[int aIndex]
  789. {
  790. get
  791. {
  792. if (aIndex < 0 || aIndex >= m_Dict.Count)
  793. return null;
  794. return m_Dict.ElementAt(aIndex).Value;
  795. }
  796. set
  797. {
  798. if (value == null)
  799. value = JSONNull.CreateOrGet();
  800. if (aIndex < 0 || aIndex >= m_Dict.Count)
  801. return;
  802. string key = m_Dict.ElementAt(aIndex).Key;
  803. m_Dict[key] = value;
  804. }
  805. }
  806. public override int Count
  807. {
  808. get { return m_Dict.Count; }
  809. }
  810. public override void Add(string aKey, JSONNode aItem)
  811. {
  812. if (aItem == null)
  813. aItem = JSONNull.CreateOrGet();
  814. if (aKey != null)
  815. {
  816. if (m_Dict.ContainsKey(aKey))
  817. m_Dict[aKey] = aItem;
  818. else
  819. m_Dict.Add(aKey, aItem);
  820. }
  821. else
  822. m_Dict.Add(Guid.NewGuid().ToString(), aItem);
  823. }
  824. public override JSONNode Remove(string aKey)
  825. {
  826. if (!m_Dict.ContainsKey(aKey))
  827. return null;
  828. JSONNode tmp = m_Dict[aKey];
  829. m_Dict.Remove(aKey);
  830. return tmp;
  831. }
  832. public override JSONNode Remove(int aIndex)
  833. {
  834. if (aIndex < 0 || aIndex >= m_Dict.Count)
  835. return null;
  836. var item = m_Dict.ElementAt(aIndex);
  837. m_Dict.Remove(item.Key);
  838. return item.Value;
  839. }
  840. public override JSONNode Remove(JSONNode aNode)
  841. {
  842. try
  843. {
  844. var item = m_Dict.Where(k => k.Value == aNode).First();
  845. m_Dict.Remove(item.Key);
  846. return aNode;
  847. }
  848. catch
  849. {
  850. return null;
  851. }
  852. }
  853. public override void Clear()
  854. {
  855. m_Dict.Clear();
  856. }
  857. public override JSONNode Clone()
  858. {
  859. var node = new JSONObject();
  860. foreach (var n in m_Dict)
  861. {
  862. node.Add(n.Key, n.Value.Clone());
  863. }
  864. return node;
  865. }
  866. public override bool HasKey(string aKey)
  867. {
  868. return m_Dict.ContainsKey(aKey);
  869. }
  870. public override JSONNode GetValueOrDefault(string aKey, JSONNode aDefault)
  871. {
  872. JSONNode res;
  873. if (m_Dict.TryGetValue(aKey, out res))
  874. return res;
  875. return aDefault;
  876. }
  877. public override IEnumerable<JSONNode> Children
  878. {
  879. get
  880. {
  881. foreach (KeyValuePair<string, JSONNode> N in m_Dict)
  882. yield return N.Value;
  883. }
  884. }
  885. internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
  886. {
  887. aSB.Append('{');
  888. bool first = true;
  889. if (inline)
  890. aMode = JSONTextMode.Compact;
  891. foreach (var k in m_Dict)
  892. {
  893. if (!first)
  894. aSB.Append(',');
  895. first = false;
  896. if (aMode == JSONTextMode.Indent)
  897. aSB.AppendLine();
  898. if (aMode == JSONTextMode.Indent)
  899. aSB.Append(' ', aIndent + aIndentInc);
  900. aSB.Append('\"').Append(Escape(k.Key)).Append('\"');
  901. if (aMode == JSONTextMode.Compact)
  902. aSB.Append(':');
  903. else
  904. aSB.Append(" : ");
  905. k.Value.WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode);
  906. }
  907. if (aMode == JSONTextMode.Indent)
  908. aSB.AppendLine().Append(' ', aIndent);
  909. aSB.Append('}');
  910. }
  911. }
  912. // End of JSONObject
  913. public partial class JSONString : JSONNode
  914. {
  915. private string m_Data;
  916. public override JSONNodeType Tag { get { return JSONNodeType.String; } }
  917. public override bool IsString { get { return true; } }
  918. public override Enumerator GetEnumerator() { return new Enumerator(); }
  919. public override string Value
  920. {
  921. get { return m_Data; }
  922. set
  923. {
  924. m_Data = value;
  925. }
  926. }
  927. public JSONString(string aData)
  928. {
  929. m_Data = aData;
  930. }
  931. public override JSONNode Clone()
  932. {
  933. return new JSONString(m_Data);
  934. }
  935. internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
  936. {
  937. aSB.Append('\"').Append(Escape(m_Data)).Append('\"');
  938. }
  939. public override bool Equals(object obj)
  940. {
  941. if (base.Equals(obj))
  942. return true;
  943. string s = obj as string;
  944. if (s != null)
  945. return m_Data == s;
  946. JSONString s2 = obj as JSONString;
  947. if (s2 != null)
  948. return m_Data == s2.m_Data;
  949. return false;
  950. }
  951. public override int GetHashCode()
  952. {
  953. return m_Data.GetHashCode();
  954. }
  955. public override void Clear()
  956. {
  957. m_Data = "";
  958. }
  959. }
  960. // End of JSONString
  961. public partial class JSONNumber : JSONNode
  962. {
  963. private double m_Data;
  964. public override JSONNodeType Tag { get { return JSONNodeType.Number; } }
  965. public override bool IsNumber { get { return true; } }
  966. public override Enumerator GetEnumerator() { return new Enumerator(); }
  967. public override string Value
  968. {
  969. get { return m_Data.ToString(CultureInfo.InvariantCulture); }
  970. set
  971. {
  972. double v;
  973. if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out v))
  974. m_Data = v;
  975. }
  976. }
  977. public override double AsDouble
  978. {
  979. get { return m_Data; }
  980. set { m_Data = value; }
  981. }
  982. public override long AsLong
  983. {
  984. get { return (long)m_Data; }
  985. set { m_Data = value; }
  986. }
  987. public override ulong AsULong
  988. {
  989. get { return (ulong)m_Data; }
  990. set { m_Data = value; }
  991. }
  992. public JSONNumber(double aData)
  993. {
  994. m_Data = aData;
  995. }
  996. public JSONNumber(string aData)
  997. {
  998. Value = aData;
  999. }
  1000. public override JSONNode Clone()
  1001. {
  1002. return new JSONNumber(m_Data);
  1003. }
  1004. internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
  1005. {
  1006. aSB.Append(Value);
  1007. }
  1008. private static bool IsNumeric(object value)
  1009. {
  1010. return value is int || value is uint
  1011. || value is float || value is double
  1012. || value is decimal
  1013. || value is long || value is ulong
  1014. || value is short || value is ushort
  1015. || value is sbyte || value is byte;
  1016. }
  1017. public override bool Equals(object obj)
  1018. {
  1019. if (obj == null)
  1020. return false;
  1021. if (base.Equals(obj))
  1022. return true;
  1023. JSONNumber s2 = obj as JSONNumber;
  1024. if (s2 != null)
  1025. return m_Data == s2.m_Data;
  1026. if (IsNumeric(obj))
  1027. return Convert.ToDouble(obj) == m_Data;
  1028. return false;
  1029. }
  1030. public override int GetHashCode()
  1031. {
  1032. return m_Data.GetHashCode();
  1033. }
  1034. public override void Clear()
  1035. {
  1036. m_Data = 0;
  1037. }
  1038. }
  1039. // End of JSONNumber
  1040. public partial class JSONBool : JSONNode
  1041. {
  1042. private bool m_Data;
  1043. public override JSONNodeType Tag { get { return JSONNodeType.Boolean; } }
  1044. public override bool IsBoolean { get { return true; } }
  1045. public override Enumerator GetEnumerator() { return new Enumerator(); }
  1046. public override string Value
  1047. {
  1048. get { return m_Data.ToString(); }
  1049. set
  1050. {
  1051. bool v;
  1052. if (bool.TryParse(value, out v))
  1053. m_Data = v;
  1054. }
  1055. }
  1056. public override bool AsBool
  1057. {
  1058. get { return m_Data; }
  1059. set { m_Data = value; }
  1060. }
  1061. public JSONBool(bool aData)
  1062. {
  1063. m_Data = aData;
  1064. }
  1065. public JSONBool(string aData)
  1066. {
  1067. Value = aData;
  1068. }
  1069. public override JSONNode Clone()
  1070. {
  1071. return new JSONBool(m_Data);
  1072. }
  1073. internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
  1074. {
  1075. aSB.Append((m_Data) ? "true" : "false");
  1076. }
  1077. public override bool Equals(object obj)
  1078. {
  1079. if (obj == null)
  1080. return false;
  1081. if (obj is bool)
  1082. return m_Data == (bool)obj;
  1083. return false;
  1084. }
  1085. public override int GetHashCode()
  1086. {
  1087. return m_Data.GetHashCode();
  1088. }
  1089. public override void Clear()
  1090. {
  1091. m_Data = false;
  1092. }
  1093. }
  1094. // End of JSONBool
  1095. public partial class JSONNull : JSONNode
  1096. {
  1097. static JSONNull m_StaticInstance = new JSONNull();
  1098. public static bool reuseSameInstance = true;
  1099. public static JSONNull CreateOrGet()
  1100. {
  1101. if (reuseSameInstance)
  1102. return m_StaticInstance;
  1103. return new JSONNull();
  1104. }
  1105. private JSONNull() { }
  1106. public override JSONNodeType Tag { get { return JSONNodeType.NullValue; } }
  1107. public override bool IsNull { get { return true; } }
  1108. public override Enumerator GetEnumerator() { return new Enumerator(); }
  1109. public override string Value
  1110. {
  1111. get { return "null"; }
  1112. set { }
  1113. }
  1114. public override bool AsBool
  1115. {
  1116. get { return false; }
  1117. set { }
  1118. }
  1119. public override JSONNode Clone()
  1120. {
  1121. return CreateOrGet();
  1122. }
  1123. public override bool Equals(object obj)
  1124. {
  1125. if (object.ReferenceEquals(this, obj))
  1126. return true;
  1127. return (obj is JSONNull);
  1128. }
  1129. public override int GetHashCode()
  1130. {
  1131. return 0;
  1132. }
  1133. internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
  1134. {
  1135. aSB.Append("null");
  1136. }
  1137. }
  1138. // End of JSONNull
  1139. internal partial class JSONLazyCreator : JSONNode
  1140. {
  1141. private JSONNode m_Node = null;
  1142. private string m_Key = null;
  1143. public override JSONNodeType Tag { get { return JSONNodeType.None; } }
  1144. public override Enumerator GetEnumerator() { return new Enumerator(); }
  1145. public JSONLazyCreator(JSONNode aNode)
  1146. {
  1147. m_Node = aNode;
  1148. m_Key = null;
  1149. }
  1150. public JSONLazyCreator(JSONNode aNode, string aKey)
  1151. {
  1152. m_Node = aNode;
  1153. m_Key = aKey;
  1154. }
  1155. private T Set<T>(T aVal) where T : JSONNode
  1156. {
  1157. if (m_Key == null)
  1158. m_Node.Add(aVal);
  1159. else
  1160. m_Node.Add(m_Key, aVal);
  1161. m_Node = null; // Be GC friendly.
  1162. return aVal;
  1163. }
  1164. public override JSONNode this[int aIndex]
  1165. {
  1166. get { return new JSONLazyCreator(this); }
  1167. set { Set(new JSONArray()).Add(value); }
  1168. }
  1169. public override JSONNode this[string aKey]
  1170. {
  1171. get { return new JSONLazyCreator(this, aKey); }
  1172. set { Set(new JSONObject()).Add(aKey, value); }
  1173. }
  1174. public override void Add(JSONNode aItem)
  1175. {
  1176. Set(new JSONArray()).Add(aItem);
  1177. }
  1178. public override void Add(string aKey, JSONNode aItem)
  1179. {
  1180. Set(new JSONObject()).Add(aKey, aItem);
  1181. }
  1182. public static bool operator ==(JSONLazyCreator a, object b)
  1183. {
  1184. if (b == null)
  1185. return true;
  1186. return System.Object.ReferenceEquals(a, b);
  1187. }
  1188. public static bool operator !=(JSONLazyCreator a, object b)
  1189. {
  1190. return !(a == b);
  1191. }
  1192. public override bool Equals(object obj)
  1193. {
  1194. if (obj == null)
  1195. return true;
  1196. return System.Object.ReferenceEquals(this, obj);
  1197. }
  1198. public override int GetHashCode()
  1199. {
  1200. return 0;
  1201. }
  1202. public override int AsInt
  1203. {
  1204. get { Set(new JSONNumber(0)); return 0; }
  1205. set { Set(new JSONNumber(value)); }
  1206. }
  1207. public override float AsFloat
  1208. {
  1209. get { Set(new JSONNumber(0.0f)); return 0.0f; }
  1210. set { Set(new JSONNumber(value)); }
  1211. }
  1212. public override double AsDouble
  1213. {
  1214. get { Set(new JSONNumber(0.0)); return 0.0; }
  1215. set { Set(new JSONNumber(value)); }
  1216. }
  1217. public override long AsLong
  1218. {
  1219. get
  1220. {
  1221. if (longAsString)
  1222. Set(new JSONString("0"));
  1223. else
  1224. Set(new JSONNumber(0.0));
  1225. return 0L;
  1226. }
  1227. set
  1228. {
  1229. if (longAsString)
  1230. Set(new JSONString(value.ToString()));
  1231. else
  1232. Set(new JSONNumber(value));
  1233. }
  1234. }
  1235. public override ulong AsULong
  1236. {
  1237. get
  1238. {
  1239. if (longAsString)
  1240. Set(new JSONString("0"));
  1241. else
  1242. Set(new JSONNumber(0.0));
  1243. return 0L;
  1244. }
  1245. set
  1246. {
  1247. if (longAsString)
  1248. Set(new JSONString(value.ToString()));
  1249. else
  1250. Set(new JSONNumber(value));
  1251. }
  1252. }
  1253. public override bool AsBool
  1254. {
  1255. get { Set(new JSONBool(false)); return false; }
  1256. set { Set(new JSONBool(value)); }
  1257. }
  1258. public override JSONArray AsArray
  1259. {
  1260. get { return Set(new JSONArray()); }
  1261. }
  1262. public override JSONObject AsObject
  1263. {
  1264. get { return Set(new JSONObject()); }
  1265. }
  1266. internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
  1267. {
  1268. aSB.Append("null");
  1269. }
  1270. }
  1271. // End of JSONLazyCreator
  1272. public static class JSON
  1273. {
  1274. public static JSONNode Parse(string aJSON)
  1275. {
  1276. return JSONNode.Parse(aJSON);
  1277. }
  1278. }
  1279. }