PetaJson.cs 130 KB

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