PetaJson.cs 135 KB

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