PetaJson.cs 121 KB

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