PetaJson.cs 135 KB

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