miniJSON.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. 
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Text;
  7. namespace SimpleFirebaseUnity.MiniJSON
  8. {
  9. // Example usage:
  10. //
  11. // using UnityEngine;
  12. // using System.Collections;
  13. // using System.Collections.Generic;
  14. // using MiniJSON;
  15. //
  16. // public class MiniJSONTest : MonoBehaviour {
  17. // void Start () {
  18. // var jsonString = "{ \"array\": [1.44,2,3], " +
  19. // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
  20. // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
  21. // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
  22. // "\"int\": 65536, " +
  23. // "\"float\": 3.1415926, " +
  24. // "\"bool\": true, " +
  25. // "\"null\": null }";
  26. //
  27. // var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
  28. //
  29. // Debug.Log("deserialized: " + dict.GetType());
  30. // Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
  31. // Debug.Log("dict['string']: " + (string) dict["string"]);
  32. // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
  33. // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
  34. // Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
  35. //
  36. // var str = Json.Serialize(dict);
  37. //
  38. // Debug.Log("serialized: " + str);
  39. // }
  40. // }
  41. /// <summary>
  42. /// This class encodes and decodes JSON strings.
  43. /// Spec. details, see http://www.json.org/
  44. ///
  45. /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
  46. /// All numbers are parsed to doubles.
  47. /// </summary>
  48. public static class Json
  49. {
  50. /// <summary>
  51. /// Parses the string json into a value
  52. /// </summary>
  53. /// <param name="json">A JSON string.</param>
  54. /// <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false</returns>
  55. public static object Deserialize(string json)
  56. {
  57. // save the string for debug information
  58. if (json == null)
  59. {
  60. return null;
  61. }
  62. return Parser.Parse(json);
  63. }
  64. sealed class Parser : IDisposable
  65. {
  66. const string WORD_BREAK = "{}[],:\"";
  67. public static bool IsWordBreak(char c)
  68. {
  69. return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1;
  70. }
  71. enum TOKEN
  72. {
  73. NONE,
  74. CURLY_OPEN,
  75. CURLY_CLOSE,
  76. SQUARED_OPEN,
  77. SQUARED_CLOSE,
  78. COLON,
  79. COMMA,
  80. STRING,
  81. NUMBER,
  82. TRUE,
  83. FALSE,
  84. NULL
  85. };
  86. StringReader json;
  87. Parser(string jsonString)
  88. {
  89. json = new StringReader(jsonString);
  90. }
  91. public static object Parse(string jsonString)
  92. {
  93. using (var instance = new Parser(jsonString))
  94. {
  95. return instance.ParseValue();
  96. }
  97. }
  98. public void Dispose()
  99. {
  100. json.Dispose();
  101. json = null;
  102. }
  103. Dictionary<string, object> ParseObject()
  104. {
  105. Dictionary<string, object> table = new Dictionary<string, object>();
  106. // ditch opening brace
  107. json.Read();
  108. // {
  109. while (true)
  110. {
  111. switch (NextToken)
  112. {
  113. case TOKEN.NONE:
  114. return null;
  115. case TOKEN.COMMA:
  116. continue;
  117. case TOKEN.CURLY_CLOSE:
  118. return table;
  119. default:
  120. // name
  121. string name = ParseString();
  122. if (name == null)
  123. {
  124. return null;
  125. }
  126. // :
  127. if (NextToken != TOKEN.COLON)
  128. {
  129. return null;
  130. }
  131. // ditch the colon
  132. json.Read();
  133. // value
  134. table[name] = ParseValue();
  135. break;
  136. }
  137. }
  138. }
  139. List<object> ParseArray()
  140. {
  141. List<object> array = new List<object>();
  142. // ditch opening bracket
  143. json.Read();
  144. // [
  145. var parsing = true;
  146. while (parsing)
  147. {
  148. TOKEN nextToken = NextToken;
  149. switch (nextToken)
  150. {
  151. case TOKEN.NONE:
  152. return null;
  153. case TOKEN.COMMA:
  154. continue;
  155. case TOKEN.SQUARED_CLOSE:
  156. parsing = false;
  157. break;
  158. default:
  159. object value = ParseByToken(nextToken);
  160. array.Add(value);
  161. break;
  162. }
  163. }
  164. return array;
  165. }
  166. object ParseValue()
  167. {
  168. TOKEN nextToken = NextToken;
  169. return ParseByToken(nextToken);
  170. }
  171. object ParseByToken(TOKEN token)
  172. {
  173. switch (token)
  174. {
  175. case TOKEN.STRING:
  176. return ParseString();
  177. case TOKEN.NUMBER:
  178. return ParseNumber();
  179. case TOKEN.CURLY_OPEN:
  180. return ParseObject();
  181. case TOKEN.SQUARED_OPEN:
  182. return ParseArray();
  183. case TOKEN.TRUE:
  184. return true;
  185. case TOKEN.FALSE:
  186. return false;
  187. case TOKEN.NULL:
  188. return null;
  189. default:
  190. return null;
  191. }
  192. }
  193. string ParseString()
  194. {
  195. StringBuilder s = new StringBuilder();
  196. char c;
  197. // ditch opening quote
  198. json.Read();
  199. bool parsing = true;
  200. while (parsing)
  201. {
  202. if (json.Peek() == -1)
  203. {
  204. parsing = false;
  205. break;
  206. }
  207. c = NextChar;
  208. switch (c)
  209. {
  210. case '"':
  211. parsing = false;
  212. break;
  213. case '\\':
  214. if (json.Peek() == -1)
  215. {
  216. parsing = false;
  217. break;
  218. }
  219. c = NextChar;
  220. switch (c)
  221. {
  222. case '"':
  223. case '\\':
  224. case '/':
  225. s.Append(c);
  226. break;
  227. case 'b':
  228. s.Append('\b');
  229. break;
  230. case 'f':
  231. s.Append('\f');
  232. break;
  233. case 'n':
  234. s.Append('\n');
  235. break;
  236. case 'r':
  237. s.Append('\r');
  238. break;
  239. case 't':
  240. s.Append('\t');
  241. break;
  242. case 'u':
  243. var hex = new char[4];
  244. for (int i = 0; i < 4; i++)
  245. {
  246. hex[i] = NextChar;
  247. }
  248. s.Append((char)Convert.ToInt32(new string(hex), 16));
  249. break;
  250. }
  251. break;
  252. default:
  253. s.Append(c);
  254. break;
  255. }
  256. }
  257. return s.ToString();
  258. }
  259. object ParseNumber()
  260. {
  261. string number = NextWord;
  262. if (number.IndexOf('.') == -1)
  263. {
  264. long parsedInt;
  265. Int64.TryParse(number, out parsedInt);
  266. return parsedInt;
  267. }
  268. double parsedDouble;
  269. Double.TryParse(number, out parsedDouble);
  270. return parsedDouble;
  271. }
  272. void EatWhitespace()
  273. {
  274. while (Char.IsWhiteSpace(PeekChar))
  275. {
  276. json.Read();
  277. if (json.Peek() == -1)
  278. {
  279. break;
  280. }
  281. }
  282. }
  283. char PeekChar
  284. {
  285. get
  286. {
  287. return Convert.ToChar(json.Peek());
  288. }
  289. }
  290. char NextChar
  291. {
  292. get
  293. {
  294. return Convert.ToChar(json.Read());
  295. }
  296. }
  297. string NextWord
  298. {
  299. get
  300. {
  301. StringBuilder word = new StringBuilder();
  302. while (!IsWordBreak(PeekChar))
  303. {
  304. word.Append(NextChar);
  305. if (json.Peek() == -1)
  306. {
  307. break;
  308. }
  309. }
  310. return word.ToString();
  311. }
  312. }
  313. TOKEN NextToken
  314. {
  315. get
  316. {
  317. EatWhitespace();
  318. if (json.Peek() == -1)
  319. {
  320. return TOKEN.NONE;
  321. }
  322. switch (PeekChar)
  323. {
  324. case '{':
  325. return TOKEN.CURLY_OPEN;
  326. case '}':
  327. json.Read();
  328. return TOKEN.CURLY_CLOSE;
  329. case '[':
  330. return TOKEN.SQUARED_OPEN;
  331. case ']':
  332. json.Read();
  333. return TOKEN.SQUARED_CLOSE;
  334. case ',':
  335. json.Read();
  336. return TOKEN.COMMA;
  337. case '"':
  338. return TOKEN.STRING;
  339. case ':':
  340. return TOKEN.COLON;
  341. case '0':
  342. case '1':
  343. case '2':
  344. case '3':
  345. case '4':
  346. case '5':
  347. case '6':
  348. case '7':
  349. case '8':
  350. case '9':
  351. case '-':
  352. return TOKEN.NUMBER;
  353. }
  354. switch (NextWord)
  355. {
  356. case "false":
  357. return TOKEN.FALSE;
  358. case "true":
  359. return TOKEN.TRUE;
  360. case "null":
  361. return TOKEN.NULL;
  362. }
  363. return TOKEN.NONE;
  364. }
  365. }
  366. }
  367. /// <summary>
  368. /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
  369. /// </summary>
  370. /// <param name="json">A Dictionary&lt;string, object&gt; / List&lt;object&gt;</param>
  371. /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
  372. public static string Serialize(object obj)
  373. {
  374. return Serializer.Serialize(obj);
  375. }
  376. sealed class Serializer
  377. {
  378. StringBuilder builder;
  379. Serializer()
  380. {
  381. builder = new StringBuilder();
  382. }
  383. public static string Serialize(object obj)
  384. {
  385. var instance = new Serializer();
  386. instance.SerializeValue(obj);
  387. return instance.builder.ToString();
  388. }
  389. void SerializeValue(object value)
  390. {
  391. IList asList;
  392. IDictionary asDict;
  393. string asStr;
  394. if (value == null)
  395. {
  396. builder.Append("null");
  397. }
  398. else if ((asStr = value as string) != null)
  399. {
  400. SerializeString(asStr);
  401. }
  402. else if (value is bool)
  403. {
  404. builder.Append((bool)value ? "true" : "false");
  405. }
  406. else if ((asList = value as IList) != null)
  407. {
  408. SerializeArray(asList);
  409. }
  410. else if ((asDict = value as IDictionary) != null)
  411. {
  412. SerializeObject(asDict);
  413. }
  414. else if (value is char)
  415. {
  416. SerializeString(new string((char)value, 1));
  417. }
  418. else {
  419. SerializeOther(value);
  420. }
  421. }
  422. void SerializeObject(IDictionary obj)
  423. {
  424. bool first = true;
  425. builder.Append('{');
  426. foreach (object e in obj.Keys)
  427. {
  428. if (!first)
  429. {
  430. builder.Append(',');
  431. }
  432. SerializeString(e.ToString());
  433. builder.Append(':');
  434. SerializeValue(obj[e]);
  435. first = false;
  436. }
  437. builder.Append('}');
  438. }
  439. void SerializeArray(IList anArray)
  440. {
  441. builder.Append('[');
  442. bool first = true;
  443. foreach (object obj in anArray)
  444. {
  445. if (!first)
  446. {
  447. builder.Append(',');
  448. }
  449. SerializeValue(obj);
  450. first = false;
  451. }
  452. builder.Append(']');
  453. }
  454. void SerializeString(string str)
  455. {
  456. builder.Append('\"');
  457. char[] charArray = str.ToCharArray();
  458. foreach (var c in charArray)
  459. {
  460. switch (c)
  461. {
  462. case '"':
  463. builder.Append("\\\"");
  464. break;
  465. case '\\':
  466. builder.Append("\\\\");
  467. break;
  468. case '\b':
  469. builder.Append("\\b");
  470. break;
  471. case '\f':
  472. builder.Append("\\f");
  473. break;
  474. case '\n':
  475. builder.Append("\\n");
  476. break;
  477. case '\r':
  478. builder.Append("\\r");
  479. break;
  480. case '\t':
  481. builder.Append("\\t");
  482. break;
  483. default:
  484. int codepoint = Convert.ToInt32(c);
  485. if ((codepoint >= 32) && (codepoint <= 126))
  486. {
  487. builder.Append(c);
  488. }
  489. else {
  490. builder.Append("\\u");
  491. builder.Append(codepoint.ToString("x4"));
  492. }
  493. break;
  494. }
  495. }
  496. builder.Append('\"');
  497. }
  498. void SerializeOther(object value)
  499. {
  500. // NOTE: decimals lose precision during serialization.
  501. // They always have, I'm just letting you know.
  502. // Previously floats and doubles lost precision too.
  503. if (value is float)
  504. {
  505. builder.Append(((float)value).ToString("R"));
  506. }
  507. else if (value is int
  508. || value is uint
  509. || value is long
  510. || value is sbyte
  511. || value is byte
  512. || value is short
  513. || value is ushort
  514. || value is ulong)
  515. {
  516. builder.Append(value);
  517. }
  518. else if (value is double
  519. || value is decimal)
  520. {
  521. builder.Append(Convert.ToDouble(value).ToString("R"));
  522. }
  523. else {
  524. SerializeString(value.ToString());
  525. }
  526. }
  527. }
  528. }
  529. }