PetaJson.cs 132 KB

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