PetaJson.cs 110 KB

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