PetaJson.cs 112 KB

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