PetaJson.cs 109 KB

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