PetaJson.cs 111 KB

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