PetaJson.cs 127 KB

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