MiniJSON.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /*
  2. * Copyright (c) 2013 Calvin Rien
  3. *
  4. * Based on the JSON parser by Patrick van Bergen
  5. * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
  6. *
  7. * Simplified it so that it doesn't throw exceptions
  8. * and can be used in Unity iPhone with maximum code stripping.
  9. *
  10. * Permission is hereby granted, free of charge, to any person obtaining
  11. * a copy of this software and associated documentation files (the
  12. * "Software"), to deal in the Software without restriction, including
  13. * without limitation the rights to use, copy, modify, merge, publish,
  14. * distribute, sublicense, and/or sell copies of the Software, and to
  15. * permit persons to whom the Software is furnished to do so, subject to
  16. * the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be
  19. * included in all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  24. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  25. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  26. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  27. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. */
  29. using System;
  30. using System.Collections;
  31. using System.Collections.Generic;
  32. using System.IO;
  33. using System.Text;
  34. namespace MiniJSON {
  35. // Example usage:
  36. //
  37. // using UnityEngine;
  38. // using System.Collections;
  39. // using System.Collections.Generic;
  40. // using MiniJSON;
  41. //
  42. // public class MiniJSONTest : MonoBehaviour {
  43. // void Start () {
  44. // var jsonString = "{ \"array\": [1.44,2,3], " +
  45. // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
  46. // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
  47. // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
  48. // "\"int\": 65536, " +
  49. // "\"float\": 3.1415926, " +
  50. // "\"bool\": true, " +
  51. // "\"null\": null }";
  52. //
  53. // var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
  54. //
  55. // Debug.Log("deserialized: " + dict.GetType());
  56. // Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
  57. // Debug.Log("dict['string']: " + (string) dict["string"]);
  58. // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
  59. // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
  60. // Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
  61. //
  62. // var str = Json.Serialize(dict);
  63. //
  64. // Debug.Log("serialized: " + str);
  65. // }
  66. // }
  67. /// <summary>
  68. /// This class encodes and decodes JSON strings.
  69. /// Spec. details, see http://www.json.org/
  70. ///
  71. /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
  72. /// All numbers are parsed to doubles.
  73. /// </summary>
  74. public static class Json {
  75. /// <summary>
  76. /// Parses the string json into a value
  77. /// </summary>
  78. /// <param name="json">A JSON string.</param>
  79. /// <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false</returns>
  80. public static object Deserialize(string json) {
  81. // save the string for debug information
  82. if (json == null) {
  83. return null;
  84. }
  85. return Parser.Parse(json);
  86. }
  87. sealed class Parser : IDisposable {
  88. const string WORD_BREAK = "{}[],:\"";
  89. public static bool IsWordBreak(char c) {
  90. return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1;
  91. }
  92. enum TOKEN {
  93. NONE,
  94. CURLY_OPEN,
  95. CURLY_CLOSE,
  96. SQUARED_OPEN,
  97. SQUARED_CLOSE,
  98. COLON,
  99. COMMA,
  100. STRING,
  101. NUMBER,
  102. TRUE,
  103. FALSE,
  104. NULL
  105. };
  106. StringReader json;
  107. Parser(string jsonString) {
  108. json = new StringReader(jsonString);
  109. }
  110. public static object Parse(string jsonString) {
  111. using (var instance = new Parser(jsonString)) {
  112. return instance.ParseValue();
  113. }
  114. }
  115. public void Dispose() {
  116. json.Dispose();
  117. json = null;
  118. }
  119. Dictionary<string, object> ParseObject() {
  120. Dictionary<string, object> table = new Dictionary<string, object>();
  121. // ditch opening brace
  122. json.Read();
  123. // {
  124. while (true) {
  125. switch (NextToken) {
  126. case TOKEN.NONE:
  127. return null;
  128. case TOKEN.COMMA:
  129. continue;
  130. case TOKEN.CURLY_CLOSE:
  131. return table;
  132. default:
  133. // name
  134. string name = ParseString();
  135. if (name == null) {
  136. return null;
  137. }
  138. // :
  139. if (NextToken != TOKEN.COLON) {
  140. return null;
  141. }
  142. // ditch the colon
  143. json.Read();
  144. // value
  145. table[name] = ParseValue();
  146. break;
  147. }
  148. }
  149. }
  150. List<object> ParseArray() {
  151. List<object> array = new List<object>();
  152. // ditch opening bracket
  153. json.Read();
  154. // [
  155. var parsing = true;
  156. while (parsing) {
  157. TOKEN nextToken = NextToken;
  158. switch (nextToken) {
  159. case TOKEN.NONE:
  160. return null;
  161. case TOKEN.COMMA:
  162. continue;
  163. case TOKEN.SQUARED_CLOSE:
  164. parsing = false;
  165. break;
  166. default:
  167. object value = ParseByToken(nextToken);
  168. array.Add(value);
  169. break;
  170. }
  171. }
  172. return array;
  173. }
  174. object ParseValue() {
  175. TOKEN nextToken = NextToken;
  176. return ParseByToken(nextToken);
  177. }
  178. object ParseByToken(TOKEN token) {
  179. switch (token) {
  180. case TOKEN.STRING:
  181. return ParseString();
  182. case TOKEN.NUMBER:
  183. return ParseNumber();
  184. case TOKEN.CURLY_OPEN:
  185. return ParseObject();
  186. case TOKEN.SQUARED_OPEN:
  187. return ParseArray();
  188. case TOKEN.TRUE:
  189. return true;
  190. case TOKEN.FALSE:
  191. return false;
  192. case TOKEN.NULL:
  193. return null;
  194. default:
  195. return null;
  196. }
  197. }
  198. string ParseString() {
  199. StringBuilder s = new StringBuilder();
  200. char c;
  201. // ditch opening quote
  202. json.Read();
  203. bool parsing = true;
  204. while (parsing) {
  205. if (json.Peek() == -1) {
  206. parsing = false;
  207. break;
  208. }
  209. c = NextChar;
  210. switch (c) {
  211. case '"':
  212. parsing = false;
  213. break;
  214. case '\\':
  215. if (json.Peek() == -1) {
  216. parsing = false;
  217. break;
  218. }
  219. c = NextChar;
  220. switch (c) {
  221. case '"':
  222. case '\\':
  223. case '/':
  224. s.Append(c);
  225. break;
  226. case 'b':
  227. s.Append('\b');
  228. break;
  229. case 'f':
  230. s.Append('\f');
  231. break;
  232. case 'n':
  233. s.Append('\n');
  234. break;
  235. case 'r':
  236. s.Append('\r');
  237. break;
  238. case 't':
  239. s.Append('\t');
  240. break;
  241. case 'u':
  242. var hex = new char[4];
  243. for (int i=0; i< 4; i++) {
  244. hex[i] = NextChar;
  245. }
  246. s.Append((char) Convert.ToInt32(new string(hex), 16));
  247. break;
  248. }
  249. break;
  250. default:
  251. s.Append(c);
  252. break;
  253. }
  254. }
  255. return s.ToString();
  256. }
  257. object ParseNumber() {
  258. string number = NextWord;
  259. if (number.IndexOf('.') == -1) {
  260. long parsedInt;
  261. Int64.TryParse(number, out parsedInt);
  262. return parsedInt;
  263. }
  264. double parsedDouble;
  265. Double.TryParse(number, out parsedDouble);
  266. return parsedDouble;
  267. }
  268. void EatWhitespace() {
  269. while (Char.IsWhiteSpace(PeekChar)) {
  270. json.Read();
  271. if (json.Peek() == -1) {
  272. break;
  273. }
  274. }
  275. }
  276. char PeekChar {
  277. get {
  278. return Convert.ToChar(json.Peek());
  279. }
  280. }
  281. char NextChar {
  282. get {
  283. return Convert.ToChar(json.Read());
  284. }
  285. }
  286. string NextWord {
  287. get {
  288. StringBuilder word = new StringBuilder();
  289. while (!IsWordBreak(PeekChar)) {
  290. word.Append(NextChar);
  291. if (json.Peek() == -1) {
  292. break;
  293. }
  294. }
  295. return word.ToString();
  296. }
  297. }
  298. TOKEN NextToken {
  299. get {
  300. EatWhitespace();
  301. if (json.Peek() == -1) {
  302. return TOKEN.NONE;
  303. }
  304. switch (PeekChar) {
  305. case '{':
  306. return TOKEN.CURLY_OPEN;
  307. case '}':
  308. json.Read();
  309. return TOKEN.CURLY_CLOSE;
  310. case '[':
  311. return TOKEN.SQUARED_OPEN;
  312. case ']':
  313. json.Read();
  314. return TOKEN.SQUARED_CLOSE;
  315. case ',':
  316. json.Read();
  317. return TOKEN.COMMA;
  318. case '"':
  319. return TOKEN.STRING;
  320. case ':':
  321. return TOKEN.COLON;
  322. case '0':
  323. case '1':
  324. case '2':
  325. case '3':
  326. case '4':
  327. case '5':
  328. case '6':
  329. case '7':
  330. case '8':
  331. case '9':
  332. case '-':
  333. return TOKEN.NUMBER;
  334. }
  335. switch (NextWord) {
  336. case "false":
  337. return TOKEN.FALSE;
  338. case "true":
  339. return TOKEN.TRUE;
  340. case "null":
  341. return TOKEN.NULL;
  342. }
  343. return TOKEN.NONE;
  344. }
  345. }
  346. }
  347. /// <summary>
  348. /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
  349. /// </summary>
  350. /// <param name="json">A Dictionary&lt;string, object&gt; / List&lt;object&gt;</param>
  351. /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
  352. public static string Serialize(object obj) {
  353. return Serializer.Serialize(obj);
  354. }
  355. sealed class Serializer {
  356. StringBuilder builder;
  357. Serializer() {
  358. builder = new StringBuilder();
  359. }
  360. public static string Serialize(object obj) {
  361. var instance = new Serializer();
  362. instance.SerializeValue(obj);
  363. return instance.builder.ToString();
  364. }
  365. void SerializeValue(object value) {
  366. IList asList;
  367. IDictionary asDict;
  368. string asStr;
  369. if (value == null) {
  370. builder.Append("null");
  371. } else if ((asStr = value as string) != null) {
  372. SerializeString(asStr);
  373. } else if (value is bool) {
  374. builder.Append((bool) value ? "true" : "false");
  375. } else if ((asList = value as IList) != null) {
  376. SerializeArray(asList);
  377. } else if ((asDict = value as IDictionary) != null) {
  378. SerializeObject(asDict);
  379. } else if (value is char) {
  380. SerializeString(new string((char) value, 1));
  381. } else {
  382. SerializeOther(value);
  383. }
  384. }
  385. void SerializeObject(IDictionary obj) {
  386. bool first = true;
  387. builder.Append('{');
  388. foreach (object e in obj.Keys) {
  389. if (!first) {
  390. builder.Append(',');
  391. }
  392. SerializeString(e.ToString());
  393. builder.Append(':');
  394. SerializeValue(obj[e]);
  395. first = false;
  396. }
  397. builder.Append('}');
  398. }
  399. void SerializeArray(IList anArray) {
  400. builder.Append('[');
  401. bool first = true;
  402. foreach (object obj in anArray) {
  403. if (!first) {
  404. builder.Append(',');
  405. }
  406. SerializeValue(obj);
  407. first = false;
  408. }
  409. builder.Append(']');
  410. }
  411. void SerializeString(string str) {
  412. builder.Append('\"');
  413. char[] charArray = str.ToCharArray();
  414. foreach (var c in charArray) {
  415. switch (c) {
  416. case '"':
  417. builder.Append("\\\"");
  418. break;
  419. case '\\':
  420. builder.Append("\\\\");
  421. break;
  422. case '\b':
  423. builder.Append("\\b");
  424. break;
  425. case '\f':
  426. builder.Append("\\f");
  427. break;
  428. case '\n':
  429. builder.Append("\\n");
  430. break;
  431. case '\r':
  432. builder.Append("\\r");
  433. break;
  434. case '\t':
  435. builder.Append("\\t");
  436. break;
  437. default:
  438. int codepoint = Convert.ToInt32(c);
  439. if ((codepoint >= 32) && (codepoint <= 126)) {
  440. builder.Append(c);
  441. } else {
  442. builder.Append("\\u");
  443. builder.Append(codepoint.ToString("x4"));
  444. }
  445. break;
  446. }
  447. }
  448. builder.Append('\"');
  449. }
  450. void SerializeOther(object value) {
  451. // NOTE: decimals lose precision during serialization.
  452. // They always have, I'm just letting you know.
  453. // Previously floats and doubles lost precision too.
  454. if (value is float) {
  455. builder.Append(((float) value).ToString("R"));
  456. } else if (value is int
  457. || value is uint
  458. || value is long
  459. || value is sbyte
  460. || value is byte
  461. || value is short
  462. || value is ushort
  463. || value is ulong) {
  464. builder.Append(value);
  465. } else if (value is double
  466. || value is decimal) {
  467. builder.Append(Convert.ToDouble(value).ToString("R"));
  468. } else {
  469. SerializeString(value.ToString());
  470. }
  471. }
  472. }
  473. }
  474. }