PetaJson.cs 128 KB

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