JsonParser.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Globalization;
  6. using System.Reflection;
  7. using System.Reflection.Emit;
  8. using System.Text;
  9. namespace CP.Common.fastJSON
  10. {
  11. /// <summary>
  12. /// This class encodes and decodes JSON strings.
  13. /// Spec. details, see http://www.json.org/
  14. ///
  15. /// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable.
  16. /// All numbers are parsed to doubles.
  17. /// </summary>
  18. internal class JsonParser
  19. {
  20. private const int TOKEN_NONE = 0;
  21. private const int TOKEN_CURLY_OPEN = 1;
  22. private const int TOKEN_CURLY_CLOSE = 2;
  23. private const int TOKEN_SQUARED_OPEN = 3;
  24. private const int TOKEN_SQUARED_CLOSE = 4;
  25. private const int TOKEN_COLON = 5;
  26. private const int TOKEN_COMMA = 6;
  27. private const int TOKEN_STRING = 7;
  28. private const int TOKEN_NUMBER = 8;
  29. private const int TOKEN_TRUE = 9;
  30. private const int TOKEN_FALSE = 10;
  31. private const int TOKEN_NULL = 11;
  32. /// <summary>
  33. /// Parses the string json into a value
  34. /// </summary>
  35. /// <param name="json">A JSON string.</param>
  36. /// <returns>An ArrayList, a dictionary, a double, a string, null, true, or false</returns>
  37. internal static object JsonDecode(string json)
  38. {
  39. bool success = true;
  40. return JsonDecode(json, ref success);
  41. }
  42. /// <summary>
  43. /// Parses the string json into a value; and fills 'success' with the successfullness of the parse.
  44. /// </summary>
  45. /// <param name="json">A JSON string.</param>
  46. /// <param name="success">Successful parse?</param>
  47. /// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns>
  48. private static object JsonDecode(string json, ref bool success)
  49. {
  50. success = true;
  51. if (json != null)
  52. {
  53. char[] charArray = json.ToCharArray();
  54. int index = 0;
  55. object value = ParseValue(charArray, ref index, ref success);
  56. return value;
  57. }
  58. else
  59. {
  60. return null;
  61. }
  62. }
  63. protected static Dictionary<string, object> ParseObject(char[] json, ref int index, ref bool success)
  64. {
  65. Dictionary<string, object> table = new Dictionary<string, object>();
  66. int token;
  67. // {
  68. NextToken(json, ref index);
  69. bool done = false;
  70. while (!done)
  71. {
  72. token = LookAhead(json, index);
  73. if (token == TOKEN_NONE)
  74. {
  75. success = false;
  76. return null;
  77. }
  78. else if (token == TOKEN_COMMA)
  79. {
  80. NextToken(json, ref index);
  81. }
  82. else if (token == TOKEN_CURLY_CLOSE)
  83. {
  84. NextToken(json, ref index);
  85. return table;
  86. }
  87. else
  88. {
  89. // name
  90. string name = ParseString(json, ref index, ref success);
  91. if (!success)
  92. {
  93. success = false;
  94. return null;
  95. }
  96. // :
  97. token = NextToken(json, ref index);
  98. if (token != TOKEN_COLON)
  99. {
  100. success = false;
  101. return null;
  102. }
  103. // value
  104. object value = ParseValue(json, ref index, ref success);
  105. if (!success)
  106. {
  107. success = false;
  108. return null;
  109. }
  110. table[name] = value;
  111. }
  112. }
  113. return table;
  114. }
  115. protected static ArrayList ParseArray(char[] json, ref int index, ref bool success)
  116. {
  117. ArrayList array = new ArrayList();
  118. NextToken(json, ref index);
  119. bool done = false;
  120. while (!done)
  121. {
  122. int token = LookAhead(json, index);
  123. if (token == TOKEN_NONE)
  124. {
  125. success = false;
  126. return null;
  127. }
  128. else if (token == TOKEN_COMMA)
  129. {
  130. NextToken(json, ref index);
  131. }
  132. else if (token == TOKEN_SQUARED_CLOSE)
  133. {
  134. NextToken(json, ref index);
  135. break;
  136. }
  137. else
  138. {
  139. object value = ParseValue(json, ref index, ref success);
  140. if (!success)
  141. {
  142. return null;
  143. }
  144. array.Add(value);
  145. }
  146. }
  147. return array;
  148. }
  149. protected static object ParseValue(char[] json, ref int index, ref bool success)
  150. {
  151. switch (LookAhead(json, index))
  152. {
  153. case TOKEN_NUMBER:
  154. return ParseNumber(json, ref index, ref success);
  155. case TOKEN_STRING:
  156. return ParseString(json, ref index, ref success);
  157. case TOKEN_CURLY_OPEN:
  158. return ParseObject(json, ref index, ref success);
  159. case TOKEN_SQUARED_OPEN:
  160. return ParseArray(json, ref index, ref success);
  161. case TOKEN_TRUE:
  162. NextToken(json, ref index);
  163. return true;
  164. case TOKEN_FALSE:
  165. NextToken(json, ref index);
  166. return false;
  167. case TOKEN_NULL:
  168. NextToken(json, ref index);
  169. return null;
  170. case TOKEN_NONE:
  171. break;
  172. }
  173. success = false;
  174. return null;
  175. }
  176. protected static string ParseString(char[] json, ref int index, ref bool success)
  177. {
  178. StringBuilder s = new StringBuilder();
  179. char c;
  180. EatWhitespace(json, ref index);
  181. // "
  182. c = json[index++];
  183. bool complete = false;
  184. while (!complete)
  185. {
  186. if (index == json.Length)
  187. {
  188. break;
  189. }
  190. c = json[index++];
  191. if (c == '"')
  192. {
  193. complete = true;
  194. break;
  195. }
  196. else if (c == '\\')
  197. {
  198. if (index == json.Length)
  199. {
  200. break;
  201. }
  202. c = json[index++];
  203. if (c == '"')
  204. {
  205. s.Append('"');
  206. }
  207. else if (c == '\\')
  208. {
  209. s.Append('\\');
  210. }
  211. else if (c == '/')
  212. {
  213. s.Append('/');
  214. }
  215. else if (c == 'b')
  216. {
  217. s.Append('\b');
  218. }
  219. else if (c == 'f')
  220. {
  221. s.Append('\f');
  222. }
  223. else if (c == 'n')
  224. {
  225. s.Append('\n');
  226. }
  227. else if (c == 'r')
  228. {
  229. s.Append('\r');
  230. }
  231. else if (c == 't')
  232. {
  233. s.Append('\t');
  234. }
  235. else if (c == 'u')
  236. {
  237. int remainingLength = json.Length - index;
  238. if (remainingLength >= 4)
  239. {
  240. // parse the 32 bit hex into an integer codepoint
  241. uint codePoint;
  242. if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint)))
  243. {
  244. return "";
  245. }
  246. // convert the integer codepoint to a unicode char and add to string
  247. s.Append(Char.ConvertFromUtf32((int)codePoint));
  248. // skip 4 chars
  249. index += 4;
  250. }
  251. else
  252. {
  253. break;
  254. }
  255. }
  256. }
  257. else
  258. {
  259. s.Append(c);
  260. }
  261. }
  262. if (!complete)
  263. {
  264. success = false;
  265. return null;
  266. }
  267. return s.ToString();
  268. }
  269. protected static string ParseNumber(char[] json, ref int index, ref bool success)
  270. {
  271. EatWhitespace(json, ref index);
  272. int lastIndex = GetLastIndexOfNumber(json, index);
  273. int charLength = (lastIndex - index) + 1;
  274. string number = new string(json, index, charLength);
  275. success = true;
  276. index = lastIndex + 1;
  277. return number;
  278. }
  279. protected static int GetLastIndexOfNumber(char[] json, int index)
  280. {
  281. int lastIndex;
  282. for (lastIndex = index; lastIndex < json.Length; lastIndex++)
  283. {
  284. if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1)
  285. {
  286. break;
  287. }
  288. }
  289. return lastIndex - 1;
  290. }
  291. protected static void EatWhitespace(char[] json, ref int index)
  292. {
  293. for (; index < json.Length; index++)
  294. {
  295. if (" \t\n\r".IndexOf(json[index]) == -1)
  296. {
  297. break;
  298. }
  299. }
  300. }
  301. protected static int LookAhead(char[] json, int index)
  302. {
  303. int saveIndex = index;
  304. return NextToken(json, ref saveIndex);
  305. }
  306. protected static int NextToken(char[] json, ref int index)
  307. {
  308. EatWhitespace(json, ref index);
  309. if (index == json.Length)
  310. {
  311. return TOKEN_NONE;
  312. }
  313. char c = json[index];
  314. index++;
  315. switch (c)
  316. {
  317. case '{':
  318. return TOKEN_CURLY_OPEN;
  319. case '}':
  320. return TOKEN_CURLY_CLOSE;
  321. case '[':
  322. return TOKEN_SQUARED_OPEN;
  323. case ']':
  324. return TOKEN_SQUARED_CLOSE;
  325. case ',':
  326. return TOKEN_COMMA;
  327. case '"':
  328. return TOKEN_STRING;
  329. case '0':
  330. case '1':
  331. case '2':
  332. case '3':
  333. case '4':
  334. case '5':
  335. case '6':
  336. case '7':
  337. case '8':
  338. case '9':
  339. case '-':
  340. return TOKEN_NUMBER;
  341. case ':':
  342. return TOKEN_COLON;
  343. }
  344. index--;
  345. int remainingLength = json.Length - index;
  346. // false
  347. if (remainingLength >= 5)
  348. {
  349. if (json[index] == 'f' &&
  350. json[index + 1] == 'a' &&
  351. json[index + 2] == 'l' &&
  352. json[index + 3] == 's' &&
  353. json[index + 4] == 'e')
  354. {
  355. index += 5;
  356. return TOKEN_FALSE;
  357. }
  358. }
  359. // true
  360. if (remainingLength >= 4)
  361. {
  362. if (json[index] == 't' &&
  363. json[index + 1] == 'r' &&
  364. json[index + 2] == 'u' &&
  365. json[index + 3] == 'e')
  366. {
  367. index += 4;
  368. return TOKEN_TRUE;
  369. }
  370. }
  371. // null
  372. if (remainingLength >= 4)
  373. {
  374. if (json[index] == 'n' &&
  375. json[index + 1] == 'u' &&
  376. json[index + 2] == 'l' &&
  377. json[index + 3] == 'l')
  378. {
  379. index += 4;
  380. return TOKEN_NULL;
  381. }
  382. }
  383. return TOKEN_NONE;
  384. }
  385. protected static bool SerializeValue(object value, StringBuilder builder)
  386. {
  387. bool success = true;
  388. if (value is string)
  389. {
  390. success = SerializeString((string)value, builder);
  391. }
  392. else if (value is Hashtable)
  393. {
  394. success = SerializeObject((Hashtable)value, builder);
  395. }
  396. else if (value is ArrayList)
  397. {
  398. success = SerializeArray((ArrayList)value, builder);
  399. }
  400. else if (IsNumeric(value))
  401. {
  402. success = SerializeNumber(Convert.ToDouble(value), builder);
  403. }
  404. else if ((value is Boolean) && ((Boolean)value == true))
  405. {
  406. builder.Append("true");
  407. }
  408. else if ((value is Boolean) && ((Boolean)value == false))
  409. {
  410. builder.Append("false");
  411. }
  412. else if (value == null)
  413. {
  414. builder.Append("null");
  415. }
  416. else
  417. {
  418. success = false;
  419. }
  420. return success;
  421. }
  422. protected static bool SerializeObject(Hashtable anObject, StringBuilder builder)
  423. {
  424. builder.Append("{");
  425. IDictionaryEnumerator e = anObject.GetEnumerator();
  426. bool first = true;
  427. while (e.MoveNext())
  428. {
  429. string key = e.Key.ToString();
  430. object value = e.Value;
  431. if (!first)
  432. {
  433. builder.Append(", ");
  434. }
  435. SerializeString(key, builder);
  436. builder.Append(":");
  437. if (!SerializeValue(value, builder))
  438. {
  439. return false;
  440. }
  441. first = false;
  442. }
  443. builder.Append("}");
  444. return true;
  445. }
  446. protected static bool SerializeArray(ArrayList anArray, StringBuilder builder)
  447. {
  448. builder.Append("[");
  449. bool first = true;
  450. for (int i = 0; i < anArray.Count; i++)
  451. {
  452. object value = anArray[i];
  453. if (!first)
  454. {
  455. builder.Append(", ");
  456. }
  457. if (!SerializeValue(value, builder))
  458. {
  459. return false;
  460. }
  461. first = false;
  462. }
  463. builder.Append("]");
  464. return true;
  465. }
  466. protected static bool SerializeString(string aString, StringBuilder builder)
  467. {
  468. builder.Append("\"");
  469. char[] charArray = aString.ToCharArray();
  470. for (int i = 0; i < charArray.Length; i++)
  471. {
  472. char c = charArray[i];
  473. if (c == '"')
  474. {
  475. builder.Append("\\\"");
  476. }
  477. else if (c == '\\')
  478. {
  479. builder.Append("\\\\");
  480. }
  481. else if (c == '\b')
  482. {
  483. builder.Append("\\b");
  484. }
  485. else if (c == '\f')
  486. {
  487. builder.Append("\\f");
  488. }
  489. else if (c == '\n')
  490. {
  491. builder.Append("\\n");
  492. }
  493. else if (c == '\r')
  494. {
  495. builder.Append("\\r");
  496. }
  497. else if (c == '\t')
  498. {
  499. builder.Append("\\t");
  500. }
  501. else
  502. {
  503. int codepoint = Convert.ToInt32(c);
  504. if ((codepoint >= 32) && (codepoint <= 126))
  505. {
  506. builder.Append(c);
  507. }
  508. else
  509. {
  510. builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
  511. }
  512. }
  513. }
  514. builder.Append("\"");
  515. return true;
  516. }
  517. protected static bool SerializeNumber(double number, StringBuilder builder)
  518. {
  519. builder.Append(Convert.ToString(number, CultureInfo.InvariantCulture));
  520. return true;
  521. }
  522. protected static bool IsNumeric(object o)
  523. {
  524. double result;
  525. return (o == null) ? false : Double.TryParse(o.ToString(), out result);
  526. }
  527. }
  528. }