PetaJson.cs 133 KB

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