PetaJson.cs 112 KB

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