PetaJson.cs 133 KB

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