PetaJson.cs 107 KB

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