PetaJson.cs 128 KB

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