PetaJson.cs 131 KB

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