JsonDeserializer.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. //
  2. // JsonDeserializer.cs
  3. //
  4. // Author:
  5. // Marek Habersack <[email protected]>
  6. //
  7. // (C) 2008 Novell, Inc. http://novell.com/
  8. // Copyright 2011, Xamarin, Inc (http://xamarin.com)
  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
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. // Code is based on JSON_checker (http://www.json.org/JSON_checker/) and JSON_parser
  30. // (http://fara.cs.uni-potsdam.de/~jsg/json_parser/) C sources.
  31. using System;
  32. using System.Collections;
  33. using System.Collections.Generic;
  34. using System.Data;
  35. using System.Globalization;
  36. using System.IO;
  37. using System.Reflection;
  38. using System.Text;
  39. namespace System.Web.Script.Serialization
  40. {
  41. internal sealed class JsonDeserializer
  42. {
  43. /* Universal error constant */
  44. const int __ = -1;
  45. const int UNIVERSAL_ERROR = __;
  46. /*
  47. Characters are mapped into these 31 character classes. This allows for
  48. a significant reduction in the size of the state transition table.
  49. */
  50. const int C_SPACE = 0x00; /* space */
  51. const int C_WHITE = 0x01; /* other whitespace */
  52. const int C_LCURB = 0x02; /* { */
  53. const int C_RCURB = 0x03; /* } */
  54. const int C_LSQRB = 0x04; /* [ */
  55. const int C_RSQRB = 0x05; /* ] */
  56. const int C_COLON = 0x06; /* : */
  57. const int C_COMMA = 0x07; /* , */
  58. const int C_QUOTE = 0x08; /* " */
  59. const int C_BACKS = 0x09; /* \ */
  60. const int C_SLASH = 0x0A; /* / */
  61. const int C_PLUS = 0x0B; /* + */
  62. const int C_MINUS = 0x0C; /* - */
  63. const int C_POINT = 0x0D; /* . */
  64. const int C_ZERO = 0x0E; /* 0 */
  65. const int C_DIGIT = 0x0F; /* 123456789 */
  66. const int C_LOW_A = 0x10; /* a */
  67. const int C_LOW_B = 0x11; /* b */
  68. const int C_LOW_C = 0x12; /* c */
  69. const int C_LOW_D = 0x13; /* d */
  70. const int C_LOW_E = 0x14; /* e */
  71. const int C_LOW_F = 0x15; /* f */
  72. const int C_LOW_L = 0x16; /* l */
  73. const int C_LOW_N = 0x17; /* n */
  74. const int C_LOW_R = 0x18; /* r */
  75. const int C_LOW_S = 0x19; /* s */
  76. const int C_LOW_T = 0x1A; /* t */
  77. const int C_LOW_U = 0x1B; /* u */
  78. const int C_ABCDF = 0x1C; /* ABCDF */
  79. const int C_E = 0x1D; /* E */
  80. const int C_ETC = 0x1E; /* everything else */
  81. const int C_STAR = 0x1F; /* * */
  82. const int C_I = 0x20; /* I */
  83. const int C_LOW_I = 0x21; /* i */
  84. const int C_LOW_Y = 0x22; /* y */
  85. const int C_N = 0x23; /* N */
  86. /* The state codes. */
  87. const int GO = 0x00; /* start */
  88. const int OK = 0x01; /* ok */
  89. const int OB = 0x02; /* object */
  90. const int KE = 0x03; /* key */
  91. const int CO = 0x04; /* colon */
  92. const int VA = 0x05; /* value */
  93. const int AR = 0x06; /* array */
  94. const int ST = 0x07; /* string */
  95. const int ES = 0x08; /* escape */
  96. const int U1 = 0x09; /* u1 */
  97. const int U2 = 0x0A; /* u2 */
  98. const int U3 = 0x0B; /* u3 */
  99. const int U4 = 0x0C; /* u4 */
  100. const int MI = 0x0D; /* minus */
  101. const int ZE = 0x0E; /* zero */
  102. const int IN = 0x0F; /* integer */
  103. const int FR = 0x10; /* fraction */
  104. const int E1 = 0x11; /* e */
  105. const int E2 = 0x12; /* ex */
  106. const int E3 = 0x13; /* exp */
  107. const int T1 = 0x14; /* tr */
  108. const int T2 = 0x15; /* tru */
  109. const int T3 = 0x16; /* true */
  110. const int F1 = 0x17; /* fa */
  111. const int F2 = 0x18; /* fal */
  112. const int F3 = 0x19; /* fals */
  113. const int F4 = 0x1A; /* false */
  114. const int N1 = 0x1B; /* nu */
  115. const int N2 = 0x1C; /* nul */
  116. const int N3 = 0x1D; /* null */
  117. const int FX = 0x1E; /* *.* *eE* */
  118. const int IV = 0x1F; /* invalid input */
  119. const int UK = 0x20; /* unquoted key name */
  120. const int UI = 0x21; /* ignore during unquoted key name construction */
  121. const int I1 = 0x22; /* In */
  122. const int I2 = 0x23; /* Inf */
  123. const int I3 = 0x24; /* Infi */
  124. const int I4 = 0x25; /* Infin */
  125. const int I5 = 0x26; /* Infini */
  126. const int I6 = 0x27; /* Infinit */
  127. const int I7 = 0x28; /* Infinity */
  128. const int V1 = 0x29; /* Na */
  129. const int V2 = 0x2A; /* NaN */
  130. /* Actions */
  131. const int FA = -10; /* false */
  132. const int TR = -11; /* false */
  133. const int NU = -12; /* null */
  134. const int DE = -13; /* double detected by exponent e E */
  135. const int DF = -14; /* double detected by fraction . */
  136. const int SB = -15; /* string begin */
  137. const int MX = -16; /* integer detected by minus */
  138. const int ZX = -17; /* integer detected by zero */
  139. const int IX = -18; /* integer detected by 1-9 */
  140. const int EX = -19; /* next char is escaped */
  141. const int UC = -20; /* Unicode character read */
  142. const int SE = -4; /* string end */
  143. const int AB = -5; /* array begin */
  144. const int AE = -7; /* array end */
  145. const int OS = -6; /* object start */
  146. const int OE = -8; /* object end */
  147. const int EO = -9; /* empty object */
  148. const int CM = -3; /* comma */
  149. const int CA = -2; /* colon action */
  150. const int PX = -21; /* integer detected by plus */
  151. const int KB = -22; /* unquoted key name begin */
  152. const int UE = -23; /* unquoted key name end */
  153. const int IF = -25; /* Infinity */
  154. const int NN = -26; /* NaN */
  155. enum JsonMode {
  156. NONE,
  157. ARRAY,
  158. DONE,
  159. KEY,
  160. OBJECT
  161. };
  162. enum JsonType {
  163. NONE = 0,
  164. ARRAY_BEGIN,
  165. ARRAY_END,
  166. OBJECT_BEGIN,
  167. OBJECT_END,
  168. INTEGER,
  169. FLOAT,
  170. NULL,
  171. TRUE,
  172. FALSE,
  173. STRING,
  174. KEY,
  175. MAX
  176. };
  177. /*
  178. This array maps the 128 ASCII characters into character classes.
  179. The remaining Unicode characters should be mapped to C_ETC.
  180. Non-whitespace control characters are errors.
  181. */
  182. static readonly int[] ascii_class = {
  183. __, __, __, __, __, __, __, __,
  184. __, C_WHITE, C_WHITE, __, __, C_WHITE, __, __,
  185. __, __, __, __, __, __, __, __,
  186. __, __, __, __, __, __, __, __,
  187. C_SPACE, C_ETC, C_QUOTE, C_ETC, C_ETC, C_ETC, C_ETC, C_QUOTE,
  188. C_ETC, C_ETC, C_STAR, C_PLUS, C_COMMA, C_MINUS, C_POINT, C_SLASH,
  189. C_ZERO, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT,
  190. C_DIGIT, C_DIGIT, C_COLON, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
  191. C_ETC, C_ABCDF, C_ABCDF, C_ABCDF, C_ABCDF, C_E, C_ABCDF, C_ETC,
  192. C_ETC, C_I, C_ETC, C_ETC, C_ETC, C_ETC, C_N, C_ETC,
  193. C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
  194. C_ETC, C_ETC, C_ETC, C_LSQRB, C_BACKS, C_RSQRB, C_ETC, C_ETC,
  195. C_ETC, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_ETC,
  196. C_ETC, C_LOW_I, C_ETC, C_ETC, C_LOW_L, C_ETC, C_LOW_N, C_ETC,
  197. C_ETC, C_ETC, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ETC, C_ETC,
  198. C_ETC, C_LOW_Y, C_ETC, C_LCURB, C_ETC, C_RCURB, C_ETC, C_ETC
  199. };
  200. static readonly int[,] state_transition_table = {
  201. /*
  202. The state transition table takes the current state and the current symbol,
  203. and returns either a new state or an action. An action is represented as a
  204. negative number. A JSON text is accepted if at the end of the text the
  205. state is OK and if the mode is MODE_DONE.
  206. white ' 1-9 ABCDF etc
  207. space | { } [ ] : , " \ / + - . 0 | a b c d e f l n r s t u | E | * I i y N */
  208. /*start GO*/ {GO,GO,OS,__,AB,__,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,__,__,__,TR,__,__,__,__,__,I1,__,__,V1},
  209. /*ok OK*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
  210. /*object OB*/ {OB,OB,__,EO,__,__,__,__,SB,__,__,__,KB,__,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,__,KB,KB,KB,KB},
  211. /*key KE*/ {KE,KE,__,__,__,__,__,__,SB,__,__,__,KB,__,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,__,KB,KB,KB,KB},
  212. /*colon CO*/ {CO,CO,__,__,__,__,CA,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
  213. /*value VA*/ {VA,VA,OS,__,AB,__,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,NU,__,__,TR,__,__,__,__,__,I1,__,__,V1},
  214. /*array AR*/ {AR,AR,OS,__,AB,AE,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,NU,__,__,TR,__,__,__,__,__,I1,__,__,V1},
  215. /*string ST*/ {ST,__,ST,ST,ST,ST,ST,ST,SE,EX,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST},
  216. /*escape ES*/ {__,__,__,__,__,__,__,__,ST,ST,ST,__,__,__,__,__,__,ST,__,__,__,ST,__,ST,ST,__,ST,U1,__,__,__,__,__,__,__,__},
  217. /*u1 U1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U2,U2,U2,U2,U2,U2,U2,U2,__,__,__,__,__,__,U2,U2,__,__,__,__,__,__},
  218. /*u2 U2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U3,U3,U3,U3,U3,U3,U3,U3,__,__,__,__,__,__,U3,U3,__,__,__,__,__,__},
  219. /*u3 U3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U4,U4,U4,U4,U4,U4,U4,U4,__,__,__,__,__,__,U4,U4,__,__,__,__,__,__},
  220. /*u4 U4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,UC,UC,UC,UC,UC,UC,UC,UC,__,__,__,__,__,__,UC,UC,__,__,__,__,__,__},
  221. /*minus MI*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,ZE,IN,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I1,__,__,__},
  222. /*zero ZE*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,DF,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
  223. /*int IN*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,DF,IN,IN,__,__,__,__,DE,__,__,__,__,__,__,__,__,DE,__,__,__,__,__,__},
  224. /*frac FR*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__,__,__,__,__,__},
  225. /*e E1*/ {__,__,__,__,__,__,__,__,__,__,__,E2,E2,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
  226. /*ex E2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
  227. /*exp E3*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
  228. /*tr T1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T2,__,__,__,__,__,__,__,__,__,__,__},
  229. /*tru T2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T3,__,__,__,__,__,__,__,__},
  230. /*true T3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
  231. /*fa F1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
  232. /*fal F2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F3,__,__,__,__,__,__,__,__,__,__,__,__,__},
  233. /*fals F3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F4,__,__,__,__,__,__,__,__,__,__},
  234. /*false F4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
  235. /*nu N1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N2,__,__,__,__,__,__,__,__},
  236. /*nul N2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N3,__,__,__,__,__,__,__,__,__,__,__,__,__},
  237. /*null N3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__},
  238. /*_. FX*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__,__,__,__,__,__},
  239. /*inval. IV*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
  240. /*unq.key UK*/ {UI,UI,__,__,__,__,UE,__,__,__,__,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,__,UK,UK,UK,UK},
  241. /*unq.ign. UI*/ {UI,UI,__,__,__,__,UE,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
  242. /*i1 I1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I2,__,__,__,__,__,__,__,__,__,__,__,__},
  243. /*i2 I2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I3,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
  244. /*i3 I3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I4,__,__},
  245. /*i4 I4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I5,__,__,__,__,__,__,__,__,__,__,__,__},
  246. /*i5 I5*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I6,__,__},
  247. /*i6 I6*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I7,__,__,__,__,__,__,__,__,__},
  248. /*i7 I7*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,IF,__},
  249. /*v1 V1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,V2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
  250. /*v2 V2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,NN},
  251. };
  252. JavaScriptSerializer serializer;
  253. JavaScriptTypeResolver typeResolver;
  254. int maxJsonLength;
  255. int currentPosition;
  256. int recursionLimit;
  257. int recursionDepth;
  258. Stack <JsonMode> modes;
  259. Stack <object> returnValue;
  260. JsonType jsonType;
  261. bool escaped;
  262. int state;
  263. Stack <string> currentKey;
  264. StringBuilder buffer;
  265. char quoteChar;
  266. public JsonDeserializer (JavaScriptSerializer serializer)
  267. {
  268. this.serializer = serializer;
  269. this.maxJsonLength = serializer.MaxJsonLength;
  270. this.recursionLimit = serializer.RecursionLimit;
  271. this.typeResolver = serializer.TypeResolver;
  272. this.modes = new Stack <JsonMode> ();
  273. this.currentKey = new Stack <string> ();
  274. this.returnValue = new Stack <object> ();
  275. this.state = GO;
  276. this.currentPosition = 0;
  277. this.recursionDepth = 0;
  278. }
  279. public object Deserialize (string input)
  280. {
  281. if (input == null)
  282. throw new ArgumentNullException ("input");
  283. return Deserialize (new StringReader (input));
  284. }
  285. public object Deserialize (TextReader input)
  286. {
  287. if (input == null)
  288. throw new ArgumentNullException ("input");
  289. int value;
  290. buffer = new StringBuilder ();
  291. while (true) {
  292. value = input.Read ();
  293. if (value < 0)
  294. break;
  295. currentPosition++;
  296. if (currentPosition > maxJsonLength)
  297. throw new ArgumentException ("Maximum JSON input length has been exceeded.");
  298. if (!ProcessCharacter ((char) value))
  299. throw new InvalidOperationException ("JSON syntax error.");
  300. }
  301. object topObject = PeekObject ();
  302. if (buffer.Length > 0) {
  303. object result;
  304. if (ParseBuffer (out result)) {
  305. if (topObject != null)
  306. StoreValue (result);
  307. else
  308. PushObject (result);
  309. }
  310. }
  311. if (returnValue.Count > 1)
  312. throw new InvalidOperationException ("JSON syntax error.");
  313. object ret = PopObject ();
  314. return ret;
  315. }
  316. #if DEBUG
  317. void DumpObject (string indent, object obj)
  318. {
  319. if (obj is Dictionary <string, object>) {
  320. Console.WriteLine (indent + "{");
  321. foreach (KeyValuePair <string, object> kvp in (Dictionary <string, object>)obj) {
  322. Console.WriteLine (indent + "\t\"{0}\": ", kvp.Key);
  323. DumpObject (indent + "\t\t", kvp.Value);
  324. }
  325. Console.WriteLine (indent + "}");
  326. } else if (obj is object[]) {
  327. Console.WriteLine (indent + "[");
  328. foreach (object o in (object[])obj)
  329. DumpObject (indent + "\t", o);
  330. Console.WriteLine (indent + "]");
  331. } else if (obj != null)
  332. Console.WriteLine (indent + obj.ToString ());
  333. else
  334. Console.WriteLine ("null");
  335. }
  336. #endif
  337. void DecodeUnicodeChar ()
  338. {
  339. int len = buffer.Length;
  340. if (len < 6)
  341. throw new ArgumentException ("Invalid escaped unicode character specification (" + currentPosition + ")");
  342. int code = Int32.Parse (buffer.ToString ().Substring (len - 4), NumberStyles.HexNumber);
  343. buffer.Length = len - 6;
  344. buffer.Append ((char)code);
  345. }
  346. string GetModeMessage (JsonMode expectedMode)
  347. {
  348. switch (expectedMode) {
  349. case JsonMode.ARRAY:
  350. return "Invalid array passed in, ',' or ']' expected (" + currentPosition + ")";
  351. case JsonMode.KEY:
  352. return "Invalid object passed in, key name or ':' expected (" + currentPosition + ")";
  353. case JsonMode.OBJECT:
  354. return "Invalid object passed in, key value expected (" + currentPosition + ")";
  355. default:
  356. return "Invalid JSON string";
  357. }
  358. }
  359. void PopMode (JsonMode expectedMode)
  360. {
  361. JsonMode mode = PeekMode ();
  362. if (mode != expectedMode)
  363. throw new ArgumentException (GetModeMessage (mode));
  364. modes.Pop ();
  365. }
  366. void PushMode (JsonMode newMode)
  367. {
  368. modes.Push (newMode);
  369. }
  370. JsonMode PeekMode ()
  371. {
  372. if (modes.Count == 0)
  373. return JsonMode.NONE;
  374. return modes.Peek ();
  375. }
  376. void PushObject (object o)
  377. {
  378. returnValue.Push (o);
  379. }
  380. object PopObject (bool notIfLast)
  381. {
  382. int count = returnValue.Count;
  383. if (count == 0)
  384. return null;
  385. if (notIfLast && count == 1)
  386. return null;
  387. return returnValue.Pop ();
  388. }
  389. object PopObject ()
  390. {
  391. return PopObject (false);
  392. }
  393. object PeekObject ()
  394. {
  395. if (returnValue.Count == 0)
  396. return null;
  397. return returnValue.Peek ();
  398. }
  399. void RemoveLastCharFromBuffer ()
  400. {
  401. int len = buffer.Length;
  402. if (len == 0)
  403. return;
  404. buffer.Length = len - 1;
  405. }
  406. bool ParseBuffer (out object result)
  407. {
  408. result = null;
  409. if (jsonType == JsonType.NONE) {
  410. buffer.Length = 0;
  411. return false;
  412. }
  413. string s = buffer.ToString ();
  414. bool converted = true;
  415. int intValue;
  416. long longValue;
  417. decimal decimalValue;
  418. double doubleValue;
  419. switch (jsonType) {
  420. case JsonType.INTEGER:
  421. /* MS AJAX.NET JSON parser promotes big integers to double */
  422. if (Int32.TryParse (s, out intValue))
  423. result = intValue;
  424. else if (Int64.TryParse (s, out longValue))
  425. result = longValue;
  426. else if (Decimal.TryParse (s, out decimalValue))
  427. result = decimalValue;
  428. else if (Double.TryParse (s, out doubleValue))
  429. result = doubleValue;
  430. else
  431. converted = false;
  432. break;
  433. case JsonType.FLOAT:
  434. if (Decimal.TryParse (s, out decimalValue))
  435. result = decimalValue;
  436. else if (Double.TryParse (s, out doubleValue))
  437. result = doubleValue;
  438. else
  439. converted = false;
  440. break;
  441. case JsonType.TRUE:
  442. if (String.Compare (s, "true", StringComparison.Ordinal) == 0)
  443. result = true;
  444. else
  445. converted = false;
  446. break;
  447. case JsonType.FALSE:
  448. if (String.Compare (s, "false", StringComparison.Ordinal) == 0)
  449. result = false;
  450. else
  451. converted = false;
  452. break;
  453. case JsonType.NULL:
  454. if (String.Compare (s, "null", StringComparison.Ordinal) != 0)
  455. converted = false;
  456. break;
  457. case JsonType.STRING:
  458. if (s.StartsWith ("/Date(", StringComparison.Ordinal) && s.EndsWith (")/", StringComparison.Ordinal)) {
  459. long javaScriptTicks = Convert.ToInt64 (s.Substring (6, s.Length - 8));
  460. result = new DateTime ((javaScriptTicks * 10000) + JsonSerializer.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  461. } else
  462. result = s;
  463. break;
  464. default:
  465. throw new InvalidOperationException (String.Format ("Internal error: unexpected JsonType ({0})", jsonType));
  466. }
  467. if (!converted)
  468. throw new ArgumentException ("Invalid JSON primitive: " + s);
  469. buffer.Length = 0;
  470. return true;
  471. }
  472. bool ProcessCharacter (char ch)
  473. {
  474. int next_class, next_state;
  475. if (ch >= 128)
  476. next_class = C_ETC;
  477. else {
  478. next_class = ascii_class [ch];
  479. if (next_class <= UNIVERSAL_ERROR)
  480. return false;
  481. }
  482. if (escaped) {
  483. escaped = false;
  484. RemoveLastCharFromBuffer ();
  485. switch (ch) {
  486. case 'b':
  487. buffer.Append ('\b');
  488. break;
  489. case 'f':
  490. buffer.Append ('\f');
  491. break;
  492. case 'n':
  493. buffer.Append ('\n');
  494. break;
  495. case 'r':
  496. buffer.Append ('\r');
  497. break;
  498. case 't':
  499. buffer.Append ('\t');
  500. break;
  501. case '"':
  502. case '\\':
  503. case '/':
  504. buffer.Append (ch);
  505. break;
  506. case 'u':
  507. buffer.Append ("\\u");
  508. break;
  509. default:
  510. return false;
  511. }
  512. } else if (jsonType != JsonType.NONE || !(next_class == C_SPACE || next_class == C_WHITE))
  513. buffer.Append (ch);
  514. next_state = state_transition_table [state, next_class];
  515. if (next_state >= 0) {
  516. state = next_state;
  517. return true;
  518. }
  519. object result;
  520. /* An action to perform */
  521. switch (next_state) {
  522. case UC: /* Unicode character */
  523. DecodeUnicodeChar ();
  524. state = ST;
  525. break;
  526. case EX: /* Escaped character */
  527. escaped = true;
  528. state = ES;
  529. break;
  530. case MX: /* integer detected by minus */
  531. jsonType = JsonType.INTEGER;
  532. state = MI;
  533. break;
  534. case PX: /* integer detected by plus */
  535. jsonType = JsonType.INTEGER;
  536. state = MI;
  537. break;
  538. case ZX: /* integer detected by zero */
  539. jsonType = JsonType.INTEGER;
  540. state = ZE;
  541. break;
  542. case IX: /* integer detected by 1-9 */
  543. jsonType = JsonType.INTEGER;
  544. state = IN;
  545. break;
  546. case DE: /* floating point number detected by exponent*/
  547. jsonType = JsonType.FLOAT;
  548. state = E1;
  549. break;
  550. case DF: /* floating point number detected by fraction */
  551. jsonType = JsonType.FLOAT;
  552. state = FX;
  553. break;
  554. case SB: /* string begin " or ' */
  555. buffer.Length = 0;
  556. quoteChar = ch;
  557. jsonType = JsonType.STRING;
  558. state = ST;
  559. break;
  560. case KB: /* unquoted key name begin */
  561. jsonType = JsonType.STRING;
  562. state = UK;
  563. break;
  564. case UE: /* unquoted key name end ':' */
  565. RemoveLastCharFromBuffer ();
  566. if (ParseBuffer (out result))
  567. StoreKey (result);
  568. jsonType = JsonType.NONE;
  569. PopMode (JsonMode.KEY);
  570. PushMode (JsonMode.OBJECT);
  571. state = VA;
  572. buffer.Length = 0;
  573. break;
  574. case NU: /* n */
  575. jsonType = JsonType.NULL;
  576. state = N1;
  577. break;
  578. case FA: /* f */
  579. jsonType = JsonType.FALSE;
  580. state = F1;
  581. break;
  582. case TR: /* t */
  583. jsonType = JsonType.TRUE;
  584. state = T1;
  585. break;
  586. case EO: /* empty } */
  587. result = PopObject (true);
  588. if (result != null)
  589. StoreValue (result);
  590. PopMode (JsonMode.KEY);
  591. state = OK;
  592. break;
  593. case OE: /* } */
  594. RemoveLastCharFromBuffer ();
  595. if (ParseBuffer (out result))
  596. StoreValue (result);
  597. result = PopObject (true);
  598. if (result != null)
  599. StoreValue (result);
  600. PopMode (JsonMode.OBJECT);
  601. jsonType = JsonType.NONE;
  602. state = OK;
  603. break;
  604. case AE: /* ] */
  605. RemoveLastCharFromBuffer ();
  606. if (ParseBuffer (out result))
  607. StoreValue (result);
  608. PopMode (JsonMode.ARRAY);
  609. result = PopObject (true);
  610. if (result != null)
  611. StoreValue (result);
  612. jsonType = JsonType.NONE;
  613. state = OK;
  614. break;
  615. case OS: /* { */
  616. RemoveLastCharFromBuffer ();
  617. CreateObject ();
  618. PushMode (JsonMode.KEY);
  619. state = OB;
  620. break;
  621. case AB: /* [ */
  622. RemoveLastCharFromBuffer ();
  623. CreateArray ();
  624. PushMode (JsonMode.ARRAY);
  625. state = AR;
  626. break;
  627. case SE: /* string end " or ' */
  628. if (ch == quoteChar) {
  629. RemoveLastCharFromBuffer ();
  630. switch (PeekMode ()) {
  631. case JsonMode.KEY:
  632. if (ParseBuffer (out result))
  633. StoreKey (result);
  634. jsonType = JsonType.NONE;
  635. state = CO;
  636. buffer.Length = 0;
  637. break;
  638. case JsonMode.ARRAY:
  639. case JsonMode.OBJECT:
  640. if (ParseBuffer (out result))
  641. StoreValue (result);
  642. jsonType = JsonType.NONE;
  643. state = OK;
  644. break;
  645. case JsonMode.NONE: /* A stand-alone string */
  646. jsonType = JsonType.STRING;
  647. state = IV; /* the rest of input is invalid */
  648. if (ParseBuffer (out result))
  649. PushObject (result);
  650. break;
  651. default:
  652. throw new ArgumentException ("Syntax error: string in unexpected place.");
  653. }
  654. }
  655. break;
  656. case CM: /* , */
  657. RemoveLastCharFromBuffer ();
  658. // With MS.AJAX, a comma resets the recursion depth
  659. recursionDepth = 0;
  660. bool doStore = ParseBuffer (out result);
  661. switch (PeekMode ()) {
  662. case JsonMode.OBJECT:
  663. if (doStore)
  664. StoreValue (result);
  665. PopMode (JsonMode.OBJECT);
  666. PushMode (JsonMode.KEY);
  667. jsonType = JsonType.NONE;
  668. state = KE;
  669. break;
  670. case JsonMode.ARRAY:
  671. jsonType = JsonType.NONE;
  672. state = VA;
  673. if (doStore)
  674. StoreValue (result);
  675. break;
  676. default:
  677. throw new ArgumentException ("Syntax error: unexpected comma.");
  678. }
  679. break;
  680. case CA: /* : */
  681. RemoveLastCharFromBuffer ();
  682. // With MS.AJAX a colon increases recursion depth
  683. if (++recursionDepth >= recursionLimit)
  684. throw new ArgumentException ("Recursion limit has been reached on parsing input.");
  685. PopMode (JsonMode.KEY);
  686. PushMode (JsonMode.OBJECT);
  687. state = VA;
  688. break;
  689. case IF: /* Infinity */
  690. case NN: /* NaN */
  691. jsonType = JsonType.FLOAT;
  692. switch (PeekMode ()) {
  693. case JsonMode.ARRAY:
  694. case JsonMode.OBJECT:
  695. if (ParseBuffer (out result))
  696. StoreValue (result);
  697. jsonType = JsonType.NONE;
  698. state = OK;
  699. break;
  700. case JsonMode.NONE: /* A stand-alone NaN/Infinity */
  701. jsonType = JsonType.FLOAT;
  702. state = IV; /* the rest of input is invalid */
  703. if (ParseBuffer (out result))
  704. PushObject (result);
  705. break;
  706. default:
  707. throw new ArgumentException ("Syntax error: misplaced NaN/Infinity.");
  708. }
  709. buffer.Length = 0;
  710. break;
  711. default:
  712. throw new ArgumentException (GetModeMessage (PeekMode ()));
  713. }
  714. return true;
  715. }
  716. void CreateArray ()
  717. {
  718. var arr = new ArrayList ();
  719. PushObject (arr);
  720. }
  721. void CreateObject ()
  722. {
  723. var dict = new Dictionary <string, object> ();
  724. PushObject (dict);
  725. }
  726. void StoreKey (object o)
  727. {
  728. string key = o as string;
  729. if (key != null)
  730. key = key.Trim ();
  731. if (String.IsNullOrEmpty (key))
  732. throw new InvalidOperationException ("Internal error: key is null, empty or not a string.");
  733. currentKey.Push (key);
  734. Dictionary <string, object> dict = PeekObject () as Dictionary <string, object>;
  735. if (dict == null)
  736. throw new InvalidOperationException ("Internal error: current object is not a dictionary.");
  737. /* MS AJAX.NET silently overwrites existing currentKey value */
  738. dict [key] = null;
  739. }
  740. void StoreValue (object o)
  741. {
  742. Dictionary <string, object> dict = PeekObject () as Dictionary <string, object>;
  743. if (dict == null) {
  744. ArrayList arr = PeekObject () as ArrayList;
  745. if (arr == null)
  746. throw new InvalidOperationException ("Internal error: current object is not a dictionary or an array.");
  747. arr.Add (o);
  748. return;
  749. }
  750. string key;
  751. if (currentKey.Count == 0)
  752. key = null;
  753. else
  754. key = currentKey.Pop ();
  755. if (String.IsNullOrEmpty (key))
  756. throw new InvalidOperationException ("Internal error: object is a dictionary, but no key present.");
  757. dict [key] = o;
  758. }
  759. }
  760. }