PetaJson.cs 125 KB

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