PetaJson.cs 128 KB

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