PetaJson.cs 120 KB

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