PetaJson.cs 127 KB

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