QuickSDKJSON.cs 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. //#define USE_SharpZipLib
  2. #if !UNITY_WEBPLAYER
  3. #define USE_FileIO
  4. #endif
  5. /* * * * *
  6. * A simple JSON Parser / builder
  7. * ------------------------------
  8. *
  9. * It mainly has been written as a simple JSON parser. It can build a JSON string
  10. * from the node-tree, or generate a node tree from any valid JSON string.
  11. *
  12. * If you want to use compression when saving to file / stream / B64 you have to include
  13. * SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and
  14. * define "USE_SharpZipLib" at the top of the file
  15. *
  16. * Written by Bunny83
  17. * 2012-06-09
  18. *
  19. * Features / attributes:
  20. * - provides strongly typed node classes and lists / dictionaries
  21. * - provides easy access to class members / array items / data values
  22. * - the parser ignores data types. Each value is a string.
  23. * - only double quotes (") are used for quoting strings.
  24. * - values and names are not restricted to quoted strings. They simply add up and are trimmed.
  25. * - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData)
  26. * - provides "casting" properties to easily convert to / from those types:
  27. * int / float / double / bool
  28. * - provides a common interface for each node so no explicit casting is required.
  29. * - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined
  30. *
  31. *
  32. * 2012-12-17 Update:
  33. * - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree
  34. * Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator
  35. * The class determines the required type by it's further use, creates the type and removes itself.
  36. * - Added binary serialization / deserialization.
  37. * - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ )
  38. * The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top
  39. * - The serializer uses different types when it comes to store the values. Since my data values
  40. * are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string.
  41. * It's not the most efficient way but for a moderate amount of data it should work on all platforms.
  42. *
  43. * * * * */
  44. using System;
  45. using System.Collections;
  46. using System.Collections.Generic;
  47. using System.Linq;
  48. namespace quicksdk
  49. {
  50. namespace SimpleJSON
  51. {
  52. public enum JSONBinaryTag
  53. {
  54. Array = 1,
  55. Class = 2,
  56. Value = 3,
  57. IntValue = 4,
  58. DoubleValue = 5,
  59. BoolValue = 6,
  60. FloatValue = 7,
  61. }
  62. public class JSONNode
  63. {
  64. #region common interface
  65. public virtual void Add (string aKey, JSONNode aItem)
  66. {
  67. }
  68. public virtual JSONNode this [int aIndex] { get { return null; } set { }
  69. }
  70. public virtual JSONNode this [string aKey] { get { return null; } set { }
  71. }
  72. public virtual string Value {
  73. get { return ""; }
  74. set { }
  75. }
  76. public virtual int Count { get { return 0; } }
  77. public virtual void Add (JSONNode aItem)
  78. {
  79. Add ("", aItem);
  80. }
  81. public virtual JSONNode Remove (string aKey)
  82. {
  83. return null;
  84. }
  85. public virtual JSONNode Remove (int aIndex)
  86. {
  87. return null;
  88. }
  89. public virtual JSONNode Remove (JSONNode aNode)
  90. {
  91. return aNode;
  92. }
  93. public virtual IEnumerable<JSONNode> Childs { get { yield break; } }
  94. public IEnumerable<JSONNode> DeepChilds {
  95. get {
  96. foreach (var C in Childs)
  97. foreach (var D in C.DeepChilds)
  98. yield return D;
  99. }
  100. }
  101. public override string ToString ()
  102. {
  103. return "JSONNode";
  104. }
  105. public virtual string ToString (string aPrefix)
  106. {
  107. return "JSONNode";
  108. }
  109. #endregion common interface
  110. #region typecasting properties
  111. public virtual int AsInt {
  112. get {
  113. int v = 0;
  114. if (int.TryParse (Value, out v))
  115. return v;
  116. return 0;
  117. }
  118. set {
  119. Value = value.ToString ();
  120. }
  121. }
  122. public virtual float AsFloat {
  123. get {
  124. float v = 0.0f;
  125. if (float.TryParse (Value, out v))
  126. return v;
  127. return 0.0f;
  128. }
  129. set {
  130. Value = value.ToString ();
  131. }
  132. }
  133. public virtual double AsDouble {
  134. get {
  135. double v = 0.0;
  136. if (double.TryParse (Value, out v))
  137. return v;
  138. return 0.0;
  139. }
  140. set {
  141. Value = value.ToString ();
  142. }
  143. }
  144. public virtual bool AsBool {
  145. get {
  146. bool v = false;
  147. if (bool.TryParse (Value, out v))
  148. return v;
  149. return !string.IsNullOrEmpty (Value);
  150. }
  151. set {
  152. Value = (value) ? "true" : "false";
  153. }
  154. }
  155. public virtual JSONArray AsArray {
  156. get {
  157. return this as JSONArray;
  158. }
  159. }
  160. public virtual JSONClass AsObject {
  161. get {
  162. return this as JSONClass;
  163. }
  164. }
  165. #endregion typecasting properties
  166. #region operators
  167. public static implicit operator JSONNode (string s)
  168. {
  169. return new JSONData (s);
  170. }
  171. public static implicit operator string (JSONNode d)
  172. {
  173. return (d == null) ? null : d.Value;
  174. }
  175. public static bool operator == (JSONNode a, object b)
  176. {
  177. if (b == null && a is JSONLazyCreator)
  178. return true;
  179. return System.Object.ReferenceEquals (a, b);
  180. }
  181. public static bool operator != (JSONNode a, object b)
  182. {
  183. return !(a == b);
  184. }
  185. public override bool Equals (object obj)
  186. {
  187. return System.Object.ReferenceEquals (this, obj);
  188. }
  189. public override int GetHashCode ()
  190. {
  191. return base.GetHashCode ();
  192. }
  193. #endregion operators
  194. internal static string Escape (string aText)
  195. {
  196. string result = "";
  197. foreach (char c in aText) {
  198. switch (c) {
  199. case '\\':
  200. result += "\\\\";
  201. break;
  202. case '\"':
  203. result += "\\\"";
  204. break;
  205. case '\n':
  206. result += "\\n";
  207. break;
  208. case '\r':
  209. result += "\\r";
  210. break;
  211. case '\t':
  212. result += "\\t";
  213. break;
  214. case '\b':
  215. result += "\\b";
  216. break;
  217. case '\f':
  218. result += "\\f";
  219. break;
  220. default :
  221. result += c;
  222. break;
  223. }
  224. }
  225. return result;
  226. }
  227. public static JSONNode Parse (string aJSON)
  228. {
  229. Stack<JSONNode> stack = new Stack<JSONNode> ();
  230. JSONNode ctx = null;
  231. int i = 0;
  232. string Token = "";
  233. string TokenName = "";
  234. bool QuoteMode = false;
  235. while (i < aJSON.Length) {
  236. switch (aJSON [i]) {
  237. case '{':
  238. if (QuoteMode) {
  239. Token += aJSON [i];
  240. break;
  241. }
  242. stack.Push (new JSONClass ());
  243. if (ctx != null) {
  244. TokenName = TokenName.Trim ();
  245. if (ctx is JSONArray)
  246. ctx.Add (stack.Peek ());
  247. else if (TokenName != "")
  248. ctx.Add (TokenName, stack.Peek ());
  249. }
  250. TokenName = "";
  251. Token = "";
  252. ctx = stack.Peek ();
  253. break;
  254. case '[':
  255. if (QuoteMode) {
  256. Token += aJSON [i];
  257. break;
  258. }
  259. stack.Push (new JSONArray ());
  260. if (ctx != null) {
  261. TokenName = TokenName.Trim ();
  262. if (ctx is JSONArray)
  263. ctx.Add (stack.Peek ());
  264. else if (TokenName != "")
  265. ctx.Add (TokenName, stack.Peek ());
  266. }
  267. TokenName = "";
  268. Token = "";
  269. ctx = stack.Peek ();
  270. break;
  271. case '}':
  272. case ']':
  273. if (QuoteMode) {
  274. Token += aJSON [i];
  275. break;
  276. }
  277. if (stack.Count == 0)
  278. throw new Exception ("JSON Parse: Too many closing brackets");
  279. stack.Pop ();
  280. if (Token != "") {
  281. TokenName = TokenName.Trim ();
  282. if (ctx is JSONArray)
  283. ctx.Add (Token);
  284. else if (TokenName != "")
  285. ctx.Add (TokenName, Token);
  286. }
  287. TokenName = "";
  288. Token = "";
  289. if (stack.Count > 0)
  290. ctx = stack.Peek ();
  291. break;
  292. case ':':
  293. if (QuoteMode) {
  294. Token += aJSON [i];
  295. break;
  296. }
  297. TokenName = Token;
  298. Token = "";
  299. break;
  300. case '"':
  301. QuoteMode ^= true;
  302. break;
  303. case ',':
  304. if (QuoteMode) {
  305. Token += aJSON [i];
  306. break;
  307. }
  308. if (Token != "") {
  309. if (ctx is JSONArray)
  310. ctx.Add (Token);
  311. else if (TokenName != "")
  312. ctx.Add (TokenName, Token);
  313. }
  314. TokenName = "";
  315. Token = "";
  316. break;
  317. case '\r':
  318. case '\n':
  319. break;
  320. case ' ':
  321. case '\t':
  322. if (QuoteMode)
  323. Token += aJSON [i];
  324. break;
  325. case '\\':
  326. ++i;
  327. if (QuoteMode) {
  328. char C = aJSON [i];
  329. switch (C) {
  330. case 't':
  331. Token += '\t';
  332. break;
  333. case 'r':
  334. Token += '\r';
  335. break;
  336. case 'n':
  337. Token += '\n';
  338. break;
  339. case 'b':
  340. Token += '\b';
  341. break;
  342. case 'f':
  343. Token += '\f';
  344. break;
  345. case 'u':
  346. {
  347. string s = aJSON.Substring (i + 1, 4);
  348. Token += (char)int.Parse (s, System.Globalization.NumberStyles.AllowHexSpecifier);
  349. i += 4;
  350. break;
  351. }
  352. default :
  353. Token += C;
  354. break;
  355. }
  356. }
  357. break;
  358. default:
  359. Token += aJSON [i];
  360. break;
  361. }
  362. ++i;
  363. }
  364. if (QuoteMode) {
  365. throw new Exception ("JSON Parse: Quotation marks seems to be messed up.");
  366. }
  367. return ctx;
  368. }
  369. public virtual void Serialize (System.IO.BinaryWriter aWriter)
  370. {
  371. }
  372. public void SaveToStream (System.IO.Stream aData)
  373. {
  374. var W = new System.IO.BinaryWriter (aData);
  375. Serialize (W);
  376. }
  377. #if USE_SharpZipLib
  378. public void SaveToCompressedStream(System.IO.Stream aData)
  379. {
  380. using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
  381. {
  382. gzipOut.IsStreamOwner = false;
  383. SaveToStream(gzipOut);
  384. gzipOut.Close();
  385. }
  386. }
  387. public void SaveToCompressedFile(string aFileName)
  388. {
  389. #if USE_FileIO
  390. System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
  391. using(var F = System.IO.File.OpenWrite(aFileName))
  392. {
  393. SaveToCompressedStream(F);
  394. }
  395. #else
  396. throw new Exception("Can't use File IO stuff in webplayer");
  397. #endif
  398. }
  399. public string SaveToCompressedBase64()
  400. {
  401. using (var stream = new System.IO.MemoryStream())
  402. {
  403. SaveToCompressedStream(stream);
  404. stream.Position = 0;
  405. return System.Convert.ToBase64String(stream.ToArray());
  406. }
  407. }
  408. #else
  409. public void SaveToCompressedStream (System.IO.Stream aData)
  410. {
  411. throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
  412. }
  413. public void SaveToCompressedFile (string aFileName)
  414. {
  415. throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
  416. }
  417. public string SaveToCompressedBase64 ()
  418. {
  419. throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
  420. }
  421. #endif
  422. public void SaveToFile (string aFileName)
  423. {
  424. #if USE_FileIO
  425. System.IO.Directory.CreateDirectory ((new System.IO.FileInfo (aFileName)).Directory.FullName);
  426. using (var F = System.IO.File.OpenWrite(aFileName)) {
  427. SaveToStream (F);
  428. }
  429. #else
  430. throw new Exception("Can't use File IO stuff in webplayer");
  431. #endif
  432. }
  433. public string SaveToBase64 ()
  434. {
  435. using (var stream = new System.IO.MemoryStream()) {
  436. SaveToStream (stream);
  437. stream.Position = 0;
  438. return System.Convert.ToBase64String (stream.ToArray ());
  439. }
  440. }
  441. public static JSONNode Deserialize (System.IO.BinaryReader aReader)
  442. {
  443. JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte ();
  444. switch (type) {
  445. case JSONBinaryTag.Array:
  446. {
  447. int count = aReader.ReadInt32 ();
  448. JSONArray tmp = new JSONArray ();
  449. for (int i = 0; i < count; i++)
  450. tmp.Add (Deserialize (aReader));
  451. return tmp;
  452. }
  453. case JSONBinaryTag.Class:
  454. {
  455. int count = aReader.ReadInt32 ();
  456. JSONClass tmp = new JSONClass ();
  457. for (int i = 0; i < count; i++) {
  458. string key = aReader.ReadString ();
  459. var val = Deserialize (aReader);
  460. tmp.Add (key, val);
  461. }
  462. return tmp;
  463. }
  464. case JSONBinaryTag.Value:
  465. {
  466. return new JSONData (aReader.ReadString ());
  467. }
  468. case JSONBinaryTag.IntValue:
  469. {
  470. return new JSONData (aReader.ReadInt32 ());
  471. }
  472. case JSONBinaryTag.DoubleValue:
  473. {
  474. return new JSONData (aReader.ReadDouble ());
  475. }
  476. case JSONBinaryTag.BoolValue:
  477. {
  478. return new JSONData (aReader.ReadBoolean ());
  479. }
  480. case JSONBinaryTag.FloatValue:
  481. {
  482. return new JSONData (aReader.ReadSingle ());
  483. }
  484. default:
  485. {
  486. throw new Exception ("Error deserializing JSON. Unknown tag: " + type);
  487. }
  488. }
  489. }
  490. #if USE_SharpZipLib
  491. public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
  492. {
  493. var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
  494. return LoadFromStream(zin);
  495. }
  496. public static JSONNode LoadFromCompressedFile(string aFileName)
  497. {
  498. #if USE_FileIO
  499. using(var F = System.IO.File.OpenRead(aFileName))
  500. {
  501. return LoadFromCompressedStream(F);
  502. }
  503. #else
  504. throw new Exception("Can't use File IO stuff in webplayer");
  505. #endif
  506. }
  507. public static JSONNode LoadFromCompressedBase64(string aBase64)
  508. {
  509. var tmp = System.Convert.FromBase64String(aBase64);
  510. var stream = new System.IO.MemoryStream(tmp);
  511. stream.Position = 0;
  512. return LoadFromCompressedStream(stream);
  513. }
  514. #else
  515. public static JSONNode LoadFromCompressedFile (string aFileName)
  516. {
  517. throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
  518. }
  519. public static JSONNode LoadFromCompressedStream (System.IO.Stream aData)
  520. {
  521. throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
  522. }
  523. public static JSONNode LoadFromCompressedBase64 (string aBase64)
  524. {
  525. throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
  526. }
  527. #endif
  528. public static JSONNode LoadFromStream (System.IO.Stream aData)
  529. {
  530. using (var R = new System.IO.BinaryReader(aData)) {
  531. return Deserialize (R);
  532. }
  533. }
  534. public static JSONNode LoadFromFile (string aFileName)
  535. {
  536. #if USE_FileIO
  537. using (var F = System.IO.File.OpenRead(aFileName)) {
  538. return LoadFromStream (F);
  539. }
  540. #else
  541. throw new Exception("Can't use File IO stuff in webplayer");
  542. #endif
  543. }
  544. public static JSONNode LoadFromBase64 (string aBase64)
  545. {
  546. var tmp = System.Convert.FromBase64String (aBase64);
  547. var stream = new System.IO.MemoryStream (tmp);
  548. stream.Position = 0;
  549. return LoadFromStream (stream);
  550. }
  551. } // End of JSONNode
  552. public class JSONArray : JSONNode, IEnumerable
  553. {
  554. private List<JSONNode> m_List = new List<JSONNode> ();
  555. public override JSONNode this [int aIndex] {
  556. get {
  557. if (aIndex < 0 || aIndex >= m_List.Count)
  558. return new JSONLazyCreator (this);
  559. return m_List [aIndex];
  560. }
  561. set {
  562. if (aIndex < 0 || aIndex >= m_List.Count)
  563. m_List.Add (value);
  564. else
  565. m_List [aIndex] = value;
  566. }
  567. }
  568. public override JSONNode this [string aKey] {
  569. get{ return new JSONLazyCreator (this);}
  570. set{ m_List.Add (value); }
  571. }
  572. public override int Count {
  573. get { return m_List.Count; }
  574. }
  575. public override void Add (string aKey, JSONNode aItem)
  576. {
  577. m_List.Add (aItem);
  578. }
  579. public override JSONNode Remove (int aIndex)
  580. {
  581. if (aIndex < 0 || aIndex >= m_List.Count)
  582. return null;
  583. JSONNode tmp = m_List [aIndex];
  584. m_List.RemoveAt (aIndex);
  585. return tmp;
  586. }
  587. public override JSONNode Remove (JSONNode aNode)
  588. {
  589. m_List.Remove (aNode);
  590. return aNode;
  591. }
  592. public override IEnumerable<JSONNode> Childs {
  593. get {
  594. foreach (JSONNode N in m_List)
  595. yield return N;
  596. }
  597. }
  598. public IEnumerator GetEnumerator ()
  599. {
  600. foreach (JSONNode N in m_List)
  601. yield return N;
  602. }
  603. public override string ToString ()
  604. {
  605. string result = "[ ";
  606. foreach (JSONNode N in m_List) {
  607. if (result.Length > 2)
  608. result += ", ";
  609. result += N.ToString ();
  610. }
  611. result += " ]";
  612. return result;
  613. }
  614. public override string ToString (string aPrefix)
  615. {
  616. string result = "[ ";
  617. foreach (JSONNode N in m_List) {
  618. if (result.Length > 3)
  619. result += ", ";
  620. result += "\n" + aPrefix + " ";
  621. result += N.ToString (aPrefix + " ");
  622. }
  623. result += "\n" + aPrefix + "]";
  624. return result;
  625. }
  626. public override void Serialize (System.IO.BinaryWriter aWriter)
  627. {
  628. aWriter.Write ((byte)JSONBinaryTag.Array);
  629. aWriter.Write (m_List.Count);
  630. for (int i = 0; i < m_List.Count; i++) {
  631. m_List [i].Serialize (aWriter);
  632. }
  633. }
  634. } // End of JSONArray
  635. public class JSONClass : JSONNode, IEnumerable
  636. {
  637. private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode> ();
  638. public override JSONNode this [string aKey] {
  639. get {
  640. if (m_Dict.ContainsKey (aKey))
  641. return m_Dict [aKey];
  642. else
  643. return new JSONLazyCreator (this, aKey);
  644. }
  645. set {
  646. if (m_Dict.ContainsKey (aKey))
  647. m_Dict [aKey] = value;
  648. else
  649. m_Dict.Add (aKey, value);
  650. }
  651. }
  652. public override JSONNode this [int aIndex] {
  653. get {
  654. if (aIndex < 0 || aIndex >= m_Dict.Count)
  655. return null;
  656. return m_Dict.ElementAt (aIndex).Value;
  657. }
  658. set {
  659. if (aIndex < 0 || aIndex >= m_Dict.Count)
  660. return;
  661. string key = m_Dict.ElementAt (aIndex).Key;
  662. m_Dict [key] = value;
  663. }
  664. }
  665. public override int Count {
  666. get { return m_Dict.Count; }
  667. }
  668. public override void Add (string aKey, JSONNode aItem)
  669. {
  670. if (!string.IsNullOrEmpty (aKey)) {
  671. if (m_Dict.ContainsKey (aKey))
  672. m_Dict [aKey] = aItem;
  673. else
  674. m_Dict.Add (aKey, aItem);
  675. } else
  676. m_Dict.Add (Guid.NewGuid ().ToString (), aItem);
  677. }
  678. public override JSONNode Remove (string aKey)
  679. {
  680. if (!m_Dict.ContainsKey (aKey))
  681. return null;
  682. JSONNode tmp = m_Dict [aKey];
  683. m_Dict.Remove (aKey);
  684. return tmp;
  685. }
  686. public override JSONNode Remove (int aIndex)
  687. {
  688. if (aIndex < 0 || aIndex >= m_Dict.Count)
  689. return null;
  690. var item = m_Dict.ElementAt (aIndex);
  691. m_Dict.Remove (item.Key);
  692. return item.Value;
  693. }
  694. public override JSONNode Remove (JSONNode aNode)
  695. {
  696. try {
  697. var item = m_Dict.Where (k => k.Value == aNode).First ();
  698. m_Dict.Remove (item.Key);
  699. return aNode;
  700. } catch {
  701. return null;
  702. }
  703. }
  704. public override IEnumerable<JSONNode> Childs {
  705. get {
  706. foreach (KeyValuePair<string,JSONNode> N in m_Dict)
  707. yield return N.Value;
  708. }
  709. }
  710. public IEnumerator GetEnumerator ()
  711. {
  712. foreach (KeyValuePair<string, JSONNode> N in m_Dict)
  713. yield return N;
  714. }
  715. public override string ToString ()
  716. {
  717. string result = "{";
  718. foreach (KeyValuePair<string, JSONNode> N in m_Dict) {
  719. if (result.Length > 2)
  720. result += ", ";
  721. result += "\"" + Escape (N.Key) + "\":" + N.Value.ToString ();
  722. }
  723. result += "}";
  724. return result;
  725. }
  726. public override string ToString (string aPrefix)
  727. {
  728. string result = "{ ";
  729. foreach (KeyValuePair<string, JSONNode> N in m_Dict) {
  730. if (result.Length > 3)
  731. result += ", ";
  732. result += "\n" + aPrefix + " ";
  733. result += "\"" + Escape (N.Key) + "\" : " + N.Value.ToString (aPrefix + " ");
  734. }
  735. result += "\n" + aPrefix + "}";
  736. return result;
  737. }
  738. public override void Serialize (System.IO.BinaryWriter aWriter)
  739. {
  740. aWriter.Write ((byte)JSONBinaryTag.Class);
  741. aWriter.Write (m_Dict.Count);
  742. foreach (string K in m_Dict.Keys) {
  743. aWriter.Write (K);
  744. m_Dict [K].Serialize (aWriter);
  745. }
  746. }
  747. } // End of JSONClass
  748. public class JSONData : JSONNode
  749. {
  750. private string m_Data;
  751. public override string Value {
  752. get { return m_Data; }
  753. set { m_Data = value; }
  754. }
  755. public JSONData (string aData)
  756. {
  757. m_Data = aData;
  758. }
  759. public JSONData (float aData)
  760. {
  761. AsFloat = aData;
  762. }
  763. public JSONData (double aData)
  764. {
  765. AsDouble = aData;
  766. }
  767. public JSONData (bool aData)
  768. {
  769. AsBool = aData;
  770. }
  771. public JSONData (int aData)
  772. {
  773. AsInt = aData;
  774. }
  775. public override string ToString ()
  776. {
  777. return "\"" + Escape (m_Data) + "\"";
  778. }
  779. public override string ToString (string aPrefix)
  780. {
  781. return "\"" + Escape (m_Data) + "\"";
  782. }
  783. public override void Serialize (System.IO.BinaryWriter aWriter)
  784. {
  785. var tmp = new JSONData ("");
  786. tmp.AsInt = AsInt;
  787. if (tmp.m_Data == this.m_Data) {
  788. aWriter.Write ((byte)JSONBinaryTag.IntValue);
  789. aWriter.Write (AsInt);
  790. return;
  791. }
  792. tmp.AsFloat = AsFloat;
  793. if (tmp.m_Data == this.m_Data) {
  794. aWriter.Write ((byte)JSONBinaryTag.FloatValue);
  795. aWriter.Write (AsFloat);
  796. return;
  797. }
  798. tmp.AsDouble = AsDouble;
  799. if (tmp.m_Data == this.m_Data) {
  800. aWriter.Write ((byte)JSONBinaryTag.DoubleValue);
  801. aWriter.Write (AsDouble);
  802. return;
  803. }
  804. tmp.AsBool = AsBool;
  805. if (tmp.m_Data == this.m_Data) {
  806. aWriter.Write ((byte)JSONBinaryTag.BoolValue);
  807. aWriter.Write (AsBool);
  808. return;
  809. }
  810. aWriter.Write ((byte)JSONBinaryTag.Value);
  811. aWriter.Write (m_Data);
  812. }
  813. } // End of JSONData
  814. internal class JSONLazyCreator : JSONNode
  815. {
  816. private JSONNode m_Node = null;
  817. private string m_Key = null;
  818. public JSONLazyCreator (JSONNode aNode)
  819. {
  820. m_Node = aNode;
  821. m_Key = null;
  822. }
  823. public JSONLazyCreator (JSONNode aNode, string aKey)
  824. {
  825. m_Node = aNode;
  826. m_Key = aKey;
  827. }
  828. private void Set (JSONNode aVal)
  829. {
  830. if (m_Key == null) {
  831. m_Node.Add (aVal);
  832. } else {
  833. m_Node.Add (m_Key, aVal);
  834. }
  835. m_Node = null; // Be GC friendly.
  836. }
  837. public override JSONNode this [int aIndex] {
  838. get {
  839. return new JSONLazyCreator (this);
  840. }
  841. set {
  842. var tmp = new JSONArray ();
  843. tmp.Add (value);
  844. Set (tmp);
  845. }
  846. }
  847. public override JSONNode this [string aKey] {
  848. get {
  849. return new JSONLazyCreator (this, aKey);
  850. }
  851. set {
  852. var tmp = new JSONClass ();
  853. tmp.Add (aKey, value);
  854. Set (tmp);
  855. }
  856. }
  857. public override void Add (JSONNode aItem)
  858. {
  859. var tmp = new JSONArray ();
  860. tmp.Add (aItem);
  861. Set (tmp);
  862. }
  863. public override void Add (string aKey, JSONNode aItem)
  864. {
  865. var tmp = new JSONClass ();
  866. tmp.Add (aKey, aItem);
  867. Set (tmp);
  868. }
  869. public static bool operator == (JSONLazyCreator a, object b)
  870. {
  871. if (b == null)
  872. return true;
  873. return System.Object.ReferenceEquals (a, b);
  874. }
  875. public static bool operator != (JSONLazyCreator a, object b)
  876. {
  877. return !(a == b);
  878. }
  879. public override bool Equals (object obj)
  880. {
  881. if (obj == null)
  882. return true;
  883. return System.Object.ReferenceEquals (this, obj);
  884. }
  885. public override int GetHashCode ()
  886. {
  887. return base.GetHashCode ();
  888. }
  889. public override string ToString ()
  890. {
  891. return "";
  892. }
  893. public override string ToString (string aPrefix)
  894. {
  895. return "";
  896. }
  897. public override int AsInt {
  898. get {
  899. JSONData tmp = new JSONData (0);
  900. Set (tmp);
  901. return 0;
  902. }
  903. set {
  904. JSONData tmp = new JSONData (value);
  905. Set (tmp);
  906. }
  907. }
  908. public override float AsFloat {
  909. get {
  910. JSONData tmp = new JSONData (0.0f);
  911. Set (tmp);
  912. return 0.0f;
  913. }
  914. set {
  915. JSONData tmp = new JSONData (value);
  916. Set (tmp);
  917. }
  918. }
  919. public override double AsDouble {
  920. get {
  921. JSONData tmp = new JSONData (0.0);
  922. Set (tmp);
  923. return 0.0;
  924. }
  925. set {
  926. JSONData tmp = new JSONData (value);
  927. Set (tmp);
  928. }
  929. }
  930. public override bool AsBool {
  931. get {
  932. JSONData tmp = new JSONData (false);
  933. Set (tmp);
  934. return false;
  935. }
  936. set {
  937. JSONData tmp = new JSONData (value);
  938. Set (tmp);
  939. }
  940. }
  941. public override JSONArray AsArray {
  942. get {
  943. JSONArray tmp = new JSONArray ();
  944. Set (tmp);
  945. return tmp;
  946. }
  947. }
  948. public override JSONClass AsObject {
  949. get {
  950. JSONClass tmp = new JSONClass ();
  951. Set (tmp);
  952. return tmp;
  953. }
  954. }
  955. } // End of JSONLazyCreator
  956. public static class JSON
  957. {
  958. public static JSONNode Parse (string aJSON)
  959. {
  960. return JSONNode.Parse (aJSON);
  961. }
  962. }
  963. }
  964. }