PetaJson.cs 132 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372
  1. // PetaJson v0.5 - A simple but flexible Json library in a single .cs file.
  2. //
  3. // Copyright (C) 2014 Topten Software (contact@toptensoftware.com) All rights reserved.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this product
  6. // except in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed under the
  11. // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  12. // either express or implied. See the License for the specific language governing permissions
  13. // and limitations under the License.
  14. // Define PETAJSON_NO_DYNAMIC to disable Expando support
  15. // Define PETAJSON_NO_EMIT to disable Reflection.Emit
  16. // Define PETAJSON_NO_DATACONTRACT to disable support for [DataContract]/[DataMember]
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Linq;
  20. using System.Text;
  21. using System.IO;
  22. using System.Reflection;
  23. using System.Globalization;
  24. using System.Collections;
  25. using System.Threading;
  26. #if !PETAJSON_NO_DYNAMIC
  27. using System.Dynamic;
  28. #endif
  29. #if !PETAJSON_NO_EMIT
  30. using System.Reflection.Emit;
  31. #endif
  32. #if !PETAJSON_NO_DATACONTRACT
  33. using System.Runtime.Serialization;
  34. #endif
  35. namespace PetaJson
  36. {
  37. // Pass to format/write/parse functions to override defaults
  38. [Flags]
  39. public enum JsonOptions
  40. {
  41. None = 0,
  42. WriteWhitespace = 0x00000001,
  43. DontWriteWhitespace = 0x00000002,
  44. StrictParser = 0x00000004,
  45. NonStrictParser = 0x00000008,
  46. Flush = 0x00000010,
  47. AutoSavePreviousVersion = 0x00000020, // Use "SavePreviousVersions" static property
  48. SavePreviousVersion = 0x00000040, // Always save previous version
  49. }
  50. // API
  51. public static class Json
  52. {
  53. static Json()
  54. {
  55. WriteWhitespaceDefault = true;
  56. StrictParserDefault = false;
  57. #if !PETAJSON_NO_EMIT
  58. Json.SetFormatterResolver(Internal.Emit.MakeFormatter);
  59. Json.SetParserResolver(Internal.Emit.MakeParser);
  60. Json.SetIntoParserResolver(Internal.Emit.MakeIntoParser);
  61. #endif
  62. }
  63. // Pretty format default
  64. public static bool WriteWhitespaceDefault
  65. {
  66. get;
  67. set;
  68. }
  69. // Strict parser
  70. public static bool StrictParserDefault
  71. {
  72. get;
  73. set;
  74. }
  75. // Write an object to a text writer
  76. public static void Write(TextWriter w, object o, JsonOptions options = JsonOptions.None)
  77. {
  78. var writer = new Internal.Writer(w, ResolveOptions(options));
  79. writer.WriteValue(o);
  80. }
  81. static void DeleteFile(string filename)
  82. {
  83. try
  84. {
  85. System.IO.File.Delete(filename);
  86. }
  87. catch
  88. {
  89. // Don't care
  90. }
  91. }
  92. public static bool SavePreviousVersions
  93. {
  94. get;
  95. set;
  96. }
  97. // Write a file atomically by writing to a temp file and then renaming it - prevents corrupted files if crash
  98. // in middle of writing file.
  99. public static void WriteFileAtomic(string filename, object o, JsonOptions options = JsonOptions.None, string backupFilename = null)
  100. {
  101. var tempName = filename + ".tmp";
  102. try
  103. {
  104. // Write the temp file
  105. WriteFile(tempName, o, (options | JsonOptions.Flush));
  106. if (System.IO.File.Exists(filename))
  107. {
  108. bool savePreviousVersion = false;
  109. if ((options & JsonOptions.AutoSavePreviousVersion)!=0)
  110. {
  111. savePreviousVersion = SavePreviousVersions;
  112. }
  113. else if ((options & JsonOptions.SavePreviousVersion)!=0)
  114. {
  115. savePreviousVersion = true;
  116. }
  117. // Work out backup filename
  118. if (savePreviousVersion)
  119. {
  120. // Make sure have a backup filename
  121. if (backupFilename == null)
  122. {
  123. backupFilename = filename + ".previous";
  124. }
  125. }
  126. else
  127. {
  128. // No backup
  129. backupFilename = null;
  130. }
  131. // Replace it
  132. File.Replace(tempName, filename, backupFilename);
  133. }
  134. else
  135. {
  136. // Rename it
  137. File.Move(tempName, filename);
  138. }
  139. }
  140. catch
  141. {
  142. DeleteFile(tempName);
  143. throw;
  144. }
  145. }
  146. // Write an object to a file
  147. public static void WriteFile(string filename, object o, JsonOptions options = JsonOptions.None)
  148. {
  149. using (var w = new StreamWriter(filename))
  150. {
  151. Write(w, o, options);
  152. if ((options & JsonOptions.Flush) != 0)
  153. {
  154. w.Flush();
  155. w.BaseStream.Flush();
  156. }
  157. }
  158. }
  159. // Format an object as a json string
  160. public static string Format(object o, JsonOptions options = JsonOptions.None)
  161. {
  162. var sw = new StringWriter();
  163. var writer = new Internal.Writer(sw, ResolveOptions(options));
  164. writer.WriteValue(o);
  165. return sw.ToString();
  166. }
  167. // Parse an object of specified type from a text reader
  168. public static object Parse(TextReader r, Type type, JsonOptions options = JsonOptions.None)
  169. {
  170. Internal.Reader reader = null;
  171. try
  172. {
  173. reader = new Internal.Reader(r, ResolveOptions(options));
  174. var retv = reader.Parse(type);
  175. reader.CheckEOF();
  176. return retv;
  177. }
  178. catch (Exception x)
  179. {
  180. var loc = reader == null ? new JsonLineOffset() : reader.CurrentTokenPosition;
  181. Console.WriteLine("Exception thrown while parsing JSON at {0}, context:{1}\n{2}", loc, reader.Context, x.ToString());
  182. throw new JsonParseException(x, reader.Context, loc);
  183. }
  184. }
  185. // Parse an object of specified type from a text reader
  186. public static T Parse<T>(TextReader r, JsonOptions options = JsonOptions.None)
  187. {
  188. return (T)Parse(r, typeof(T), options);
  189. }
  190. // Parse from text reader into an already instantied object
  191. public static void ParseInto(TextReader r, Object into, JsonOptions options = JsonOptions.None)
  192. {
  193. if (into == null)
  194. throw new NullReferenceException();
  195. if (into.GetType().IsValueType)
  196. throw new InvalidOperationException("Can't ParseInto a value type");
  197. Internal.Reader reader = null;
  198. try
  199. {
  200. reader = new Internal.Reader(r, ResolveOptions(options));
  201. reader.ParseInto(into);
  202. reader.CheckEOF();
  203. }
  204. catch (Exception x)
  205. {
  206. var loc = reader == null ? new JsonLineOffset() : reader.CurrentTokenPosition;
  207. Console.WriteLine("Exception thrown while parsing JSON at {0}, context:{1}\n{2}", loc, reader.Context, x.ToString());
  208. throw new JsonParseException(x,reader.Context,loc);
  209. }
  210. }
  211. // Parse an object of specified type from a file
  212. public static object ParseFile(string filename, Type type, JsonOptions options = JsonOptions.None)
  213. {
  214. using (var r = new StreamReader(filename))
  215. {
  216. return Parse(r, type, options);
  217. }
  218. }
  219. // Parse an object of specified type from a file
  220. public static T ParseFile<T>(string filename, JsonOptions options = JsonOptions.None)
  221. {
  222. using (var r = new StreamReader(filename))
  223. {
  224. return Parse<T>(r, options);
  225. }
  226. }
  227. // Parse from file into an already instantied object
  228. public static void ParseFileInto(string filename, Object into, JsonOptions options = JsonOptions.None)
  229. {
  230. using (var r = new StreamReader(filename))
  231. {
  232. ParseInto(r, into, options);
  233. }
  234. }
  235. // Parse an object from a string
  236. public static object Parse(string data, Type type, JsonOptions options = JsonOptions.None)
  237. {
  238. return Parse(new StringReader(data), type, options);
  239. }
  240. // Parse an object from a string
  241. public static T Parse<T>(string data, JsonOptions options = JsonOptions.None)
  242. {
  243. return (T)Parse<T>(new StringReader(data), options);
  244. }
  245. // Parse from string into an already instantiated object
  246. public static void ParseInto(string data, Object into, JsonOptions options = JsonOptions.None)
  247. {
  248. ParseInto(new StringReader(data), into, options);
  249. }
  250. // Create a clone of an object
  251. public static T Clone<T>(T source)
  252. {
  253. return (T)Reparse(source.GetType(), source);
  254. }
  255. // Create a clone of an object (untyped)
  256. public static object Clone(object source)
  257. {
  258. return Reparse(source.GetType(), source);
  259. }
  260. // Clone an object into another instance
  261. public static void CloneInto(object dest, object source)
  262. {
  263. ReparseInto(dest, source);
  264. }
  265. // Reparse an object by writing to a stream and re-reading (possibly
  266. // as a different type).
  267. public static object Reparse(Type type, object source)
  268. {
  269. if (source == null)
  270. return null;
  271. var ms = new MemoryStream();
  272. try
  273. {
  274. // Write
  275. var w = new StreamWriter(ms);
  276. Json.Write(w, source);
  277. w.Flush();
  278. // Read
  279. ms.Seek(0, SeekOrigin.Begin);
  280. var r = new StreamReader(ms);
  281. return Json.Parse(r, type);
  282. }
  283. finally
  284. {
  285. ms.Dispose();
  286. }
  287. }
  288. // Typed version of above
  289. public static T Reparse<T>(object source)
  290. {
  291. return (T)Reparse(typeof(T), source);
  292. }
  293. // Reparse one object into another object
  294. public static void ReparseInto(object dest, object source)
  295. {
  296. var ms = new MemoryStream();
  297. try
  298. {
  299. // Write
  300. var w = new StreamWriter(ms);
  301. Json.Write(w, source);
  302. w.Flush();
  303. // Read
  304. ms.Seek(0, SeekOrigin.Begin);
  305. var r = new StreamReader(ms);
  306. Json.ParseInto(r, dest);
  307. }
  308. finally
  309. {
  310. ms.Dispose();
  311. }
  312. }
  313. // Register a callback that can format a value of a particular type into json
  314. public static void RegisterFormatter(Type type, Action<IJsonWriter, object> formatter)
  315. {
  316. Internal.Writer._formatters[type] = formatter;
  317. }
  318. // Typed version of above
  319. public static void RegisterFormatter<T>(Action<IJsonWriter, T> formatter)
  320. {
  321. RegisterFormatter(typeof(T), (w, o) => formatter(w, (T)o));
  322. }
  323. // Register a parser for a specified type
  324. public static void RegisterParser(Type type, Func<IJsonReader, Type, object> parser)
  325. {
  326. Internal.Reader._parsers.Set(type, parser);
  327. }
  328. // Register a typed parser
  329. public static void RegisterParser<T>(Func<IJsonReader, Type, T> parser)
  330. {
  331. RegisterParser(typeof(T), (r, t) => parser(r, t));
  332. }
  333. // Simpler version for simple types
  334. public static void RegisterParser(Type type, Func<object, object> parser)
  335. {
  336. RegisterParser(type, (r, t) => r.ReadLiteral(parser));
  337. }
  338. // Simpler and typesafe parser for simple types
  339. public static void RegisterParser<T>(Func<object, T> parser)
  340. {
  341. RegisterParser(typeof(T), literal => parser(literal));
  342. }
  343. // Register an into parser
  344. public static void RegisterIntoParser(Type type, Action<IJsonReader, object> parser)
  345. {
  346. Internal.Reader._intoParsers.Set(type, parser);
  347. }
  348. // Register an into parser
  349. public static void RegisterIntoParser<T>(Action<IJsonReader, object> parser)
  350. {
  351. RegisterIntoParser(typeof(T), parser);
  352. }
  353. // Register a factory for instantiating objects (typically abstract classes)
  354. // Callback will be invoked for each key in the dictionary until it returns an object
  355. // instance and which point it will switch to serialization using reflection
  356. public static void RegisterTypeFactory(Type type, Func<IJsonReader, string, object> factory)
  357. {
  358. Internal.Reader._typeFactories.Set(type, factory);
  359. }
  360. // Register a callback to provide a formatter for a newly encountered type
  361. public static void SetFormatterResolver(Func<Type, Action<IJsonWriter, object>> resolver)
  362. {
  363. Internal.Writer._formatterResolver = resolver;
  364. }
  365. // Register a callback to provide a parser for a newly encountered value type
  366. public static void SetParserResolver(Func<Type, Func<IJsonReader, Type, object>> resolver)
  367. {
  368. Internal.Reader._parserResolver = resolver;
  369. }
  370. // Register a callback to provide a parser for a newly encountered reference type
  371. public static void SetIntoParserResolver(Func<Type, Action<IJsonReader, object>> resolver)
  372. {
  373. Internal.Reader._intoParserResolver = resolver;
  374. }
  375. public static bool WalkPath(this IDictionary<string, object> This, string Path, bool create, Func<IDictionary<string,object>,string, bool> leafCallback)
  376. {
  377. // Walk the path
  378. var parts = Path.Split('.');
  379. for (int i = 0; i < parts.Length-1; i++)
  380. {
  381. object val;
  382. if (!This.TryGetValue(parts[i], out val))
  383. {
  384. if (!create)
  385. return false;
  386. val = new Dictionary<string, object>();
  387. This[parts[i]] = val;
  388. }
  389. This = (IDictionary<string,object>)val;
  390. }
  391. // Process the leaf
  392. return leafCallback(This, parts[parts.Length-1]);
  393. }
  394. public static bool PathExists(this IDictionary<string, object> This, string Path)
  395. {
  396. return This.WalkPath(Path, false, (dict, key) => dict.ContainsKey(key));
  397. }
  398. public static object GetPath(this IDictionary<string, object> This, Type type, string Path, object def)
  399. {
  400. This.WalkPath(Path, false, (dict, key) =>
  401. {
  402. object val;
  403. if (dict.TryGetValue(key, out val))
  404. {
  405. if (val == null)
  406. def = val;
  407. else if (type.IsAssignableFrom(val.GetType()))
  408. def = val;
  409. else
  410. def = Reparse(type, val);
  411. }
  412. return true;
  413. });
  414. return def;
  415. }
  416. // Ensure there's an object of type T at specified path
  417. public static T GetObjectAtPath<T>(this IDictionary<string, object> This, string Path) where T:class,new()
  418. {
  419. T retVal = null;
  420. This.WalkPath(Path, true, (dict, key) =>
  421. {
  422. object val;
  423. dict.TryGetValue(key, out val);
  424. retVal = val as T;
  425. if (retVal == null)
  426. {
  427. retVal = val == null ? new T() : Reparse<T>(val);
  428. dict[key] = retVal;
  429. }
  430. return true;
  431. });
  432. return retVal;
  433. }
  434. public static T GetPath<T>(this IDictionary<string, object> This, string Path, T def = default(T))
  435. {
  436. return (T)This.GetPath(typeof(T), Path, def);
  437. }
  438. public static void SetPath(this IDictionary<string, object> This, string Path, object value)
  439. {
  440. This.WalkPath(Path, true, (dict, key) => { dict[key] = value; return true; });
  441. }
  442. // Resolve passed options
  443. static JsonOptions ResolveOptions(JsonOptions options)
  444. {
  445. JsonOptions resolved = JsonOptions.None;
  446. if ((options & (JsonOptions.WriteWhitespace|JsonOptions.DontWriteWhitespace))!=0)
  447. resolved |= options & (JsonOptions.WriteWhitespace | JsonOptions.DontWriteWhitespace);
  448. else
  449. resolved |= WriteWhitespaceDefault ? JsonOptions.WriteWhitespace : JsonOptions.DontWriteWhitespace;
  450. if ((options & (JsonOptions.StrictParser | JsonOptions.NonStrictParser)) != 0)
  451. resolved |= options & (JsonOptions.StrictParser | JsonOptions.NonStrictParser);
  452. else
  453. resolved |= StrictParserDefault ? JsonOptions.StrictParser : JsonOptions.NonStrictParser;
  454. return resolved;
  455. }
  456. }
  457. // Called before loading via reflection
  458. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  459. public interface IJsonLoading
  460. {
  461. void OnJsonLoading(IJsonReader r);
  462. }
  463. // Called after loading via reflection
  464. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  465. public interface IJsonLoaded
  466. {
  467. void OnJsonLoaded(IJsonReader r);
  468. }
  469. // Called for each field while loading from reflection
  470. // Return true if handled
  471. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  472. public interface IJsonLoadField
  473. {
  474. bool OnJsonField(IJsonReader r, string key);
  475. }
  476. // Called when about to write using reflection
  477. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  478. public interface IJsonWriting
  479. {
  480. void OnJsonWriting(IJsonWriter w);
  481. }
  482. // Called after written using reflection
  483. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  484. public interface IJsonWritten
  485. {
  486. void OnJsonWritten(IJsonWriter w);
  487. }
  488. // Describes the current literal in the json stream
  489. public enum LiteralKind
  490. {
  491. None,
  492. String,
  493. Null,
  494. True,
  495. False,
  496. SignedInteger,
  497. UnsignedInteger,
  498. FloatingPoint,
  499. }
  500. // Passed to registered parsers
  501. [Obfuscation(Exclude=true, ApplyToMembers=true)]
  502. public interface IJsonReader
  503. {
  504. object Parse(Type type);
  505. T Parse<T>();
  506. void ParseInto(object into);
  507. object ReadLiteral(Func<object, object> converter);
  508. void ParseDictionary(Action<string> callback);
  509. void ParseArray(Action callback);
  510. LiteralKind GetLiteralKind();
  511. string GetLiteralString();
  512. void NextToken();
  513. }
  514. // Passed to registered formatters
  515. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  516. public interface IJsonWriter
  517. {
  518. void WriteStringLiteral(string str);
  519. void WriteRaw(string str);
  520. void WriteArray(Action callback);
  521. void WriteDictionary(Action callback);
  522. void WriteValue(object value);
  523. void WriteElement();
  524. void WriteKey(string key);
  525. void WriteKeyNoEscaping(string key);
  526. }
  527. // Exception thrown for any parse error
  528. public class JsonParseException : Exception
  529. {
  530. public JsonParseException(Exception inner, string context, JsonLineOffset position) :
  531. base(string.Format("JSON parse error at {0}{1} - {2}", position, string.IsNullOrEmpty(context) ? "" : string.Format(", context {0}", context), inner.Message), inner)
  532. {
  533. Position = position;
  534. Context = context;
  535. }
  536. public JsonLineOffset Position;
  537. public string Context;
  538. }
  539. // Represents a line and character offset position in the source Json
  540. public struct JsonLineOffset
  541. {
  542. public int Line;
  543. public int Offset;
  544. public override string ToString()
  545. {
  546. return string.Format("line {0}, character {1}", Line + 1, Offset + 1);
  547. }
  548. }
  549. // Used to decorate fields and properties that should be serialized
  550. //
  551. // - [Json] on class or struct causes all public fields and properties to be serialized
  552. // - [Json] on a public or non-public field or property causes that member to be serialized
  553. // - [JsonExclude] on a field or property causes that field to be not serialized
  554. // - A class or struct with no [Json] attribute has all public fields/properties serialized
  555. // - A class or struct with no [Json] attribute but a [Json] attribute on one or more members only serializes those members
  556. //
  557. // Use [Json("keyname")] to explicitly specify the key to be used
  558. // [Json] without the keyname will be serialized using the name of the member with the first letter lowercased.
  559. //
  560. // [Json(KeepInstance=true)] causes container/subobject types to be serialized into the existing member instance (if not null)
  561. //
  562. // You can also use the system supplied DataContract and DataMember attributes. They'll only be used if there
  563. // are no PetaJson attributes on the class or it's members. You must specify DataContract on the type and
  564. // DataMember on any fields/properties that require serialization. There's no need for exclude attribute.
  565. // When using DataMember, the name of the field or property is used as is - the first letter is left in upper case
  566. //
  567. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field)]
  568. public class JsonAttribute : Attribute
  569. {
  570. public JsonAttribute()
  571. {
  572. _key = null;
  573. }
  574. public JsonAttribute(string key)
  575. {
  576. _key = key;
  577. }
  578. // Key used to save this field/property
  579. string _key;
  580. public string Key
  581. {
  582. get { return _key; }
  583. }
  584. // If true uses ParseInto to parse into the existing object instance
  585. // If false, creates a new instance as assigns it to the property
  586. public bool KeepInstance
  587. {
  588. get;
  589. set;
  590. }
  591. // If true, the property will be loaded, but not saved
  592. // Use to upgrade deprecated persisted settings, but not
  593. // write them back out again
  594. public bool Deprecated
  595. {
  596. get;
  597. set;
  598. }
  599. }
  600. // See comments for JsonAttribute above
  601. [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
  602. public class JsonExcludeAttribute : Attribute
  603. {
  604. public JsonExcludeAttribute()
  605. {
  606. }
  607. }
  608. // Apply to enum values to specify which enum value to select
  609. // if the supplied json value doesn't match any.
  610. // If not found throws an exception
  611. // eg, any unknown values in the json will be mapped to Fruit.unknown
  612. //
  613. // [JsonUnknown(Fruit.unknown)]
  614. // enum Fruit
  615. // {
  616. // unknown,
  617. // Apple,
  618. // Pear,
  619. // }
  620. [AttributeUsage(AttributeTargets.Enum)]
  621. public class JsonUnknownAttribute : Attribute
  622. {
  623. public JsonUnknownAttribute(object unknownValue)
  624. {
  625. UnknownValue = unknownValue;
  626. }
  627. public object UnknownValue
  628. {
  629. get;
  630. private set;
  631. }
  632. }
  633. namespace Internal
  634. {
  635. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  636. public enum Token
  637. {
  638. EOF,
  639. Identifier,
  640. Literal,
  641. OpenBrace,
  642. CloseBrace,
  643. OpenSquare,
  644. CloseSquare,
  645. Equal,
  646. Colon,
  647. SemiColon,
  648. Comma,
  649. }
  650. // Helper to create instances but include the type name in the thrown exception
  651. public static class DecoratingActivator
  652. {
  653. public static object CreateInstance(Type t)
  654. {
  655. try
  656. {
  657. return Activator.CreateInstance(t);
  658. }
  659. catch (Exception x)
  660. {
  661. throw new InvalidOperationException(string.Format("Failed to create instance of type '{0}'", t.FullName), x);
  662. }
  663. }
  664. }
  665. public class Reader : IJsonReader
  666. {
  667. static Reader()
  668. {
  669. // Setup default resolvers
  670. _parserResolver = ResolveParser;
  671. _intoParserResolver = ResolveIntoParser;
  672. Func<IJsonReader, Type, object> simpleConverter = (reader, type) =>
  673. {
  674. return reader.ReadLiteral(literal => Convert.ChangeType(literal, type, CultureInfo.InvariantCulture));
  675. };
  676. Func<IJsonReader, Type, object> numberConverter = (reader, type) =>
  677. {
  678. switch (reader.GetLiteralKind())
  679. {
  680. case LiteralKind.SignedInteger:
  681. case LiteralKind.UnsignedInteger:
  682. case LiteralKind.FloatingPoint:
  683. object val = Convert.ChangeType(reader.GetLiteralString(), type, CultureInfo.InvariantCulture);
  684. reader.NextToken();
  685. return val;
  686. }
  687. throw new InvalidDataException("expected a numeric literal");
  688. };
  689. // Default type handlers
  690. _parsers.Set(typeof(string), simpleConverter);
  691. _parsers.Set(typeof(char), simpleConverter);
  692. _parsers.Set(typeof(bool), simpleConverter);
  693. _parsers.Set(typeof(byte), numberConverter);
  694. _parsers.Set(typeof(sbyte), numberConverter);
  695. _parsers.Set(typeof(short), numberConverter);
  696. _parsers.Set(typeof(ushort), numberConverter);
  697. _parsers.Set(typeof(int), numberConverter);
  698. _parsers.Set(typeof(uint), numberConverter);
  699. _parsers.Set(typeof(long), numberConverter);
  700. _parsers.Set(typeof(ulong), numberConverter);
  701. _parsers.Set(typeof(decimal), numberConverter);
  702. _parsers.Set(typeof(float), numberConverter);
  703. _parsers.Set(typeof(double), numberConverter);
  704. _parsers.Set(typeof(DateTime), (reader, type) =>
  705. {
  706. return reader.ReadLiteral(literal => Utils.FromUnixMilliseconds((long)Convert.ChangeType(literal, typeof(long), CultureInfo.InvariantCulture)));
  707. });
  708. _parsers.Set(typeof(byte[]), (reader, type) =>
  709. {
  710. return reader.ReadLiteral(literal => Convert.FromBase64String((string)Convert.ChangeType(literal, typeof(string), CultureInfo.InvariantCulture)));
  711. });
  712. }
  713. public Reader(TextReader r, JsonOptions options)
  714. {
  715. _tokenizer = new Tokenizer(r, options);
  716. _options = options;
  717. }
  718. Tokenizer _tokenizer;
  719. JsonOptions _options;
  720. List<string> _contextStack = new List<string>();
  721. public string Context
  722. {
  723. get
  724. {
  725. return string.Join(".", _contextStack);
  726. }
  727. }
  728. static Action<IJsonReader, object> ResolveIntoParser(Type type)
  729. {
  730. var ri = ReflectionInfo.GetReflectionInfo(type);
  731. if (ri != null)
  732. return ri.ParseInto;
  733. else
  734. return null;
  735. }
  736. static Func<IJsonReader, Type, object> ResolveParser(Type type)
  737. {
  738. // See if the Type has a static parser method - T ParseJson(IJsonReader)
  739. var parseJson = ReflectionInfo.FindParseJson(type);
  740. if (parseJson != null)
  741. {
  742. if (parseJson.GetParameters()[0].ParameterType == typeof(IJsonReader))
  743. {
  744. return (r, t) => parseJson.Invoke(null, new Object[] { r });
  745. }
  746. else
  747. {
  748. return (r, t) =>
  749. {
  750. if (r.GetLiteralKind() == LiteralKind.String)
  751. {
  752. var o = parseJson.Invoke(null, new Object[] { r.GetLiteralString() });
  753. r.NextToken();
  754. return o;
  755. }
  756. throw new InvalidDataException(string.Format("Expected string literal for type {0}", type.FullName));
  757. };
  758. }
  759. }
  760. return (r, t) =>
  761. {
  762. var into = DecoratingActivator.CreateInstance(type);
  763. r.ParseInto(into);
  764. return into;
  765. };
  766. }
  767. public JsonLineOffset CurrentTokenPosition
  768. {
  769. get { return _tokenizer.CurrentTokenPosition; }
  770. }
  771. // ReadLiteral is implemented with a converter callback so that any
  772. // errors on converting to the target type are thrown before the tokenizer
  773. // is advanced to the next token. This ensures error location is reported
  774. // at the start of the literal, not the following token.
  775. public object ReadLiteral(Func<object, object> converter)
  776. {
  777. _tokenizer.Check(Token.Literal);
  778. var retv = converter(_tokenizer.LiteralValue);
  779. _tokenizer.NextToken();
  780. return retv;
  781. }
  782. public void CheckEOF()
  783. {
  784. _tokenizer.Check(Token.EOF);
  785. }
  786. public object Parse(Type type)
  787. {
  788. // Null?
  789. if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.Null)
  790. {
  791. _tokenizer.NextToken();
  792. return null;
  793. }
  794. // Handle nullable types
  795. var typeUnderlying = Nullable.GetUnderlyingType(type);
  796. if (typeUnderlying != null)
  797. type = typeUnderlying;
  798. // See if we have a reader
  799. Func<IJsonReader, Type, object> parser;
  800. if (Reader._parsers.TryGetValue(type, out parser))
  801. {
  802. return parser(this, type);
  803. }
  804. // See if we have factory
  805. Func<IJsonReader, string, object> factory;
  806. if (Reader._typeFactories.TryGetValue(type, out factory))
  807. {
  808. // Try first without passing dictionary keys
  809. object into = factory(this, null);
  810. if (into == null)
  811. {
  812. // This is a awkward situation. The factory requires a value from the dictionary
  813. // in order to create the target object (typically an abstract class with the class
  814. // kind recorded in the Json). Since there's no guarantee of order in a json dictionary
  815. // we can't assume the required key is first.
  816. // So, create a bookmark on the tokenizer, read keys until the factory returns an
  817. // object instance and then rewind the tokenizer and continue
  818. // Create a bookmark so we can rewind
  819. _tokenizer.CreateBookmark();
  820. // Skip the opening brace
  821. _tokenizer.Skip(Token.OpenBrace);
  822. // First pass to work out type
  823. ParseDictionaryKeys(key =>
  824. {
  825. // Try to instantiate the object
  826. into = factory(this, key);
  827. return into == null;
  828. });
  829. // Move back to start of the dictionary
  830. _tokenizer.RewindToBookmark();
  831. // Quit if still didn't get an object from the factory
  832. if (into == null)
  833. throw new InvalidOperationException("Factory didn't create object instance (probably due to a missing key in the Json)");
  834. }
  835. // Second pass
  836. ParseInto(into);
  837. // Done
  838. return into;
  839. }
  840. // Do we already have an into parser?
  841. Action<IJsonReader, object> intoParser;
  842. if (Reader._intoParsers.TryGetValue(type, out intoParser))
  843. {
  844. var into = DecoratingActivator.CreateInstance(type);
  845. ParseInto(into);
  846. return into;
  847. }
  848. // Enumerated type?
  849. if (type.IsEnum)
  850. {
  851. if (type.GetCustomAttributes(typeof(FlagsAttribute), false).Any())
  852. return ReadLiteral(literal => {
  853. try
  854. {
  855. return Enum.Parse(type, (string)literal);
  856. }
  857. catch
  858. {
  859. return Enum.ToObject(type, literal);
  860. }
  861. });
  862. else
  863. return ReadLiteral(literal => {
  864. try
  865. {
  866. return Enum.Parse(type, (string)literal);
  867. }
  868. catch (Exception)
  869. {
  870. var attr = type.GetCustomAttributes(typeof(JsonUnknownAttribute), false).FirstOrDefault();
  871. if (attr==null)
  872. throw;
  873. return ((JsonUnknownAttribute)attr).UnknownValue;
  874. }
  875. });
  876. }
  877. // Array?
  878. if (type.IsArray && type.GetArrayRank() == 1)
  879. {
  880. // First parse as a List<>
  881. var listType = typeof(List<>).MakeGenericType(type.GetElementType());
  882. var list = DecoratingActivator.CreateInstance(listType);
  883. ParseInto(list);
  884. return listType.GetMethod("ToArray").Invoke(list, null);
  885. }
  886. // Convert interfaces to concrete types
  887. if (type.IsInterface)
  888. type = Utils.ResolveInterfaceToClass(type);
  889. // Untyped dictionary?
  890. if (_tokenizer.CurrentToken == Token.OpenBrace && (type.IsAssignableFrom(typeof(IDictionary<string, object>))))
  891. {
  892. #if !PETAJSON_NO_DYNAMIC
  893. var container = (new ExpandoObject()) as IDictionary<string, object>;
  894. #else
  895. var container = new Dictionary<string, object>();
  896. #endif
  897. ParseDictionary(key =>
  898. {
  899. container[key] = Parse(typeof(Object));
  900. });
  901. return container;
  902. }
  903. // Untyped list?
  904. if (_tokenizer.CurrentToken == Token.OpenSquare && (type.IsAssignableFrom(typeof(List<object>))))
  905. {
  906. var container = new List<object>();
  907. ParseArray(() =>
  908. {
  909. container.Add(Parse(typeof(Object)));
  910. });
  911. return container;
  912. }
  913. // Untyped literal?
  914. if (_tokenizer.CurrentToken == Token.Literal && type.IsAssignableFrom(_tokenizer.LiteralType))
  915. {
  916. var lit = _tokenizer.LiteralValue;
  917. _tokenizer.NextToken();
  918. return lit;
  919. }
  920. // Call value type resolver
  921. if (type.IsValueType)
  922. {
  923. var tp = _parsers.Get(type, () => _parserResolver(type));
  924. if (tp != null)
  925. {
  926. return tp(this, type);
  927. }
  928. }
  929. // Call reference type resolver
  930. if (type.IsClass && type != typeof(object))
  931. {
  932. var into = DecoratingActivator.CreateInstance(type);
  933. ParseInto(into);
  934. return into;
  935. }
  936. // Give up
  937. throw new InvalidDataException(string.Format("syntax error, unexpected token {0}", _tokenizer.CurrentToken));
  938. }
  939. // Parse into an existing object instance
  940. public void ParseInto(object into)
  941. {
  942. if (into == null)
  943. return;
  944. if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.Null)
  945. {
  946. throw new InvalidOperationException("can't parse null into existing instance");
  947. //return;
  948. }
  949. var type = into.GetType();
  950. // Existing parse into handler?
  951. Action<IJsonReader,object> parseInto;
  952. if (_intoParsers.TryGetValue(type, out parseInto))
  953. {
  954. parseInto(this, into);
  955. return;
  956. }
  957. // Generic dictionary?
  958. var dictType = Utils.FindGenericInterface(type, typeof(IDictionary<,>));
  959. if (dictType!=null)
  960. {
  961. // Get the key and value types
  962. var typeKey = dictType.GetGenericArguments()[0];
  963. var typeValue = dictType.GetGenericArguments()[1];
  964. // Parse it
  965. IDictionary dict = (IDictionary)into;
  966. dict.Clear();
  967. ParseDictionary(key =>
  968. {
  969. dict.Add(Convert.ChangeType(key, typeKey), Parse(typeValue));
  970. });
  971. return;
  972. }
  973. // Generic list
  974. var listType = Utils.FindGenericInterface(type, typeof(IList<>));
  975. if (listType!=null)
  976. {
  977. // Get element type
  978. var typeElement = listType.GetGenericArguments()[0];
  979. // Parse it
  980. IList list = (IList)into;
  981. list.Clear();
  982. ParseArray(() =>
  983. {
  984. list.Add(Parse(typeElement));
  985. });
  986. return;
  987. }
  988. // Untyped dictionary
  989. var objDict = into as IDictionary;
  990. if (objDict != null)
  991. {
  992. objDict.Clear();
  993. ParseDictionary(key =>
  994. {
  995. objDict[key] = Parse(typeof(Object));
  996. });
  997. return;
  998. }
  999. // Untyped list
  1000. var objList = into as IList;
  1001. if (objList!=null)
  1002. {
  1003. objList.Clear();
  1004. ParseArray(() =>
  1005. {
  1006. objList.Add(Parse(typeof(Object)));
  1007. });
  1008. return;
  1009. }
  1010. // Try to resolve a parser
  1011. var intoParser = _intoParsers.Get(type, () => _intoParserResolver(type));
  1012. if (intoParser != null)
  1013. {
  1014. intoParser(this, into);
  1015. return;
  1016. }
  1017. throw new InvalidOperationException(string.Format("Don't know how to parse into type '{0}'", type.FullName));
  1018. }
  1019. public T Parse<T>()
  1020. {
  1021. return (T)Parse(typeof(T));
  1022. }
  1023. public LiteralKind GetLiteralKind()
  1024. {
  1025. return _tokenizer.LiteralKind;
  1026. }
  1027. public string GetLiteralString()
  1028. {
  1029. return _tokenizer.String;
  1030. }
  1031. public void NextToken()
  1032. {
  1033. _tokenizer.NextToken();
  1034. }
  1035. // Parse a dictionary
  1036. public void ParseDictionary(Action<string> callback)
  1037. {
  1038. _tokenizer.Skip(Token.OpenBrace);
  1039. ParseDictionaryKeys(key => { callback(key); return true; });
  1040. _tokenizer.Skip(Token.CloseBrace);
  1041. }
  1042. // Parse dictionary keys, calling callback for each one. Continues until end of input
  1043. // or when callback returns false
  1044. private void ParseDictionaryKeys(Func<string, bool> callback)
  1045. {
  1046. // End?
  1047. while (_tokenizer.CurrentToken != Token.CloseBrace)
  1048. {
  1049. // Parse the key
  1050. string key = null;
  1051. if (_tokenizer.CurrentToken == Token.Identifier && (_options & JsonOptions.StrictParser)==0)
  1052. {
  1053. key = _tokenizer.String;
  1054. }
  1055. else if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.String)
  1056. {
  1057. key = (string)_tokenizer.LiteralValue;
  1058. }
  1059. else
  1060. {
  1061. throw new InvalidDataException("syntax error, expected string literal or identifier");
  1062. }
  1063. _tokenizer.NextToken();
  1064. _tokenizer.Skip(Token.Colon);
  1065. // Remember current position
  1066. var pos = _tokenizer.CurrentTokenPosition;
  1067. // Call the callback, quit if cancelled
  1068. _contextStack.Add(key);
  1069. bool doDefaultProcessing = callback(key);
  1070. _contextStack.RemoveAt(_contextStack.Count-1);
  1071. if (!doDefaultProcessing)
  1072. return;
  1073. // If the callback didn't read anything from the tokenizer, then skip it ourself
  1074. if (pos.Line == _tokenizer.CurrentTokenPosition.Line && pos.Offset == _tokenizer.CurrentTokenPosition.Offset)
  1075. {
  1076. Parse(typeof(object));
  1077. }
  1078. // Separating/trailing comma
  1079. if (_tokenizer.SkipIf(Token.Comma))
  1080. {
  1081. if ((_options & JsonOptions.StrictParser) != 0 && _tokenizer.CurrentToken == Token.CloseBrace)
  1082. {
  1083. throw new InvalidDataException("Trailing commas not allowed in strict mode");
  1084. }
  1085. continue;
  1086. }
  1087. // End
  1088. break;
  1089. }
  1090. }
  1091. // Parse an array
  1092. public void ParseArray(Action callback)
  1093. {
  1094. _tokenizer.Skip(Token.OpenSquare);
  1095. int index = 0;
  1096. while (_tokenizer.CurrentToken != Token.CloseSquare)
  1097. {
  1098. _contextStack.Add(string.Format("[{0}]", index));
  1099. callback();
  1100. _contextStack.RemoveAt(_contextStack.Count-1);
  1101. if (_tokenizer.SkipIf(Token.Comma))
  1102. {
  1103. if ((_options & JsonOptions.StrictParser)!=0 && _tokenizer.CurrentToken==Token.CloseSquare)
  1104. {
  1105. throw new InvalidDataException("Trailing commas not allowed in strict mode");
  1106. }
  1107. continue;
  1108. }
  1109. break;
  1110. }
  1111. _tokenizer.Skip(Token.CloseSquare);
  1112. }
  1113. // Yikes!
  1114. public static Func<Type, Action<IJsonReader, object>> _intoParserResolver;
  1115. public static Func<Type, Func<IJsonReader, Type, object>> _parserResolver;
  1116. public static ThreadSafeCache<Type, Func<IJsonReader, Type, object>> _parsers = new ThreadSafeCache<Type, Func<IJsonReader, Type, object>>();
  1117. public static ThreadSafeCache<Type, Action<IJsonReader, object>> _intoParsers = new ThreadSafeCache<Type, Action<IJsonReader, object>>();
  1118. public static ThreadSafeCache<Type, Func<IJsonReader, string, object>> _typeFactories = new ThreadSafeCache<Type, Func<IJsonReader, string, object>>();
  1119. }
  1120. public class Writer : IJsonWriter
  1121. {
  1122. static Writer()
  1123. {
  1124. _formatterResolver = ResolveFormatter;
  1125. // Register standard formatters
  1126. _formatters.Add(typeof(string), (w, o) => w.WriteStringLiteral((string)o));
  1127. _formatters.Add(typeof(char), (w, o) => w.WriteStringLiteral(((char)o).ToString()));
  1128. _formatters.Add(typeof(bool), (w, o) => w.WriteRaw(((bool)o) ? "true" : "false"));
  1129. Action<IJsonWriter, object> convertWriter = (w, o) => w.WriteRaw((string)Convert.ChangeType(o, typeof(string), System.Globalization.CultureInfo.InvariantCulture));
  1130. _formatters.Add(typeof(int), convertWriter);
  1131. _formatters.Add(typeof(uint), convertWriter);
  1132. _formatters.Add(typeof(long), convertWriter);
  1133. _formatters.Add(typeof(ulong), convertWriter);
  1134. _formatters.Add(typeof(short), convertWriter);
  1135. _formatters.Add(typeof(ushort), convertWriter);
  1136. _formatters.Add(typeof(decimal), convertWriter);
  1137. _formatters.Add(typeof(byte), convertWriter);
  1138. _formatters.Add(typeof(sbyte), convertWriter);
  1139. _formatters.Add(typeof(DateTime), (w, o) => convertWriter(w, Utils.ToUnixMilliseconds((DateTime)o)));
  1140. _formatters.Add(typeof(float), (w, o) => w.WriteRaw(((float)o).ToString("R", System.Globalization.CultureInfo.InvariantCulture)));
  1141. _formatters.Add(typeof(double), (w, o) => w.WriteRaw(((double)o).ToString("R", System.Globalization.CultureInfo.InvariantCulture)));
  1142. _formatters.Add(typeof(byte[]), (w, o) =>
  1143. {
  1144. w.WriteRaw("\"");
  1145. w.WriteRaw(Convert.ToBase64String((byte[])o));
  1146. w.WriteRaw("\"");
  1147. });
  1148. }
  1149. public static Func<Type, Action<IJsonWriter, object>> _formatterResolver;
  1150. public static Dictionary<Type, Action<IJsonWriter, object>> _formatters = new Dictionary<Type, Action<IJsonWriter, object>>();
  1151. static Action<IJsonWriter, object> ResolveFormatter(Type type)
  1152. {
  1153. // Try `void FormatJson(IJsonWriter)`
  1154. var formatJson = ReflectionInfo.FindFormatJson(type);
  1155. if (formatJson != null)
  1156. {
  1157. if (formatJson.ReturnType==typeof(void))
  1158. return (w, obj) => formatJson.Invoke(obj, new Object[] { w });
  1159. if (formatJson.ReturnType == typeof(string))
  1160. return (w, obj) => w.WriteStringLiteral((string)formatJson.Invoke(obj, new Object[] { }));
  1161. }
  1162. var ri = ReflectionInfo.GetReflectionInfo(type);
  1163. if (ri != null)
  1164. return ri.Write;
  1165. else
  1166. return null;
  1167. }
  1168. public Writer(TextWriter w, JsonOptions options)
  1169. {
  1170. _writer = w;
  1171. _atStartOfLine = true;
  1172. _needElementSeparator = false;
  1173. _options = options;
  1174. }
  1175. private TextWriter _writer;
  1176. private int IndentLevel;
  1177. private bool _atStartOfLine;
  1178. private bool _needElementSeparator = false;
  1179. private JsonOptions _options;
  1180. private char _currentBlockKind = '\0';
  1181. // Move to the next line
  1182. public void NextLine()
  1183. {
  1184. if (_atStartOfLine)
  1185. return;
  1186. if ((_options & JsonOptions.WriteWhitespace)!=0)
  1187. {
  1188. WriteRaw("\n");
  1189. WriteRaw(new string('\t', IndentLevel));
  1190. }
  1191. _atStartOfLine = true;
  1192. }
  1193. // Start the next element, writing separators and white space
  1194. void NextElement()
  1195. {
  1196. if (_needElementSeparator)
  1197. {
  1198. WriteRaw(",");
  1199. NextLine();
  1200. }
  1201. else
  1202. {
  1203. NextLine();
  1204. IndentLevel++;
  1205. WriteRaw(_currentBlockKind.ToString());
  1206. NextLine();
  1207. }
  1208. _needElementSeparator = true;
  1209. }
  1210. // Write next array element
  1211. public void WriteElement()
  1212. {
  1213. if (_currentBlockKind != '[')
  1214. throw new InvalidOperationException("Attempt to write array element when not in array block");
  1215. NextElement();
  1216. }
  1217. // Write next dictionary key
  1218. public void WriteKey(string key)
  1219. {
  1220. if (_currentBlockKind != '{')
  1221. throw new InvalidOperationException("Attempt to write dictionary element when not in dictionary block");
  1222. NextElement();
  1223. WriteStringLiteral(key);
  1224. WriteRaw(((_options & JsonOptions.WriteWhitespace) != 0) ? ": " : ":");
  1225. }
  1226. // Write an already escaped dictionary key
  1227. public void WriteKeyNoEscaping(string key)
  1228. {
  1229. if (_currentBlockKind != '{')
  1230. throw new InvalidOperationException("Attempt to write dictionary element when not in dictionary block");
  1231. NextElement();
  1232. WriteRaw("\"");
  1233. WriteRaw(key);
  1234. WriteRaw("\"");
  1235. WriteRaw(((_options & JsonOptions.WriteWhitespace) != 0) ? ": " : ":");
  1236. }
  1237. // Write anything
  1238. public void WriteRaw(string str)
  1239. {
  1240. _atStartOfLine = false;
  1241. _writer.Write(str);
  1242. }
  1243. static int IndexOfEscapeableChar(string str, int pos)
  1244. {
  1245. int length = str.Length;
  1246. while (pos < length)
  1247. {
  1248. var ch = str[pos];
  1249. if (ch == '\\' || ch == '/' || ch == '\"' || (ch>=0 && ch <= 0x1f) || (ch >= 0x7f && ch <=0x9f) || ch==0x2028 || ch== 0x2029)
  1250. return pos;
  1251. pos++;
  1252. }
  1253. return -1;
  1254. }
  1255. public void WriteStringLiteral(string str)
  1256. {
  1257. _atStartOfLine = false;
  1258. if (str == null)
  1259. {
  1260. _writer.Write("null");
  1261. return;
  1262. }
  1263. _writer.Write("\"");
  1264. int pos = 0;
  1265. int escapePos;
  1266. while ((escapePos = IndexOfEscapeableChar(str, pos)) >= 0)
  1267. {
  1268. if (escapePos > pos)
  1269. _writer.Write(str.Substring(pos, escapePos - pos));
  1270. switch (str[escapePos])
  1271. {
  1272. case '\"': _writer.Write("\\\""); break;
  1273. case '\\': _writer.Write("\\\\"); break;
  1274. case '/': _writer.Write("\\/"); break;
  1275. case '\b': _writer.Write("\\b"); break;
  1276. case '\f': _writer.Write("\\f"); break;
  1277. case '\n': _writer.Write("\\n"); break;
  1278. case '\r': _writer.Write("\\r"); break;
  1279. case '\t': _writer.Write("\\t"); break;
  1280. default:
  1281. _writer.Write(string.Format("\\u{0:x4}", (int)str[escapePos]));
  1282. break;
  1283. }
  1284. pos = escapePos + 1;
  1285. }
  1286. if (str.Length > pos)
  1287. _writer.Write(str.Substring(pos));
  1288. _writer.Write("\"");
  1289. }
  1290. // Write an array or dictionary block
  1291. private void WriteBlock(string open, string close, Action callback)
  1292. {
  1293. var prevBlockKind = _currentBlockKind;
  1294. _currentBlockKind = open[0];
  1295. var didNeedElementSeparator = _needElementSeparator;
  1296. _needElementSeparator = false;
  1297. callback();
  1298. if (_needElementSeparator)
  1299. {
  1300. IndentLevel--;
  1301. NextLine();
  1302. }
  1303. else
  1304. {
  1305. WriteRaw(open);
  1306. }
  1307. WriteRaw(close);
  1308. _needElementSeparator = didNeedElementSeparator;
  1309. _currentBlockKind = prevBlockKind;
  1310. }
  1311. // Write an array
  1312. public void WriteArray(Action callback)
  1313. {
  1314. WriteBlock("[", "]", callback);
  1315. }
  1316. // Write a dictionary
  1317. public void WriteDictionary(Action callback)
  1318. {
  1319. WriteBlock("{", "}", callback);
  1320. }
  1321. // Write any value
  1322. public void WriteValue(object value)
  1323. {
  1324. _atStartOfLine = false;
  1325. // Special handling for null
  1326. if (value == null)
  1327. {
  1328. _writer.Write("null");
  1329. return;
  1330. }
  1331. var type = value.GetType();
  1332. // Handle nullable types
  1333. var typeUnderlying = Nullable.GetUnderlyingType(type);
  1334. if (typeUnderlying != null)
  1335. type = typeUnderlying;
  1336. // Look up type writer
  1337. Action<IJsonWriter, object> typeWriter;
  1338. if (_formatters.TryGetValue(type, out typeWriter))
  1339. {
  1340. // Write it
  1341. typeWriter(this, value);
  1342. return;
  1343. }
  1344. // Enumerated type?
  1345. if (type.IsEnum)
  1346. {
  1347. if (type.GetCustomAttributes(typeof(FlagsAttribute), false).Any())
  1348. WriteRaw(Convert.ToUInt32(value).ToString(CultureInfo.InvariantCulture));
  1349. else
  1350. WriteStringLiteral(value.ToString());
  1351. return;
  1352. }
  1353. // Dictionary?
  1354. var d = value as System.Collections.IDictionary;
  1355. if (d != null)
  1356. {
  1357. WriteDictionary(() =>
  1358. {
  1359. foreach (var key in d.Keys)
  1360. {
  1361. WriteKey(key.ToString());
  1362. WriteValue(d[key]);
  1363. }
  1364. });
  1365. return;
  1366. }
  1367. // Dictionary?
  1368. var dso = value as IDictionary<string,object>;
  1369. if (dso != null)
  1370. {
  1371. WriteDictionary(() =>
  1372. {
  1373. foreach (var key in dso.Keys)
  1374. {
  1375. WriteKey(key.ToString());
  1376. WriteValue(dso[key]);
  1377. }
  1378. });
  1379. return;
  1380. }
  1381. // Array?
  1382. var e = value as System.Collections.IEnumerable;
  1383. if (e != null)
  1384. {
  1385. WriteArray(() =>
  1386. {
  1387. foreach (var i in e)
  1388. {
  1389. WriteElement();
  1390. WriteValue(i);
  1391. }
  1392. });
  1393. return;
  1394. }
  1395. // Resolve a formatter
  1396. var formatter = _formatterResolver(type);
  1397. if (formatter != null)
  1398. {
  1399. _formatters[type] = formatter;
  1400. formatter(this, value);
  1401. return;
  1402. }
  1403. // Give up
  1404. throw new InvalidDataException(string.Format("Don't know how to write '{0}' to json", value.GetType()));
  1405. }
  1406. }
  1407. // Information about a field or property found through reflection
  1408. public class JsonMemberInfo
  1409. {
  1410. // The Json key for this member
  1411. public string JsonKey;
  1412. // True if should keep existing instance (reference types only)
  1413. public bool KeepInstance;
  1414. // True if deprecated
  1415. public bool Deprecated;
  1416. // Reflected member info
  1417. MemberInfo _mi;
  1418. public MemberInfo Member
  1419. {
  1420. get { return _mi; }
  1421. set
  1422. {
  1423. // Store it
  1424. _mi = value;
  1425. // Also create getters and setters
  1426. if (_mi is PropertyInfo)
  1427. {
  1428. GetValue = (obj) => ((PropertyInfo)_mi).GetValue(obj, null);
  1429. SetValue = (obj, val) => ((PropertyInfo)_mi).SetValue(obj, val, null);
  1430. }
  1431. else
  1432. {
  1433. GetValue = ((FieldInfo)_mi).GetValue;
  1434. SetValue = ((FieldInfo)_mi).SetValue;
  1435. }
  1436. }
  1437. }
  1438. // Member type
  1439. public Type MemberType
  1440. {
  1441. get
  1442. {
  1443. if (Member is PropertyInfo)
  1444. {
  1445. return ((PropertyInfo)Member).PropertyType;
  1446. }
  1447. else
  1448. {
  1449. return ((FieldInfo)Member).FieldType;
  1450. }
  1451. }
  1452. }
  1453. // Get/set helpers
  1454. public Action<object, object> SetValue;
  1455. public Func<object, object> GetValue;
  1456. }
  1457. // Stores reflection info about a type
  1458. public class ReflectionInfo
  1459. {
  1460. // List of members to be serialized
  1461. public List<JsonMemberInfo> Members;
  1462. // Cache of these ReflectionInfos's
  1463. static ThreadSafeCache<Type, ReflectionInfo> _cache = new ThreadSafeCache<Type, ReflectionInfo>();
  1464. public static MethodInfo FindFormatJson(Type type)
  1465. {
  1466. if (type.IsValueType)
  1467. {
  1468. // Try `void FormatJson(IJsonWriter)`
  1469. var formatJson = type.GetMethod("FormatJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(IJsonWriter) }, null);
  1470. if (formatJson != null && formatJson.ReturnType == typeof(void))
  1471. return formatJson;
  1472. // Try `string FormatJson()`
  1473. formatJson = type.GetMethod("FormatJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null);
  1474. if (formatJson != null && formatJson.ReturnType == typeof(string))
  1475. return formatJson;
  1476. }
  1477. return null;
  1478. }
  1479. public static MethodInfo FindParseJson(Type type)
  1480. {
  1481. // Try `T ParseJson(IJsonReader)`
  1482. var parseJson = type.GetMethod("ParseJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(IJsonReader) }, null);
  1483. if (parseJson != null && parseJson.ReturnType == type)
  1484. return parseJson;
  1485. // Try `T ParseJson(string)`
  1486. parseJson = type.GetMethod("ParseJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(string) }, null);
  1487. if (parseJson != null && parseJson.ReturnType == type)
  1488. return parseJson;
  1489. return null;
  1490. }
  1491. // Write one of these types
  1492. public void Write(IJsonWriter w, object val)
  1493. {
  1494. w.WriteDictionary(() =>
  1495. {
  1496. var writing = val as IJsonWriting;
  1497. if (writing != null)
  1498. writing.OnJsonWriting(w);
  1499. foreach (var jmi in Members.Where(x=>!x.Deprecated))
  1500. {
  1501. w.WriteKeyNoEscaping(jmi.JsonKey);
  1502. w.WriteValue(jmi.GetValue(val));
  1503. }
  1504. var written = val as IJsonWritten;
  1505. if (written != null)
  1506. written.OnJsonWritten(w);
  1507. });
  1508. }
  1509. // Read one of these types.
  1510. // NB: Although PetaJson.JsonParseInto only works on reference type, when using reflection
  1511. // it also works for value types so we use the one method for both
  1512. public void ParseInto(IJsonReader r, object into)
  1513. {
  1514. var loading = into as IJsonLoading;
  1515. if (loading != null)
  1516. loading.OnJsonLoading(r);
  1517. r.ParseDictionary(key =>
  1518. {
  1519. ParseFieldOrProperty(r, into, key);
  1520. });
  1521. var loaded = into as IJsonLoaded;
  1522. if (loaded != null)
  1523. loaded.OnJsonLoaded(r);
  1524. }
  1525. // The member info is stored in a list (as opposed to a dictionary) so that
  1526. // the json is written in the same order as the fields/properties are defined
  1527. // On loading, we assume the fields will be in the same order, but need to
  1528. // handle if they're not. This function performs a linear search, but
  1529. // starts after the last found item as an optimization that should work
  1530. // most of the time.
  1531. int _lastFoundIndex = 0;
  1532. bool FindMemberInfo(string name, out JsonMemberInfo found)
  1533. {
  1534. for (int i = 0; i < Members.Count; i++)
  1535. {
  1536. int index = (i + _lastFoundIndex) % Members.Count;
  1537. var jmi = Members[index];
  1538. if (jmi.JsonKey == name)
  1539. {
  1540. _lastFoundIndex = index;
  1541. found = jmi;
  1542. return true;
  1543. }
  1544. }
  1545. found = null;
  1546. return false;
  1547. }
  1548. // Parse a value from IJsonReader into an object instance
  1549. public void ParseFieldOrProperty(IJsonReader r, object into, string key)
  1550. {
  1551. // IJsonLoadField
  1552. var lf = into as IJsonLoadField;
  1553. if (lf != null && lf.OnJsonField(r, key))
  1554. return;
  1555. // Find member
  1556. JsonMemberInfo jmi;
  1557. if (FindMemberInfo(key, out jmi))
  1558. {
  1559. // Try to keep existing instance
  1560. if (jmi.KeepInstance)
  1561. {
  1562. var subInto = jmi.GetValue(into);
  1563. if (subInto != null)
  1564. {
  1565. r.ParseInto(subInto);
  1566. return;
  1567. }
  1568. }
  1569. // Parse and set
  1570. var val = r.Parse(jmi.MemberType);
  1571. jmi.SetValue(into, val);
  1572. return;
  1573. }
  1574. }
  1575. // Get the reflection info for a specified type
  1576. public static ReflectionInfo GetReflectionInfo(Type type)
  1577. {
  1578. // Check cache
  1579. return _cache.Get(type, () =>
  1580. {
  1581. var allMembers = Utils.GetAllFieldsAndProperties(type);
  1582. // Does type have a [Json] attribute
  1583. bool typeMarked = type.GetCustomAttributes(typeof(JsonAttribute), true).OfType<JsonAttribute>().Any();
  1584. // Do any members have a [Json] attribute
  1585. bool anyFieldsMarked = allMembers.Any(x => x.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().Any());
  1586. #if !PETAJSON_NO_DATACONTRACT
  1587. // Try with DataContract and friends
  1588. if (!typeMarked && !anyFieldsMarked && type.GetCustomAttributes(typeof(DataContractAttribute), true).OfType<DataContractAttribute>().Any())
  1589. {
  1590. var ri = CreateReflectionInfo(type, mi =>
  1591. {
  1592. // Get attributes
  1593. var attr = mi.GetCustomAttributes(typeof(DataMemberAttribute), false).OfType<DataMemberAttribute>().FirstOrDefault();
  1594. if (attr != null)
  1595. {
  1596. return new JsonMemberInfo()
  1597. {
  1598. Member = mi,
  1599. JsonKey = attr.Name ?? mi.Name, // No lower case first letter if using DataContract/Member
  1600. };
  1601. }
  1602. return null;
  1603. });
  1604. ri.Members.Sort((a, b) => String.CompareOrdinal(a.JsonKey, b.JsonKey)); // Match DataContractJsonSerializer
  1605. return ri;
  1606. }
  1607. #endif
  1608. {
  1609. // Should we serialize all public methods?
  1610. bool serializeAllPublics = typeMarked || !anyFieldsMarked;
  1611. // Build
  1612. var ri = CreateReflectionInfo(type, mi =>
  1613. {
  1614. // Explicitly excluded?
  1615. if (mi.GetCustomAttributes(typeof(JsonExcludeAttribute), false).Any())
  1616. return null;
  1617. // Get attributes
  1618. var attr = mi.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().FirstOrDefault();
  1619. if (attr != null)
  1620. {
  1621. return new JsonMemberInfo()
  1622. {
  1623. Member = mi,
  1624. JsonKey = attr.Key ?? mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
  1625. KeepInstance = attr.KeepInstance,
  1626. Deprecated = attr.Deprecated,
  1627. };
  1628. }
  1629. // Serialize all publics?
  1630. if (serializeAllPublics && Utils.IsPublic(mi))
  1631. {
  1632. return new JsonMemberInfo()
  1633. {
  1634. Member = mi,
  1635. JsonKey = mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
  1636. };
  1637. }
  1638. return null;
  1639. });
  1640. return ri;
  1641. }
  1642. });
  1643. }
  1644. public static ReflectionInfo CreateReflectionInfo(Type type, Func<MemberInfo, JsonMemberInfo> callback)
  1645. {
  1646. // Work out properties and fields
  1647. var members = Utils.GetAllFieldsAndProperties(type).Select(x => callback(x)).Where(x => x != null).ToList();
  1648. // Anything with KeepInstance must be a reference type
  1649. var invalid = members.FirstOrDefault(x => x.KeepInstance && x.MemberType.IsValueType);
  1650. if (invalid!=null)
  1651. {
  1652. throw new InvalidOperationException(string.Format("KeepInstance=true can only be applied to reference types ({0}.{1})", type.FullName, invalid.Member));
  1653. }
  1654. // Must have some members
  1655. if (!members.Any())
  1656. return null;
  1657. // Create reflection info
  1658. return new ReflectionInfo() { Members = members };
  1659. }
  1660. }
  1661. public class ThreadSafeCache<TKey, TValue>
  1662. {
  1663. public ThreadSafeCache()
  1664. {
  1665. }
  1666. public TValue Get(TKey key, Func<TValue> createIt)
  1667. {
  1668. // Check if already exists
  1669. _lock.EnterReadLock();
  1670. try
  1671. {
  1672. TValue val;
  1673. if (_map.TryGetValue(key, out val))
  1674. return val;
  1675. }
  1676. finally
  1677. {
  1678. _lock.ExitReadLock();
  1679. }
  1680. // Nope, take lock and try again
  1681. _lock.EnterWriteLock();
  1682. try
  1683. {
  1684. // Check again before creating it
  1685. TValue val;
  1686. if (!_map.TryGetValue(key, out val))
  1687. {
  1688. // Store the new one
  1689. val = createIt();
  1690. _map[key] = val;
  1691. }
  1692. return val;
  1693. }
  1694. finally
  1695. {
  1696. _lock.ExitWriteLock();
  1697. }
  1698. }
  1699. public bool TryGetValue(TKey key, out TValue val)
  1700. {
  1701. _lock.EnterReadLock();
  1702. try
  1703. {
  1704. return _map.TryGetValue(key, out val);
  1705. }
  1706. finally
  1707. {
  1708. _lock.ExitReadLock();
  1709. }
  1710. }
  1711. public void Set(TKey key, TValue value)
  1712. {
  1713. _lock.EnterWriteLock();
  1714. try
  1715. {
  1716. _map[key] = value;
  1717. }
  1718. finally
  1719. {
  1720. _lock.ExitWriteLock();
  1721. }
  1722. }
  1723. Dictionary<TKey, TValue> _map = new Dictionary<TKey,TValue>();
  1724. ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
  1725. }
  1726. internal static class Utils
  1727. {
  1728. // Get all fields and properties of a type
  1729. public static IEnumerable<MemberInfo> GetAllFieldsAndProperties(Type t)
  1730. {
  1731. if (t == null)
  1732. return Enumerable.Empty<FieldInfo>();
  1733. BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;
  1734. return t.GetMembers(flags).Where(x => x is FieldInfo || x is PropertyInfo).Concat(GetAllFieldsAndProperties(t.BaseType));
  1735. }
  1736. public static Type FindGenericInterface(Type type, Type tItf)
  1737. {
  1738. foreach (var t in type.GetInterfaces())
  1739. {
  1740. // Is this a generic list?
  1741. if (t.IsGenericType && t.GetGenericTypeDefinition() == tItf)
  1742. return t;
  1743. }
  1744. return null;
  1745. }
  1746. public static bool IsPublic(MemberInfo mi)
  1747. {
  1748. // Public field
  1749. var fi = mi as FieldInfo;
  1750. if (fi != null)
  1751. return fi.IsPublic;
  1752. // Public property
  1753. // (We only check the get method so we can work with anonymous types)
  1754. var pi = mi as PropertyInfo;
  1755. if (pi != null)
  1756. {
  1757. var gm = pi.GetGetMethod(true);
  1758. return (gm != null && gm.IsPublic);
  1759. }
  1760. return false;
  1761. }
  1762. public static Type ResolveInterfaceToClass(Type tItf)
  1763. {
  1764. // Generic type
  1765. if (tItf.IsGenericType)
  1766. {
  1767. var genDef = tItf.GetGenericTypeDefinition();
  1768. // IList<> -> List<>
  1769. if (genDef == typeof(IList<>))
  1770. {
  1771. return typeof(List<>).MakeGenericType(tItf.GetGenericArguments());
  1772. }
  1773. // IDictionary<string,> -> Dictionary<string,>
  1774. if (genDef == typeof(IDictionary<,>) && tItf.GetGenericArguments()[0] == typeof(string))
  1775. {
  1776. return typeof(Dictionary<,>).MakeGenericType(tItf.GetGenericArguments());
  1777. }
  1778. }
  1779. // IEnumerable -> List<object>
  1780. if (tItf == typeof(IEnumerable))
  1781. return typeof(List<object>);
  1782. // IDicitonary -> Dictionary<string,object>
  1783. if (tItf == typeof(IDictionary))
  1784. return typeof(Dictionary<string, object>);
  1785. return tItf;
  1786. }
  1787. public static long ToUnixMilliseconds(DateTime This)
  1788. {
  1789. return (long)This.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
  1790. }
  1791. public static DateTime FromUnixMilliseconds(long timeStamp)
  1792. {
  1793. return new DateTime(1970, 1, 1).AddMilliseconds(timeStamp);
  1794. }
  1795. }
  1796. public class Tokenizer
  1797. {
  1798. public Tokenizer(TextReader r, JsonOptions options)
  1799. {
  1800. _underlying = r;
  1801. _options = options;
  1802. FillBuffer();
  1803. NextChar();
  1804. NextToken();
  1805. }
  1806. private JsonOptions _options;
  1807. private StringBuilder _sb = new StringBuilder();
  1808. private TextReader _underlying;
  1809. private char[] _buf = new char[4096];
  1810. private int _pos;
  1811. private int _bufUsed;
  1812. private StringBuilder _rewindBuffer;
  1813. private int _rewindBufferPos;
  1814. private JsonLineOffset _currentCharPos;
  1815. private char _currentChar;
  1816. private Stack<ReaderState> _bookmarks = new Stack<ReaderState>();
  1817. public JsonLineOffset CurrentTokenPosition;
  1818. public Token CurrentToken;
  1819. public LiteralKind LiteralKind;
  1820. public string String;
  1821. public object LiteralValue
  1822. {
  1823. get
  1824. {
  1825. if (CurrentToken != Token.Literal)
  1826. throw new InvalidOperationException("token is not a literal");
  1827. switch (LiteralKind)
  1828. {
  1829. case LiteralKind.Null: return null;
  1830. case LiteralKind.False: return false;
  1831. case LiteralKind.True: return true;
  1832. case LiteralKind.String: return String;
  1833. case LiteralKind.SignedInteger: return long.Parse(String, CultureInfo.InvariantCulture);
  1834. case LiteralKind.UnsignedInteger:
  1835. if (String.StartsWith("0x") || String.StartsWith("0X"))
  1836. return Convert.ToUInt64(String.Substring(2), 16);
  1837. else
  1838. return ulong.Parse(String, CultureInfo.InvariantCulture);
  1839. case LiteralKind.FloatingPoint: return double.Parse(String, CultureInfo.InvariantCulture);
  1840. }
  1841. return null;
  1842. }
  1843. }
  1844. public Type LiteralType
  1845. {
  1846. get
  1847. {
  1848. if (CurrentToken != Token.Literal)
  1849. throw new InvalidOperationException("token is not a literal");
  1850. switch (LiteralKind)
  1851. {
  1852. case LiteralKind.Null: return typeof(Object);
  1853. case LiteralKind.False: return typeof(Boolean);
  1854. case LiteralKind.True: return typeof(Boolean);
  1855. case LiteralKind.String: return typeof(string);
  1856. case LiteralKind.SignedInteger: return typeof(long);
  1857. case LiteralKind.UnsignedInteger: return typeof(ulong);
  1858. case LiteralKind.FloatingPoint: return typeof(double);
  1859. }
  1860. return null;
  1861. }
  1862. }
  1863. // This object represents the entire state of the reader and is used for rewind
  1864. struct ReaderState
  1865. {
  1866. public ReaderState(Tokenizer tokenizer)
  1867. {
  1868. _currentCharPos = tokenizer._currentCharPos;
  1869. _currentChar = tokenizer._currentChar;
  1870. _string = tokenizer.String;
  1871. _literalKind = tokenizer.LiteralKind;
  1872. _rewindBufferPos = tokenizer._rewindBufferPos;
  1873. _currentTokenPos = tokenizer.CurrentTokenPosition;
  1874. _currentToken = tokenizer.CurrentToken;
  1875. }
  1876. public void Apply(Tokenizer tokenizer)
  1877. {
  1878. tokenizer._currentCharPos = _currentCharPos;
  1879. tokenizer._currentChar = _currentChar;
  1880. tokenizer._rewindBufferPos = _rewindBufferPos;
  1881. tokenizer.CurrentToken = _currentToken;
  1882. tokenizer.CurrentTokenPosition = _currentTokenPos;
  1883. tokenizer.String = _string;
  1884. tokenizer.LiteralKind = _literalKind;
  1885. }
  1886. private JsonLineOffset _currentCharPos;
  1887. private JsonLineOffset _currentTokenPos;
  1888. private char _currentChar;
  1889. private Token _currentToken;
  1890. private LiteralKind _literalKind;
  1891. private string _string;
  1892. private int _rewindBufferPos;
  1893. }
  1894. // Create a rewind bookmark
  1895. public void CreateBookmark()
  1896. {
  1897. _bookmarks.Push(new ReaderState(this));
  1898. if (_rewindBuffer == null)
  1899. {
  1900. _rewindBuffer = new StringBuilder();
  1901. _rewindBufferPos = 0;
  1902. }
  1903. }
  1904. // Discard bookmark
  1905. public void DiscardBookmark()
  1906. {
  1907. _bookmarks.Pop();
  1908. if (_bookmarks.Count == 0)
  1909. {
  1910. _rewindBuffer = null;
  1911. _rewindBufferPos = 0;
  1912. }
  1913. }
  1914. // Rewind to a bookmark
  1915. public void RewindToBookmark()
  1916. {
  1917. _bookmarks.Pop().Apply(this);
  1918. }
  1919. // Fill buffer by reading from underlying TextReader
  1920. void FillBuffer()
  1921. {
  1922. _bufUsed = _underlying.Read(_buf, 0, _buf.Length);
  1923. _pos = 0;
  1924. }
  1925. // Get the next character from the input stream
  1926. // (this function could be extracted into a few different methods, but is mostly inlined
  1927. // for performance - yes it makes a difference)
  1928. public char NextChar()
  1929. {
  1930. if (_rewindBuffer == null)
  1931. {
  1932. if (_pos >= _bufUsed)
  1933. {
  1934. if (_bufUsed > 0)
  1935. {
  1936. FillBuffer();
  1937. }
  1938. if (_bufUsed == 0)
  1939. {
  1940. return _currentChar = '\0';
  1941. }
  1942. }
  1943. // Next
  1944. _currentCharPos.Offset++;
  1945. return _currentChar = _buf[_pos++];
  1946. }
  1947. if (_rewindBufferPos < _rewindBuffer.Length)
  1948. {
  1949. _currentCharPos.Offset++;
  1950. return _currentChar = _rewindBuffer[_rewindBufferPos++];
  1951. }
  1952. else
  1953. {
  1954. if (_pos >= _bufUsed && _bufUsed > 0)
  1955. FillBuffer();
  1956. _currentChar = _bufUsed == 0 ? '\0' : _buf[_pos++];
  1957. _rewindBuffer.Append(_currentChar);
  1958. _rewindBufferPos++;
  1959. _currentCharPos.Offset++;
  1960. return _currentChar;
  1961. }
  1962. }
  1963. // Read the next token from the input stream
  1964. // (Mostly inline for performance)
  1965. public void NextToken()
  1966. {
  1967. while (true)
  1968. {
  1969. // Skip whitespace and handle line numbers
  1970. while (true)
  1971. {
  1972. if (_currentChar == '\r')
  1973. {
  1974. if (NextChar() == '\n')
  1975. {
  1976. NextChar();
  1977. }
  1978. _currentCharPos.Line++;
  1979. _currentCharPos.Offset = 0;
  1980. }
  1981. else if (_currentChar == '\n')
  1982. {
  1983. if (NextChar() == '\r')
  1984. {
  1985. NextChar();
  1986. }
  1987. _currentCharPos.Line++;
  1988. _currentCharPos.Offset = 0;
  1989. }
  1990. else if (_currentChar == ' ')
  1991. {
  1992. NextChar();
  1993. }
  1994. else if (_currentChar == '\t')
  1995. {
  1996. NextChar();
  1997. }
  1998. else
  1999. break;
  2000. }
  2001. // Remember position of token
  2002. CurrentTokenPosition = _currentCharPos;
  2003. // Handle common characters first
  2004. switch (_currentChar)
  2005. {
  2006. case '/':
  2007. // Comments not support in strict mode
  2008. if ((_options & JsonOptions.StrictParser) != 0)
  2009. {
  2010. throw new InvalidDataException(string.Format("syntax error, unexpected character '{0}'", _currentChar));
  2011. }
  2012. // Process comment
  2013. NextChar();
  2014. switch (_currentChar)
  2015. {
  2016. case '/':
  2017. NextChar();
  2018. while (_currentChar!='\0' && _currentChar != '\r' && _currentChar != '\n')
  2019. {
  2020. NextChar();
  2021. }
  2022. break;
  2023. case '*':
  2024. bool endFound = false;
  2025. while (!endFound && _currentChar!='\0')
  2026. {
  2027. if (_currentChar == '*')
  2028. {
  2029. NextChar();
  2030. if (_currentChar == '/')
  2031. {
  2032. endFound = true;
  2033. }
  2034. }
  2035. NextChar();
  2036. }
  2037. break;
  2038. default:
  2039. throw new InvalidDataException("syntax error, unexpected character after slash");
  2040. }
  2041. continue;
  2042. case '\"':
  2043. case '\'':
  2044. {
  2045. _sb.Length = 0;
  2046. var quoteKind = _currentChar;
  2047. NextChar();
  2048. while (_currentChar!='\0')
  2049. {
  2050. if (_currentChar == '\\')
  2051. {
  2052. NextChar();
  2053. var escape = _currentChar;
  2054. switch (escape)
  2055. {
  2056. case '\"': _sb.Append('\"'); break;
  2057. case '\\': _sb.Append('\\'); break;
  2058. case '/': _sb.Append('/'); break;
  2059. case 'b': _sb.Append('\b'); break;
  2060. case 'f': _sb.Append('\f'); break;
  2061. case 'n': _sb.Append('\n'); break;
  2062. case 'r': _sb.Append('\r'); break;
  2063. case 't': _sb.Append('\t'); break;
  2064. case 'u':
  2065. var sbHex = new StringBuilder();
  2066. for (int i = 0; i < 4; i++)
  2067. {
  2068. NextChar();
  2069. sbHex.Append(_currentChar);
  2070. }
  2071. _sb.Append((char)Convert.ToUInt16(sbHex.ToString(), 16));
  2072. break;
  2073. default:
  2074. throw new InvalidDataException(string.Format("Invalid escape sequence in string literal: '\\{0}'", _currentChar));
  2075. }
  2076. }
  2077. else if (_currentChar == quoteKind)
  2078. {
  2079. String = _sb.ToString();
  2080. CurrentToken = Token.Literal;
  2081. LiteralKind = LiteralKind.String;
  2082. NextChar();
  2083. return;
  2084. }
  2085. else
  2086. {
  2087. _sb.Append(_currentChar);
  2088. }
  2089. NextChar();
  2090. }
  2091. throw new InvalidDataException("syntax error, unterminated string literal");
  2092. }
  2093. case '{': CurrentToken = Token.OpenBrace; NextChar(); return;
  2094. case '}': CurrentToken = Token.CloseBrace; NextChar(); return;
  2095. case '[': CurrentToken = Token.OpenSquare; NextChar(); return;
  2096. case ']': CurrentToken = Token.CloseSquare; NextChar(); return;
  2097. case '=': CurrentToken = Token.Equal; NextChar(); return;
  2098. case ':': CurrentToken = Token.Colon; NextChar(); return;
  2099. case ';': CurrentToken = Token.SemiColon; NextChar(); return;
  2100. case ',': CurrentToken = Token.Comma; NextChar(); return;
  2101. case '\0': CurrentToken = Token.EOF; return;
  2102. }
  2103. // Number?
  2104. if (char.IsDigit(_currentChar) || _currentChar == '-')
  2105. {
  2106. TokenizeNumber();
  2107. return;
  2108. }
  2109. // Identifier? (checked for after everything else as identifiers are actually quite rare in valid json)
  2110. if (Char.IsLetter(_currentChar) || _currentChar == '_' || _currentChar == '$')
  2111. {
  2112. // Find end of identifier
  2113. _sb.Length = 0;
  2114. while (Char.IsLetterOrDigit(_currentChar) || _currentChar == '_' || _currentChar == '$')
  2115. {
  2116. _sb.Append(_currentChar);
  2117. NextChar();
  2118. }
  2119. String = _sb.ToString();
  2120. // Handle special identifiers
  2121. switch (String)
  2122. {
  2123. case "true":
  2124. LiteralKind = LiteralKind.True;
  2125. CurrentToken = Token.Literal;
  2126. return;
  2127. case "false":
  2128. LiteralKind = LiteralKind.False;
  2129. CurrentToken = Token.Literal;
  2130. return;
  2131. case "null":
  2132. LiteralKind = LiteralKind.Null;
  2133. CurrentToken = Token.Literal;
  2134. return;
  2135. }
  2136. CurrentToken = Token.Identifier;
  2137. return;
  2138. }
  2139. // What the?
  2140. throw new InvalidDataException(string.Format("syntax error, unexpected character '{0}'", _currentChar));
  2141. }
  2142. }
  2143. // Parse a sequence of characters that could make up a valid number
  2144. // For performance, we don't actually parse it into a number yet. When using PetaJsonEmit we parse
  2145. // later, directly into a value type to avoid boxing
  2146. private void TokenizeNumber()
  2147. {
  2148. _sb.Length = 0;
  2149. // Leading negative sign
  2150. bool signed = false;
  2151. if (_currentChar == '-')
  2152. {
  2153. signed = true;
  2154. _sb.Append(_currentChar);
  2155. NextChar();
  2156. }
  2157. // Hex prefix?
  2158. bool hex = false;
  2159. if (_currentChar == '0' && (_options & JsonOptions.StrictParser)==0)
  2160. {
  2161. _sb.Append(_currentChar);
  2162. NextChar();
  2163. if (_currentChar == 'x' || _currentChar == 'X')
  2164. {
  2165. _sb.Append(_currentChar);
  2166. NextChar();
  2167. hex = true;
  2168. }
  2169. }
  2170. // Process characters, but vaguely figure out what type it is
  2171. bool cont = true;
  2172. bool fp = false;
  2173. while (cont)
  2174. {
  2175. switch (_currentChar)
  2176. {
  2177. case '0':
  2178. case '1':
  2179. case '2':
  2180. case '3':
  2181. case '4':
  2182. case '5':
  2183. case '6':
  2184. case '7':
  2185. case '8':
  2186. case '9':
  2187. _sb.Append(_currentChar);
  2188. NextChar();
  2189. break;
  2190. case 'A':
  2191. case 'a':
  2192. case 'B':
  2193. case 'b':
  2194. case 'C':
  2195. case 'c':
  2196. case 'D':
  2197. case 'd':
  2198. case 'F':
  2199. case 'f':
  2200. if (!hex)
  2201. cont = false;
  2202. else
  2203. {
  2204. _sb.Append(_currentChar);
  2205. NextChar();
  2206. }
  2207. break;
  2208. case '.':
  2209. if (hex)
  2210. {
  2211. cont = false;
  2212. }
  2213. else
  2214. {
  2215. fp = true;
  2216. _sb.Append(_currentChar);
  2217. NextChar();
  2218. }
  2219. break;
  2220. case 'E':
  2221. case 'e':
  2222. if (!hex)
  2223. {
  2224. fp = true;
  2225. _sb.Append(_currentChar);
  2226. NextChar();
  2227. if (_currentChar == '+' || _currentChar == '-')
  2228. {
  2229. _sb.Append(_currentChar);
  2230. NextChar();
  2231. }
  2232. }
  2233. break;
  2234. default:
  2235. cont = false;
  2236. break;
  2237. }
  2238. }
  2239. if (char.IsLetter(_currentChar))
  2240. throw new InvalidDataException(string.Format("syntax error, invalid character following number '{0}'", _sb.ToString()));
  2241. // Setup token
  2242. String = _sb.ToString();
  2243. CurrentToken = Token.Literal;
  2244. // Setup literal kind
  2245. if (fp)
  2246. {
  2247. LiteralKind = LiteralKind.FloatingPoint;
  2248. }
  2249. else if (signed)
  2250. {
  2251. LiteralKind = LiteralKind.SignedInteger;
  2252. }
  2253. else
  2254. {
  2255. LiteralKind = LiteralKind.UnsignedInteger;
  2256. }
  2257. }
  2258. // Check the current token, throw exception if mismatch
  2259. public void Check(Token tokenRequired)
  2260. {
  2261. if (tokenRequired != CurrentToken)
  2262. {
  2263. throw new InvalidDataException(string.Format("syntax error, expected {0} found {1}", tokenRequired, CurrentToken));
  2264. }
  2265. }
  2266. // Skip token which must match
  2267. public void Skip(Token tokenRequired)
  2268. {
  2269. Check(tokenRequired);
  2270. NextToken();
  2271. }
  2272. // Skip token if it matches
  2273. public bool SkipIf(Token tokenRequired)
  2274. {
  2275. if (tokenRequired == CurrentToken)
  2276. {
  2277. NextToken();
  2278. return true;
  2279. }
  2280. return false;
  2281. }
  2282. }
  2283. #if !PETAJSON_NO_EMIT
  2284. static class Emit
  2285. {
  2286. // Generates a function that when passed an object of specified type, renders it to an IJsonReader
  2287. public static Action<IJsonWriter, object> MakeFormatter(Type type)
  2288. {
  2289. var formatJson = ReflectionInfo.FindFormatJson(type);
  2290. if (formatJson != null)
  2291. {
  2292. var method = new DynamicMethod("invoke_formatJson", null, new Type[] { typeof(IJsonWriter), typeof(Object) }, true);
  2293. var il = method.GetILGenerator();
  2294. if (formatJson.ReturnType == typeof(string))
  2295. {
  2296. // w.WriteStringLiteral(o.FormatJson())
  2297. il.Emit(OpCodes.Ldarg_0);
  2298. il.Emit(OpCodes.Ldarg_1);
  2299. il.Emit(OpCodes.Unbox, type);
  2300. il.Emit(OpCodes.Call, formatJson);
  2301. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteStringLiteral"));
  2302. }
  2303. else
  2304. {
  2305. // o.FormatJson(w);
  2306. il.Emit(OpCodes.Ldarg_1);
  2307. il.Emit(type.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, type);
  2308. il.Emit(OpCodes.Ldarg_0);
  2309. il.Emit(type.IsValueType ? OpCodes.Call : OpCodes.Callvirt, formatJson);
  2310. }
  2311. il.Emit(OpCodes.Ret);
  2312. return (Action<IJsonWriter, object>)method.CreateDelegate(typeof(Action<IJsonWriter, object>));
  2313. }
  2314. else
  2315. {
  2316. // Get the reflection info for this type
  2317. var ri = ReflectionInfo.GetReflectionInfo(type);
  2318. if (ri == null)
  2319. return null;
  2320. // Create a dynamic method that can do the work
  2321. var method = new DynamicMethod("dynamic_formatter", null, new Type[] { typeof(IJsonWriter), typeof(object) }, true);
  2322. var il = method.GetILGenerator();
  2323. // Cast/unbox the target object and store in local variable
  2324. var locTypedObj = il.DeclareLocal(type);
  2325. il.Emit(OpCodes.Ldarg_1);
  2326. il.Emit(type.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, type);
  2327. il.Emit(OpCodes.Stloc, locTypedObj);
  2328. // Get Invariant CultureInfo (since we'll probably be needing this)
  2329. var locInvariant = il.DeclareLocal(typeof(IFormatProvider));
  2330. il.Emit(OpCodes.Call, typeof(CultureInfo).GetProperty("InvariantCulture").GetGetMethod());
  2331. il.Emit(OpCodes.Stloc, locInvariant);
  2332. // These are the types we'll call .ToString(Culture.InvariantCulture) on
  2333. var toStringTypes = new Type[] {
  2334. typeof(int), typeof(uint), typeof(long), typeof(ulong),
  2335. typeof(short), typeof(ushort), typeof(decimal),
  2336. typeof(byte), typeof(sbyte)
  2337. };
  2338. // Theses types we also generate for
  2339. var otherSupportedTypes = new Type[] {
  2340. typeof(double), typeof(float), typeof(string), typeof(char)
  2341. };
  2342. // Call IJsonWriting if implemented
  2343. if (typeof(IJsonWriting).IsAssignableFrom(type))
  2344. {
  2345. if (type.IsValueType)
  2346. {
  2347. il.Emit(OpCodes.Ldloca, locTypedObj);
  2348. il.Emit(OpCodes.Ldarg_0);
  2349. il.Emit(OpCodes.Call, type.GetInterfaceMap(typeof(IJsonWriting)).TargetMethods[0]);
  2350. }
  2351. else
  2352. {
  2353. il.Emit(OpCodes.Ldloc, locTypedObj);
  2354. il.Emit(OpCodes.Castclass, typeof(IJsonWriting));
  2355. il.Emit(OpCodes.Ldarg_0);
  2356. il.Emit(OpCodes.Callvirt, typeof(IJsonWriting).GetMethod("OnJsonWriting", new Type[] { typeof(IJsonWriter) }));
  2357. }
  2358. }
  2359. // Process all members
  2360. foreach (var m in ri.Members)
  2361. {
  2362. // Dont save deprecated properties
  2363. if (m.Deprecated)
  2364. {
  2365. continue;
  2366. }
  2367. // Ignore write only properties
  2368. var pi = m.Member as PropertyInfo;
  2369. if (pi != null && pi.GetGetMethod(true) == null)
  2370. {
  2371. continue;
  2372. }
  2373. // Write the Json key
  2374. il.Emit(OpCodes.Ldarg_0);
  2375. il.Emit(OpCodes.Ldstr, m.JsonKey);
  2376. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteKeyNoEscaping", new Type[] { typeof(string) }));
  2377. // Load the writer
  2378. il.Emit(OpCodes.Ldarg_0);
  2379. // Get the member type
  2380. var memberType = m.MemberType;
  2381. // Load the target object
  2382. if (type.IsValueType)
  2383. {
  2384. il.Emit(OpCodes.Ldloca, locTypedObj);
  2385. }
  2386. else
  2387. {
  2388. il.Emit(OpCodes.Ldloc, locTypedObj);
  2389. }
  2390. // Work out if we need the value or it's address on the stack
  2391. bool NeedValueAddress = (memberType.IsValueType && (toStringTypes.Contains(memberType) || otherSupportedTypes.Contains(memberType)));
  2392. if (Nullable.GetUnderlyingType(memberType) != null)
  2393. {
  2394. NeedValueAddress = true;
  2395. }
  2396. // Property?
  2397. if (pi != null)
  2398. {
  2399. // Call property's get method
  2400. if (type.IsValueType)
  2401. il.Emit(OpCodes.Call, pi.GetGetMethod(true));
  2402. else
  2403. il.Emit(OpCodes.Callvirt, pi.GetGetMethod(true));
  2404. // If we need the address then store in a local and take it's address
  2405. if (NeedValueAddress)
  2406. {
  2407. var locTemp = il.DeclareLocal(memberType);
  2408. il.Emit(OpCodes.Stloc, locTemp);
  2409. il.Emit(OpCodes.Ldloca, locTemp);
  2410. }
  2411. }
  2412. // Field?
  2413. var fi = m.Member as FieldInfo;
  2414. if (fi != null)
  2415. {
  2416. if (NeedValueAddress)
  2417. {
  2418. il.Emit(OpCodes.Ldflda, fi);
  2419. }
  2420. else
  2421. {
  2422. il.Emit(OpCodes.Ldfld, fi);
  2423. }
  2424. }
  2425. Label? lblFinished = null;
  2426. // Is it a nullable type?
  2427. var typeUnderlying = Nullable.GetUnderlyingType(memberType);
  2428. if (typeUnderlying != null)
  2429. {
  2430. // Duplicate the address so we can call get_HasValue() and then get_Value()
  2431. il.Emit(OpCodes.Dup);
  2432. // Define some labels
  2433. var lblHasValue = il.DefineLabel();
  2434. lblFinished = il.DefineLabel();
  2435. // Call has_Value
  2436. il.Emit(OpCodes.Call, memberType.GetProperty("HasValue").GetGetMethod());
  2437. il.Emit(OpCodes.Brtrue, lblHasValue);
  2438. // No value, write "null:
  2439. il.Emit(OpCodes.Pop);
  2440. il.Emit(OpCodes.Ldstr, "null");
  2441. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  2442. il.Emit(OpCodes.Br_S, lblFinished.Value);
  2443. // Get it's value
  2444. il.MarkLabel(lblHasValue);
  2445. il.Emit(OpCodes.Call, memberType.GetProperty("Value").GetGetMethod());
  2446. // Switch to the underlying type from here on
  2447. memberType = typeUnderlying;
  2448. NeedValueAddress = (memberType.IsValueType && (toStringTypes.Contains(memberType) || otherSupportedTypes.Contains(memberType)));
  2449. // Work out again if we need the address of the value
  2450. if (NeedValueAddress)
  2451. {
  2452. var locTemp = il.DeclareLocal(memberType);
  2453. il.Emit(OpCodes.Stloc, locTemp);
  2454. il.Emit(OpCodes.Ldloca, locTemp);
  2455. }
  2456. }
  2457. // ToString()
  2458. if (toStringTypes.Contains(memberType))
  2459. {
  2460. // Convert to string
  2461. il.Emit(OpCodes.Ldloc, locInvariant);
  2462. il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { typeof(IFormatProvider) }));
  2463. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  2464. }
  2465. // ToString("R")
  2466. else if (memberType == typeof(float) || memberType == typeof(double))
  2467. {
  2468. il.Emit(OpCodes.Ldstr, "R");
  2469. il.Emit(OpCodes.Ldloc, locInvariant);
  2470. il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { typeof(string), typeof(IFormatProvider) }));
  2471. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  2472. }
  2473. // String?
  2474. else if (memberType == typeof(string))
  2475. {
  2476. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteStringLiteral", new Type[] { typeof(string) }));
  2477. }
  2478. // Char?
  2479. else if (memberType == typeof(char))
  2480. {
  2481. il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { }));
  2482. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteStringLiteral", new Type[] { typeof(string) }));
  2483. }
  2484. // Bool?
  2485. else if (memberType == typeof(bool))
  2486. {
  2487. var lblTrue = il.DefineLabel();
  2488. var lblCont = il.DefineLabel();
  2489. il.Emit(OpCodes.Brtrue_S, lblTrue);
  2490. il.Emit(OpCodes.Ldstr, "false");
  2491. il.Emit(OpCodes.Br_S, lblCont);
  2492. il.MarkLabel(lblTrue);
  2493. il.Emit(OpCodes.Ldstr, "true");
  2494. il.MarkLabel(lblCont);
  2495. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  2496. }
  2497. // NB: We don't support DateTime as it's format can be changed
  2498. else
  2499. {
  2500. // Unsupported type, pass through
  2501. if (memberType.IsValueType)
  2502. {
  2503. il.Emit(OpCodes.Box, memberType);
  2504. }
  2505. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteValue", new Type[] { typeof(object) }));
  2506. }
  2507. if (lblFinished.HasValue)
  2508. il.MarkLabel(lblFinished.Value);
  2509. }
  2510. // Call IJsonWritten
  2511. if (typeof(IJsonWritten).IsAssignableFrom(type))
  2512. {
  2513. if (type.IsValueType)
  2514. {
  2515. il.Emit(OpCodes.Ldloca, locTypedObj);
  2516. il.Emit(OpCodes.Ldarg_0);
  2517. il.Emit(OpCodes.Call, type.GetInterfaceMap(typeof(IJsonWritten)).TargetMethods[0]);
  2518. }
  2519. else
  2520. {
  2521. il.Emit(OpCodes.Ldloc, locTypedObj);
  2522. il.Emit(OpCodes.Castclass, typeof(IJsonWriting));
  2523. il.Emit(OpCodes.Ldarg_0);
  2524. il.Emit(OpCodes.Callvirt, typeof(IJsonWriting).GetMethod("OnJsonWritten", new Type[] { typeof(IJsonWriter) }));
  2525. }
  2526. }
  2527. // Done!
  2528. il.Emit(OpCodes.Ret);
  2529. var impl = (Action<IJsonWriter, object>)method.CreateDelegate(typeof(Action<IJsonWriter, object>));
  2530. // Wrap it in a call to WriteDictionary
  2531. return (w, obj) =>
  2532. {
  2533. w.WriteDictionary(() =>
  2534. {
  2535. impl(w, obj);
  2536. });
  2537. };
  2538. }
  2539. }
  2540. // Pseudo box lets us pass a value type by reference. Used during
  2541. // deserialization of value types.
  2542. interface IPseudoBox
  2543. {
  2544. object GetValue();
  2545. }
  2546. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  2547. class PseudoBox<T> : IPseudoBox where T : struct
  2548. {
  2549. public T value = default(T);
  2550. object IPseudoBox.GetValue() { return value; }
  2551. }
  2552. // Make a parser for value types
  2553. public static Func<IJsonReader, Type, object> MakeParser(Type type)
  2554. {
  2555. System.Diagnostics.Debug.Assert(type.IsValueType);
  2556. // ParseJson method?
  2557. var parseJson = ReflectionInfo.FindParseJson(type);
  2558. if (parseJson != null)
  2559. {
  2560. if (parseJson.GetParameters()[0].ParameterType == typeof(IJsonReader))
  2561. {
  2562. var method = new DynamicMethod("invoke_ParseJson", typeof(Object), new Type[] { typeof(IJsonReader), typeof(Type) }, true);
  2563. var il = method.GetILGenerator();
  2564. il.Emit(OpCodes.Ldarg_0);
  2565. il.Emit(OpCodes.Call, parseJson);
  2566. il.Emit(OpCodes.Box, type);
  2567. il.Emit(OpCodes.Ret);
  2568. return (Func<IJsonReader,Type,object>)method.CreateDelegate(typeof(Func<IJsonReader,Type,object>));
  2569. }
  2570. else
  2571. {
  2572. var method = new DynamicMethod("invoke_ParseJson", typeof(Object), new Type[] { typeof(string) }, true);
  2573. var il = method.GetILGenerator();
  2574. il.Emit(OpCodes.Ldarg_0);
  2575. il.Emit(OpCodes.Call, parseJson);
  2576. il.Emit(OpCodes.Box, type);
  2577. il.Emit(OpCodes.Ret);
  2578. var invoke = (Func<string, object>)method.CreateDelegate(typeof(Func<string, object>));
  2579. return (r, t) =>
  2580. {
  2581. if (r.GetLiteralKind() == LiteralKind.String)
  2582. {
  2583. var o = invoke(r.GetLiteralString());
  2584. r.NextToken();
  2585. return o;
  2586. }
  2587. throw new InvalidDataException(string.Format("Expected string literal for type {0}", type.FullName));
  2588. };
  2589. }
  2590. }
  2591. else
  2592. {
  2593. // Get the reflection info for this type
  2594. var ri = ReflectionInfo.GetReflectionInfo(type);
  2595. if (ri == null)
  2596. return null;
  2597. // We'll create setters for each property/field
  2598. var setters = new Dictionary<string, Action<IJsonReader, object>>();
  2599. // Store the value in a pseudo box until it's fully initialized
  2600. var boxType = typeof(PseudoBox<>).MakeGenericType(type);
  2601. // Process all members
  2602. foreach (var m in ri.Members)
  2603. {
  2604. // Ignore write only properties
  2605. var pi = m.Member as PropertyInfo;
  2606. var fi = m.Member as FieldInfo;
  2607. if (pi != null && pi.GetSetMethod(true) == null)
  2608. {
  2609. continue;
  2610. }
  2611. // Create a dynamic method that can do the work
  2612. var method = new DynamicMethod("dynamic_parser", null, new Type[] { typeof(IJsonReader), typeof(object) }, true);
  2613. var il = method.GetILGenerator();
  2614. // Load the target
  2615. il.Emit(OpCodes.Ldarg_1);
  2616. il.Emit(OpCodes.Castclass, boxType);
  2617. il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
  2618. // Get the value
  2619. GenerateGetJsonValue(m, il);
  2620. // Assign it
  2621. if (pi != null)
  2622. il.Emit(OpCodes.Call, pi.GetSetMethod(true));
  2623. if (fi != null)
  2624. il.Emit(OpCodes.Stfld, fi);
  2625. // Done
  2626. il.Emit(OpCodes.Ret);
  2627. // Store in the map of setters
  2628. setters.Add(m.JsonKey, (Action<IJsonReader, object>)method.CreateDelegate(typeof(Action<IJsonReader, object>)));
  2629. }
  2630. // Create helpers to invoke the interfaces (this is painful but avoids having to really box
  2631. // the value in order to call the interface).
  2632. Action<object, IJsonReader> invokeLoading = MakeInterfaceCall(type, typeof(IJsonLoading));
  2633. Action<object, IJsonReader> invokeLoaded = MakeInterfaceCall(type, typeof(IJsonLoaded));
  2634. Func<object, IJsonReader, string, bool> invokeField = MakeLoadFieldCall(type);
  2635. // Create the parser
  2636. Func<IJsonReader, Type, object> parser = (reader, Type) =>
  2637. {
  2638. // Create pseudobox (ie: new PseudoBox<Type>)
  2639. var box = DecoratingActivator.CreateInstance(boxType);
  2640. // Call IJsonLoading
  2641. if (invokeLoading != null)
  2642. invokeLoading(box, reader);
  2643. // Read the dictionary
  2644. reader.ParseDictionary(key =>
  2645. {
  2646. // Call IJsonLoadField
  2647. if (invokeField != null && invokeField(box, reader, key))
  2648. return;
  2649. // Get a setter and invoke it if found
  2650. Action<IJsonReader, object> setter;
  2651. if (setters.TryGetValue(key, out setter))
  2652. {
  2653. setter(reader, box);
  2654. }
  2655. });
  2656. // IJsonLoaded
  2657. if (invokeLoaded != null)
  2658. invokeLoaded(box, reader);
  2659. // Return the value
  2660. return ((IPseudoBox)box).GetValue();
  2661. };
  2662. // Done
  2663. return parser;
  2664. }
  2665. }
  2666. // Helper to make the call to a PsuedoBox value's IJsonLoading or IJsonLoaded
  2667. static Action<object, IJsonReader> MakeInterfaceCall(Type type, Type tItf)
  2668. {
  2669. // Interface supported?
  2670. if (!tItf.IsAssignableFrom(type))
  2671. return null;
  2672. // Resolve the box type
  2673. var boxType = typeof(PseudoBox<>).MakeGenericType(type);
  2674. // Create method
  2675. var method = new DynamicMethod("dynamic_invoke_" + tItf.Name, null, new Type[] { typeof(object), typeof(IJsonReader) }, true);
  2676. var il = method.GetILGenerator();
  2677. // Call interface method
  2678. il.Emit(OpCodes.Ldarg_0);
  2679. il.Emit(OpCodes.Castclass, boxType);
  2680. il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
  2681. il.Emit(OpCodes.Ldarg_1);
  2682. il.Emit(OpCodes.Call, type.GetInterfaceMap(tItf).TargetMethods[0]);
  2683. il.Emit(OpCodes.Ret);
  2684. // Done
  2685. return (Action<object, IJsonReader>)method.CreateDelegate(typeof(Action<object, IJsonReader>));
  2686. }
  2687. // Similar to above but for IJsonLoadField
  2688. static Func<object, IJsonReader, string, bool> MakeLoadFieldCall(Type type)
  2689. {
  2690. // Interface supported?
  2691. var tItf = typeof(IJsonLoadField);
  2692. if (!tItf.IsAssignableFrom(type))
  2693. return null;
  2694. // Resolve the box type
  2695. var boxType = typeof(PseudoBox<>).MakeGenericType(type);
  2696. // Create method
  2697. var method = new DynamicMethod("dynamic_invoke_" + tItf.Name, typeof(bool), new Type[] { typeof(object), typeof(IJsonReader), typeof(string) }, true);
  2698. var il = method.GetILGenerator();
  2699. // Call interface method
  2700. il.Emit(OpCodes.Ldarg_0);
  2701. il.Emit(OpCodes.Castclass, boxType);
  2702. il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
  2703. il.Emit(OpCodes.Ldarg_1);
  2704. il.Emit(OpCodes.Ldarg_2);
  2705. il.Emit(OpCodes.Call, type.GetInterfaceMap(tItf).TargetMethods[0]);
  2706. il.Emit(OpCodes.Ret);
  2707. // Done
  2708. return (Func<object, IJsonReader, string, bool>)method.CreateDelegate(typeof(Func<object, IJsonReader, string, bool>));
  2709. }
  2710. // Create an "into parser" that can parse from IJsonReader into a reference type (ie: a class)
  2711. public static Action<IJsonReader, object> MakeIntoParser(Type type)
  2712. {
  2713. System.Diagnostics.Debug.Assert(!type.IsValueType);
  2714. // Get the reflection info for this type
  2715. var ri = ReflectionInfo.GetReflectionInfo(type);
  2716. if (ri == null)
  2717. return null;
  2718. // We'll create setters for each property/field
  2719. var setters = new Dictionary<string, Action<IJsonReader, object>>();
  2720. // Process all members
  2721. foreach (var m in ri.Members)
  2722. {
  2723. // Ignore write only properties
  2724. var pi = m.Member as PropertyInfo;
  2725. var fi = m.Member as FieldInfo;
  2726. if (pi != null && pi.GetSetMethod(true) == null)
  2727. {
  2728. continue;
  2729. }
  2730. // Ignore read only properties that has KeepInstance attribute
  2731. if (pi != null && pi.GetGetMethod(true) == null && m.KeepInstance)
  2732. {
  2733. continue;
  2734. }
  2735. // Create a dynamic method that can do the work
  2736. var method = new DynamicMethod("dynamic_parser", null, new Type[] { typeof(IJsonReader), typeof(object) }, true);
  2737. var il = method.GetILGenerator();
  2738. // Load the target
  2739. il.Emit(OpCodes.Ldarg_1);
  2740. il.Emit(OpCodes.Castclass, type);
  2741. // Try to keep existing instance?
  2742. if (m.KeepInstance)
  2743. {
  2744. // Get existing existing instance
  2745. il.Emit(OpCodes.Dup);
  2746. if (pi != null)
  2747. il.Emit(OpCodes.Callvirt, pi.GetGetMethod(true));
  2748. else
  2749. il.Emit(OpCodes.Ldfld, fi);
  2750. var existingInstance = il.DeclareLocal(m.MemberType);
  2751. var lblExistingInstanceNull = il.DefineLabel();
  2752. // Keep a copy of the existing instance in a locale
  2753. il.Emit(OpCodes.Dup);
  2754. il.Emit(OpCodes.Stloc, existingInstance);
  2755. // Compare to null
  2756. il.Emit(OpCodes.Ldnull);
  2757. il.Emit(OpCodes.Ceq);
  2758. il.Emit(OpCodes.Brtrue_S, lblExistingInstanceNull);
  2759. il.Emit(OpCodes.Ldarg_0); // reader
  2760. il.Emit(OpCodes.Ldloc, existingInstance); // into
  2761. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("ParseInto", new Type[] { typeof(Object) }));
  2762. il.Emit(OpCodes.Pop); // Clean up target left on stack (1)
  2763. il.Emit(OpCodes.Ret);
  2764. il.MarkLabel(lblExistingInstanceNull);
  2765. }
  2766. // Get the value from IJsonReader
  2767. GenerateGetJsonValue(m, il);
  2768. // Assign it
  2769. if (pi != null)
  2770. il.Emit(OpCodes.Callvirt, pi.GetSetMethod(true));
  2771. if (fi != null)
  2772. il.Emit(OpCodes.Stfld, fi);
  2773. // Done
  2774. il.Emit(OpCodes.Ret);
  2775. // Store the handler in map
  2776. setters.Add(m.JsonKey, (Action<IJsonReader, object>)method.CreateDelegate(typeof(Action<IJsonReader, object>)));
  2777. }
  2778. // Now create the parseInto delegate
  2779. Action<IJsonReader, object> parseInto = (reader, obj) =>
  2780. {
  2781. // Call IJsonLoading
  2782. var loading = obj as IJsonLoading;
  2783. if (loading != null)
  2784. loading.OnJsonLoading(reader);
  2785. // Cache IJsonLoadField
  2786. var lf = obj as IJsonLoadField;
  2787. // Read dictionary keys
  2788. reader.ParseDictionary(key =>
  2789. {
  2790. // Call IJsonLoadField
  2791. if (lf != null && lf.OnJsonField(reader, key))
  2792. return;
  2793. // Call setters
  2794. Action<IJsonReader, object> setter;
  2795. if (setters.TryGetValue(key, out setter))
  2796. {
  2797. setter(reader, obj);
  2798. }
  2799. });
  2800. // Call IJsonLoaded
  2801. var loaded = obj as IJsonLoaded;
  2802. if (loaded != null)
  2803. loaded.OnJsonLoaded(reader);
  2804. };
  2805. // Since we've created the ParseInto handler, we might as well register
  2806. // as a Parse handler too.
  2807. RegisterIntoParser(type, parseInto);
  2808. // Done
  2809. return parseInto;
  2810. }
  2811. // Registers a ParseInto handler as Parse handler that instantiates the object
  2812. // and then parses into it.
  2813. static void RegisterIntoParser(Type type, Action<IJsonReader, object> parseInto)
  2814. {
  2815. // Check type has a parameterless constructor
  2816. var con = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);
  2817. if (con == null)
  2818. return;
  2819. // Create a dynamic method that can do the work
  2820. var method = new DynamicMethod("dynamic_factory", typeof(object), new Type[] { typeof(IJsonReader), typeof(Action<IJsonReader, object>) }, true);
  2821. var il = method.GetILGenerator();
  2822. // Create the new object
  2823. var locObj = il.DeclareLocal(typeof(object));
  2824. il.Emit(OpCodes.Newobj, con);
  2825. il.Emit(OpCodes.Dup); // For return value
  2826. il.Emit(OpCodes.Stloc, locObj);
  2827. il.Emit(OpCodes.Ldarg_1); // parseinto delegate
  2828. il.Emit(OpCodes.Ldarg_0); // IJsonReader
  2829. il.Emit(OpCodes.Ldloc, locObj); // new object instance
  2830. il.Emit(OpCodes.Callvirt, typeof(Action<IJsonReader, object>).GetMethod("Invoke"));
  2831. il.Emit(OpCodes.Ret);
  2832. var factory = (Func<IJsonReader, Action<IJsonReader, object>, object>)method.CreateDelegate(typeof(Func<IJsonReader, Action<IJsonReader, object>, object>));
  2833. Json.RegisterParser(type, (reader, type2) =>
  2834. {
  2835. return factory(reader, parseInto);
  2836. });
  2837. }
  2838. // Generate the MSIL to retrieve a value for a particular field or property from a IJsonReader
  2839. private static void GenerateGetJsonValue(JsonMemberInfo m, ILGenerator il)
  2840. {
  2841. Action<string> generateCallToHelper = helperName =>
  2842. {
  2843. // Call the helper
  2844. il.Emit(OpCodes.Ldarg_0);
  2845. il.Emit(OpCodes.Call, typeof(Emit).GetMethod(helperName, new Type[] { typeof(IJsonReader) }));
  2846. // Move to next token
  2847. il.Emit(OpCodes.Ldarg_0);
  2848. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("NextToken", new Type[] { }));
  2849. };
  2850. Type[] numericTypes = new Type[] {
  2851. typeof(int), typeof(uint), typeof(long), typeof(ulong),
  2852. typeof(short), typeof(ushort), typeof(decimal),
  2853. typeof(byte), typeof(sbyte),
  2854. typeof(double), typeof(float)
  2855. };
  2856. if (m.MemberType == typeof(string))
  2857. {
  2858. generateCallToHelper("GetLiteralString");
  2859. }
  2860. else if (m.MemberType == typeof(bool))
  2861. {
  2862. generateCallToHelper("GetLiteralBool");
  2863. }
  2864. else if (m.MemberType == typeof(char))
  2865. {
  2866. generateCallToHelper("GetLiteralChar");
  2867. }
  2868. else if (numericTypes.Contains(m.MemberType))
  2869. {
  2870. // Get raw number string
  2871. il.Emit(OpCodes.Ldarg_0);
  2872. il.Emit(OpCodes.Call, typeof(Emit).GetMethod("GetLiteralNumber", new Type[] { typeof(IJsonReader) }));
  2873. // Convert to a string
  2874. il.Emit(OpCodes.Call, typeof(CultureInfo).GetProperty("InvariantCulture").GetGetMethod());
  2875. il.Emit(OpCodes.Call, m.MemberType.GetMethod("Parse", new Type[] { typeof(string), typeof(IFormatProvider) }));
  2876. //
  2877. il.Emit(OpCodes.Ldarg_0);
  2878. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("NextToken", new Type[] { }));
  2879. }
  2880. else
  2881. {
  2882. il.Emit(OpCodes.Ldarg_0);
  2883. il.Emit(OpCodes.Ldtoken, m.MemberType);
  2884. il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }));
  2885. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("Parse", new Type[] { typeof(Type) }));
  2886. il.Emit(m.MemberType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, m.MemberType);
  2887. }
  2888. }
  2889. // Helper to fetch a literal bool from an IJsonReader
  2890. [Obfuscation(Exclude = true)]
  2891. public static bool GetLiteralBool(IJsonReader r)
  2892. {
  2893. switch (r.GetLiteralKind())
  2894. {
  2895. case LiteralKind.True:
  2896. return true;
  2897. case LiteralKind.False:
  2898. return false;
  2899. default:
  2900. throw new InvalidDataException("expected a boolean value");
  2901. }
  2902. }
  2903. // Helper to fetch a literal character from an IJsonReader
  2904. [Obfuscation(Exclude = true)]
  2905. public static char GetLiteralChar(IJsonReader r)
  2906. {
  2907. if (r.GetLiteralKind() != LiteralKind.String)
  2908. throw new InvalidDataException("expected a single character string literal");
  2909. var str = r.GetLiteralString();
  2910. if (str == null || str.Length != 1)
  2911. throw new InvalidDataException("expected a single character string literal");
  2912. return str[0];
  2913. }
  2914. // Helper to fetch a literal string from an IJsonReader
  2915. [Obfuscation(Exclude = true)]
  2916. public static string GetLiteralString(IJsonReader r)
  2917. {
  2918. switch (r.GetLiteralKind())
  2919. {
  2920. case LiteralKind.Null: return null;
  2921. case LiteralKind.String: return r.GetLiteralString();
  2922. }
  2923. throw new InvalidDataException("expected a string literal");
  2924. }
  2925. // Helper to fetch a literal number from an IJsonReader (returns the raw string)
  2926. [Obfuscation(Exclude = true)]
  2927. public static string GetLiteralNumber(IJsonReader r)
  2928. {
  2929. switch (r.GetLiteralKind())
  2930. {
  2931. case LiteralKind.SignedInteger:
  2932. case LiteralKind.UnsignedInteger:
  2933. case LiteralKind.FloatingPoint:
  2934. return r.GetLiteralString();
  2935. }
  2936. throw new InvalidDataException("expected a numeric literal");
  2937. }
  2938. }
  2939. #endif
  2940. }
  2941. }