PetaJson.cs 129 KB

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