PetaJson.cs 109 KB

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