PetaJson.cs 127 KB

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