PetaJson.cs 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940
  1. /* PetaJson v0.5 - A simple but flexible Json library in a single .cs file.
  2. *
  3. * Copyright © 2014 Topten Software. All Rights Reserved.
  4. *
  5. * Apache License 2.0 - http://www.toptensoftware.com/petapoco/license
  6. */
  7. // Define PETAJSON_DYNAMIC in your project settings for Expando support
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Text;
  12. using System.IO;
  13. using System.Reflection;
  14. using System.Globalization;
  15. using System.Collections;
  16. #if PETAJSON_DYNAMIC
  17. using System.Dynamic;
  18. #endif
  19. namespace PetaJson
  20. {
  21. // Pass to format/write/parse functions to override defaults
  22. [Flags]
  23. public enum JsonOptions
  24. {
  25. None = 0,
  26. WriteWhitespace = 0x00000001,
  27. DontWriteWhitespace = 0x00000002,
  28. StrictParser = 0x00000004,
  29. NonStrictParser = 0x00000008,
  30. }
  31. // API
  32. public static class Json
  33. {
  34. static Json()
  35. {
  36. WriteWhitespaceDefault = true;
  37. StrictParserDefault = false;
  38. }
  39. // Pretty format default
  40. public static bool WriteWhitespaceDefault
  41. {
  42. get;
  43. set;
  44. }
  45. // Strict parser
  46. public static bool StrictParserDefault
  47. {
  48. get;
  49. set;
  50. }
  51. // Write an object to a text writer
  52. public static void Write(TextWriter w, object o, JsonOptions options = JsonOptions.None)
  53. {
  54. var writer = new Internal.Writer(w, ResolveOptions(options));
  55. writer.WriteValue(o);
  56. }
  57. // Write an object to a file
  58. public static void WriteFile(string filename, object o, JsonOptions options = JsonOptions.None)
  59. {
  60. using (var w = new StreamWriter(filename))
  61. {
  62. Write(w, o, options);
  63. }
  64. }
  65. // Format an object as a json string
  66. public static string Format(object o, JsonOptions options = JsonOptions.None)
  67. {
  68. var sw = new StringWriter();
  69. var writer = new Internal.Writer(sw, ResolveOptions(options));
  70. writer.WriteValue(o);
  71. return sw.ToString();
  72. }
  73. // Parse an object of specified type from a text reader
  74. public static object Parse(TextReader r, Type type, JsonOptions options = JsonOptions.None)
  75. {
  76. Internal.Reader reader = null;
  77. try
  78. {
  79. reader = new Internal.Reader(r, ResolveOptions(options));
  80. var retv = reader.Parse(type);
  81. reader.CheckEOF();
  82. return retv;
  83. }
  84. catch (Exception x)
  85. {
  86. throw new JsonParseException(x, reader==null ? new JsonLineOffset() : reader.CurrentTokenPosition);
  87. }
  88. }
  89. // Parse an object of specified type from a text reader
  90. public static T Parse<T>(TextReader r, JsonOptions options = JsonOptions.None)
  91. {
  92. return (T)Parse(r, typeof(T), options);
  93. }
  94. // Parse from text reader into an already instantied object
  95. public static void ParseInto(TextReader r, Object into, JsonOptions options = JsonOptions.None)
  96. {
  97. Internal.Reader reader = null;
  98. try
  99. {
  100. reader = new Internal.Reader(r, ResolveOptions(options));
  101. reader.ParseInto(into);
  102. reader.CheckEOF();
  103. }
  104. catch (Exception x)
  105. {
  106. throw new JsonParseException(x, reader==null ? new JsonLineOffset() : reader.CurrentTokenPosition);
  107. }
  108. }
  109. // Parse an object of specified type from a file
  110. public static object ParseFile(string filename, Type type, JsonOptions options = JsonOptions.None)
  111. {
  112. using (var r = new StreamReader(filename))
  113. {
  114. return Parse(r, type, options);
  115. }
  116. }
  117. // Parse an object of specified type from a file
  118. public static T ParseFile<T>(string filename, JsonOptions options = JsonOptions.None)
  119. {
  120. using (var r = new StreamReader(filename))
  121. {
  122. return Parse<T>(r, options);
  123. }
  124. }
  125. // Parse from file into an already instantied object
  126. public static void ParseFileInto(string filename, Object into, JsonOptions options = JsonOptions.None)
  127. {
  128. using (var r = new StreamReader(filename))
  129. {
  130. ParseInto(r, into, options);
  131. }
  132. }
  133. // Parse an object from a string
  134. public static object Parse(string data, Type type, JsonOptions options = JsonOptions.None)
  135. {
  136. return Parse(new StringReader(data), type, options);
  137. }
  138. // Parse an object from a string
  139. public static T Parse<T>(string data, JsonOptions options = JsonOptions.None)
  140. {
  141. return (T)Parse<T>(new StringReader(data), options);
  142. }
  143. // Parse from string into an already instantiated object
  144. public static void ParseInto(string data, Object into, JsonOptions options = JsonOptions.None)
  145. {
  146. ParseInto(new StringReader(data), into, options);
  147. }
  148. // Create a clone of an object
  149. public static T Clone<T>(T source)
  150. {
  151. return (T)Clone((object)source);
  152. }
  153. // Create a clone of an object (untyped)
  154. public static object Clone(object source)
  155. {
  156. if (source == null)
  157. return null;
  158. return Parse(Format(source), source.GetType());
  159. }
  160. // Clone an object into another instance
  161. public static void CloneInto<T>(T dest, T source)
  162. {
  163. ParseInto(Format(source), dest);
  164. }
  165. // Register a callback that can format a value of a particular type into json
  166. public static void RegisterFormatter(Type type, Action<IJsonWriter, object> formatter)
  167. {
  168. Internal.Writer._typeWriters[type] = formatter;
  169. }
  170. // Typed version of above
  171. public static void RegisterFormatter<T>(Action<IJsonWriter, T> formatter)
  172. {
  173. RegisterFormatter(typeof(T), (w, o) => formatter(w, (T)o));
  174. }
  175. // Register a parser for a specified type
  176. public static void RegisterParser(Type type, Func<IJsonReader, Type, object> parser)
  177. {
  178. Internal.Reader._typeParsers[type] = parser;
  179. }
  180. // Register a typed parser
  181. public static void RegisterParser<T>(Func<IJsonReader, Type, T> parser)
  182. {
  183. RegisterParser(typeof(T), (r, t) => parser(r, t));
  184. }
  185. // Simpler version for simple types
  186. public static void RegisterParser(Type type, Func<object, object> parser)
  187. {
  188. RegisterParser(type, (r, t) => r.ReadLiteral(parser));
  189. }
  190. // Simpler and typesafe parser for simple types
  191. public static void RegisterParser<T>(Func<object, T> parser)
  192. {
  193. RegisterParser(typeof(T), literal => parser(literal));
  194. }
  195. public static void SetTypeFormatterResolver(Func<Type, Action<IJsonWriter, object>> resolver)
  196. {
  197. Internal.Writer._typeWriterResolver = resolver;
  198. }
  199. public static void SetTypeIntoParserResolver(Func<Type, Action<IJsonReader, object>> resolver)
  200. {
  201. Internal.Reader._typeIntoParserResolver = resolver;
  202. }
  203. // Register a factory for instantiating objects (typically abstract classes)
  204. // Callback will be invoked for each key in the dictionary until it returns an object
  205. // instance and which point it will switch to serialization using reflection
  206. public static void RegisterTypeFactory(Type type, Func<IJsonReader, string, object> factory)
  207. {
  208. Internal.Reader._typeFactories[type] = factory;
  209. }
  210. // Resolve passed options
  211. static JsonOptions ResolveOptions(JsonOptions options)
  212. {
  213. JsonOptions resolved = JsonOptions.None;
  214. if ((options & (JsonOptions.WriteWhitespace|JsonOptions.DontWriteWhitespace))!=0)
  215. resolved |= options & (JsonOptions.WriteWhitespace | JsonOptions.DontWriteWhitespace);
  216. else
  217. resolved |= WriteWhitespaceDefault ? JsonOptions.WriteWhitespace : JsonOptions.DontWriteWhitespace;
  218. if ((options & (JsonOptions.StrictParser | JsonOptions.NonStrictParser)) != 0)
  219. resolved |= options & (JsonOptions.StrictParser | JsonOptions.NonStrictParser);
  220. else
  221. resolved |= StrictParserDefault ? JsonOptions.StrictParser : JsonOptions.NonStrictParser;
  222. return resolved;
  223. }
  224. }
  225. // Called before loading via reflection
  226. public interface IJsonLoading
  227. {
  228. void OnJsonLoading(IJsonReader r);
  229. }
  230. // Called after loading via reflection
  231. public interface IJsonLoaded
  232. {
  233. void OnJsonLoaded(IJsonReader r);
  234. }
  235. // Called for each field while loading from reflection
  236. // Return true if handled
  237. public interface IJsonLoadField
  238. {
  239. bool OnJsonField(IJsonReader r, string key);
  240. }
  241. // Called when about to write using reflection
  242. public interface IJsonWriting
  243. {
  244. void OnJsonWriting(IJsonWriter w);
  245. }
  246. // Called after written using reflection
  247. public interface IJsonWritten
  248. {
  249. void OnJsonWritten(IJsonWriter w);
  250. }
  251. public enum LiteralKind
  252. {
  253. None,
  254. String,
  255. Null,
  256. True,
  257. False,
  258. SignedInteger,
  259. UnsignedInteger,
  260. FloatingPoint,
  261. }
  262. // Passed to registered parsers
  263. public interface IJsonReader
  264. {
  265. object ReadLiteral(Func<object, object> converter);
  266. void ReadDictionary(Action<string> callback);
  267. void ReadArray(Action callback);
  268. object Parse(Type type);
  269. T Parse<T>();
  270. void ParseInto(object into);
  271. LiteralKind GetLiteralKind();
  272. string GetLiteralString();
  273. void NextToken();
  274. }
  275. // Passed to registered formatters
  276. public interface IJsonWriter
  277. {
  278. void WriteStringLiteral(string str);
  279. void WriteRaw(string str);
  280. void WriteArray(Action callback);
  281. void WriteDictionary(Action callback);
  282. void WriteValue(object value);
  283. void WriteElement();
  284. void WriteKey(string key);
  285. void WriteKeyNoEscaping(string key);
  286. }
  287. // Exception thrown for any parse error
  288. public class JsonParseException : Exception
  289. {
  290. public JsonParseException(Exception inner, JsonLineOffset position) :
  291. base(string.Format("Json parse error at {0} - {1}", position, inner.Message), inner)
  292. {
  293. Position = position;
  294. }
  295. public JsonLineOffset Position;
  296. }
  297. // Stores a line, character offset in source file
  298. public struct JsonLineOffset
  299. {
  300. public int Line;
  301. public int Offset;
  302. public override string ToString()
  303. {
  304. return string.Format("line {0}, character {1}", Line + 1, Offset + 1);
  305. }
  306. }
  307. // Used to decorate fields and properties that should be serialized
  308. //
  309. // - [Json] on class or struct causes all public fields and properties to be serialized
  310. // - [Json] on a public or non-public field or property causes that member to be serialized
  311. // - [JsonExclude] on a field or property causes that field to be not serialized
  312. // - A class or struct with no [Json] attribute has all public fields/properties serialized
  313. // - A class or struct with no [Json] attribute but a [Json] attribute on one or more members only serializes those members
  314. //
  315. // Use [Json("keyname")] to explicitly specify the key to be used
  316. // [Json] without the keyname will be serialized using the name of the member with the first letter lowercased.
  317. //
  318. // [Json(KeepInstance=true)] causes container/subobject types to be serialized into the existing member instance (if not null)
  319. //
  320. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field)]
  321. public class JsonAttribute : Attribute
  322. {
  323. public JsonAttribute()
  324. {
  325. _key = null;
  326. }
  327. public JsonAttribute(string key)
  328. {
  329. _key = key;
  330. }
  331. // Key used to save this field/property
  332. string _key;
  333. public string Key
  334. {
  335. get { return _key; }
  336. }
  337. // If true uses ParseInto to parse into the existing object instance
  338. // If false, creates a new instance as assigns it to the property
  339. public bool KeepInstance
  340. {
  341. get;
  342. set;
  343. }
  344. }
  345. // See comments above
  346. [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
  347. public class JsonExcludeAttribute : Attribute
  348. {
  349. public JsonExcludeAttribute()
  350. {
  351. }
  352. }
  353. namespace Internal
  354. {
  355. public enum Token
  356. {
  357. EOF,
  358. Identifier,
  359. Literal,
  360. OpenBrace,
  361. CloseBrace,
  362. OpenSquare,
  363. CloseSquare,
  364. Equal,
  365. Colon,
  366. SemiColon,
  367. Comma,
  368. }
  369. public class Reader : IJsonReader
  370. {
  371. static Reader()
  372. {
  373. _typeIntoParserResolver = ResolveParseInto;
  374. Func<IJsonReader, Type, object> simpleConverter = (reader, type) =>
  375. {
  376. return reader.ReadLiteral(literal => Convert.ChangeType(literal, type, CultureInfo.InvariantCulture));
  377. };
  378. _typeParsers.Add(typeof(string), simpleConverter);
  379. _typeParsers.Add(typeof(char), simpleConverter);
  380. _typeParsers.Add(typeof(bool), simpleConverter);
  381. _typeParsers.Add(typeof(byte), simpleConverter);
  382. _typeParsers.Add(typeof(sbyte), simpleConverter);
  383. _typeParsers.Add(typeof(short), simpleConverter);
  384. _typeParsers.Add(typeof(ushort), simpleConverter);
  385. _typeParsers.Add(typeof(int), simpleConverter);
  386. _typeParsers.Add(typeof(uint), simpleConverter);
  387. _typeParsers.Add(typeof(long), simpleConverter);
  388. _typeParsers.Add(typeof(ulong), simpleConverter);
  389. _typeParsers.Add(typeof(decimal), simpleConverter);
  390. _typeParsers.Add(typeof(float), simpleConverter);
  391. _typeParsers.Add(typeof(double), simpleConverter);
  392. _typeParsers.Add(typeof(DateTime), (reader, type) =>
  393. {
  394. return reader.ReadLiteral(literal => Utils.FromUnixMilliseconds((long)Convert.ChangeType(literal, typeof(long), CultureInfo.InvariantCulture)));
  395. });
  396. _typeParsers.Add(typeof(byte[]), (reader, type) =>
  397. {
  398. return reader.ReadLiteral(literal => Convert.FromBase64String((string)Convert.ChangeType(literal, typeof(string), CultureInfo.InvariantCulture)));
  399. });
  400. }
  401. public Reader(TextReader r, JsonOptions options)
  402. {
  403. _tokenizer = new Tokenizer(r, options);
  404. _options = options;
  405. }
  406. static Action<IJsonReader, object> ResolveParseInto(Type type)
  407. {
  408. var ri = ReflectionInfo.GetReflectionInfo(type);
  409. if (ri != null)
  410. return ri.ParseInto;
  411. else
  412. return null;
  413. }
  414. Tokenizer _tokenizer;
  415. JsonOptions _options;
  416. public JsonLineOffset CurrentTokenPosition
  417. {
  418. get { return _tokenizer.CurrentTokenPosition; }
  419. }
  420. // ReadLiteral is implemented with a converter callback so that any
  421. // errors on converting to the target type are thrown before the tokenizer
  422. // is advanced to the next token. This ensures error location is reported
  423. // at the start of the literal, not the following token.
  424. public object ReadLiteral(Func<object, object> converter)
  425. {
  426. _tokenizer.Check(Token.Literal);
  427. var retv = converter(_tokenizer.LiteralValue);
  428. _tokenizer.NextToken();
  429. return retv;
  430. }
  431. public void CheckEOF()
  432. {
  433. _tokenizer.Check(Token.EOF);
  434. }
  435. public object Parse(Type type)
  436. {
  437. // Null?
  438. if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.Null)
  439. {
  440. _tokenizer.NextToken();
  441. return null;
  442. }
  443. // Handle nullable types
  444. var typeUnderlying = Nullable.GetUnderlyingType(type);
  445. if (typeUnderlying != null)
  446. type = typeUnderlying;
  447. // See if we have a reader
  448. Func<IJsonReader, Type, object> typeReader;
  449. if (Reader._typeParsers.TryGetValue(type, out typeReader))
  450. {
  451. return typeReader(this, type);
  452. }
  453. // See if we have factory
  454. Func<IJsonReader, string, object> typeFactory;
  455. if (Reader._typeFactories.TryGetValue(type, out typeFactory))
  456. {
  457. // Try first without passing dictionary keys
  458. object into = typeFactory(this, null);
  459. if (into == null)
  460. {
  461. // This is a awkward situation. The factory requires a value from the dictionary
  462. // in order to create the target object (typically an abstract class with the class
  463. // kind recorded in the Json). Since there's no guarantee of order in a json dictionary
  464. // we can't assume the required key is first.
  465. // So, create a bookmark on the tokenizer, read keys until the factory returns an
  466. // object instance and then rewind the tokenizer and continue
  467. // Create a bookmark so we can rewind
  468. _tokenizer.CreateBookmark();
  469. // Skip the opening brace
  470. _tokenizer.Skip(Token.OpenBrace);
  471. // First pass to work out type
  472. ReadDictionaryKeys(key =>
  473. {
  474. // Try to instantiate the object
  475. into = typeFactory(this, key);
  476. return into == null;
  477. });
  478. // Move back to start of the dictionary
  479. _tokenizer.RewindToBookmark();
  480. // Quit if still didn't get an object from the factory
  481. if (into == null)
  482. throw new InvalidOperationException("Factory didn't create object instance (probably due to a missing key in the Json)");
  483. }
  484. // Second pass
  485. ParseInto(into);
  486. // Done
  487. return into;
  488. }
  489. // Do we already have an into reader?
  490. Action<IJsonReader, object> typeIntoReader;
  491. if (Reader._typeIntoParsers.TryGetValue(type, out typeIntoReader))
  492. {
  493. var into = Activator.CreateInstance(type);
  494. ParseInto(into);
  495. return into;
  496. }
  497. // Enumerated type?
  498. if (type.IsEnum)
  499. {
  500. return ReadLiteral(literal => Enum.Parse(type, (string)literal));
  501. }
  502. // Array?
  503. if (type.IsArray && type.GetArrayRank() == 1)
  504. {
  505. // First parse as a List<>
  506. var listType = typeof(List<>).MakeGenericType(type.GetElementType());
  507. var list = Activator.CreateInstance(listType);
  508. ParseInto(list);
  509. return listType.GetMethod("ToArray").Invoke(list, null);
  510. }
  511. // Untyped dictionary?
  512. if (_tokenizer.CurrentToken == Token.OpenBrace && (type.IsAssignableFrom(typeof(Dictionary<string, object>))))
  513. {
  514. #if PETAJSON_DYNAMIC
  515. var container = (new ExpandoObject()) as IDictionary<string, object>;
  516. #else
  517. var container = new Dictionary<string, object>();
  518. #endif
  519. ReadDictionary(key =>
  520. {
  521. container[key] = Parse(typeof(Object));
  522. });
  523. return container;
  524. }
  525. // Untyped list?
  526. if (_tokenizer.CurrentToken == Token.OpenSquare && (type.IsAssignableFrom(typeof(List<object>))))
  527. {
  528. var container = new List<object>();
  529. ReadArray(() =>
  530. {
  531. container.Add(Parse(typeof(Object)));
  532. });
  533. return container;
  534. }
  535. // Untyped literal?
  536. if (_tokenizer.CurrentToken == Token.Literal && type.IsAssignableFrom(_tokenizer.LiteralType))
  537. {
  538. var lit = _tokenizer.LiteralValue;
  539. _tokenizer.NextToken();
  540. return lit;
  541. }
  542. // Is it a type we can parse into?
  543. if ((type.IsClass || (type.IsValueType && !type.IsPrimitive)) && type != typeof(object))
  544. {
  545. var into = Activator.CreateInstance(type);
  546. ParseInto(into);
  547. return into;
  548. }
  549. throw new InvalidDataException(string.Format("syntax error - unexpected token {0}", _tokenizer.CurrentToken));
  550. }
  551. public Type FindGenericInterface(Type type, Type tItf)
  552. {
  553. foreach (var t in type.GetInterfaces())
  554. {
  555. // Is this a generic list?
  556. if (t.IsGenericType && t.GetGenericTypeDefinition() == tItf)
  557. return type;
  558. }
  559. return null;
  560. }
  561. public void ParseInto(object into)
  562. {
  563. if (into == null)
  564. return;
  565. var type = into.GetType();
  566. // Existing parse into handler?
  567. Action<IJsonReader,object> parseInto;
  568. if (_typeIntoParsers.TryGetValue(type, out parseInto))
  569. {
  570. parseInto(this, into);
  571. return;
  572. }
  573. // Generic dictionary?
  574. var dictType = FindGenericInterface(type, typeof(IDictionary<,>));
  575. if (dictType!=null)
  576. {
  577. // Get the key and value types
  578. var typeKey = dictType.GetGenericArguments()[0];
  579. var typeValue = dictType.GetGenericArguments()[1];
  580. // Parse it
  581. IDictionary dict = (IDictionary)into;
  582. dict.Clear();
  583. ReadDictionary(key =>
  584. {
  585. dict.Add(Convert.ChangeType(key, typeKey), Parse(typeValue));
  586. });
  587. return;
  588. }
  589. // Generic list
  590. var listType = FindGenericInterface(type, typeof(IList<>));
  591. if (listType!=null)
  592. {
  593. // Get element type
  594. var typeElement = listType.GetGenericArguments()[0];
  595. // Parse it
  596. IList list = (IList)into;
  597. list.Clear();
  598. ReadArray(() =>
  599. {
  600. list.Add(Parse(typeElement));
  601. });
  602. return;
  603. }
  604. // Untyped dictionary
  605. var objDict = into as IDictionary;
  606. if (objDict != null)
  607. {
  608. objDict.Clear();
  609. ReadDictionary(key =>
  610. {
  611. objDict[key] = Parse(typeof(Object));
  612. });
  613. return;
  614. }
  615. // Untyped list
  616. var objList = into as IList;
  617. if (objList!=null)
  618. {
  619. objList.Clear();
  620. ReadArray(() =>
  621. {
  622. objList.Add(Parse(typeof(Object)));
  623. });
  624. return;
  625. }
  626. // Use reflection?
  627. var tw = _typeIntoParserResolver(type);
  628. if (tw != null)
  629. {
  630. _typeIntoParsers[type] = tw;
  631. tw(this, into);
  632. return;
  633. }
  634. throw new InvalidOperationException(string.Format("Don't know how to parse into type '{0}'", type.FullName));
  635. }
  636. public T Parse<T>()
  637. {
  638. return (T)Parse(typeof(T));
  639. }
  640. public LiteralKind GetLiteralKind()
  641. {
  642. return _tokenizer.LiteralKind;
  643. }
  644. public string GetLiteralString()
  645. {
  646. return _tokenizer.String;
  647. }
  648. public void NextToken()
  649. {
  650. _tokenizer.NextToken();
  651. }
  652. public void ReadDictionary(Action<string> callback)
  653. {
  654. _tokenizer.Skip(Token.OpenBrace);
  655. ReadDictionaryKeys(key => { callback(key); return true; });
  656. _tokenizer.Skip(Token.CloseBrace);
  657. }
  658. private void ReadDictionaryKeys(Func<string, bool> callback)
  659. {
  660. while (_tokenizer.CurrentToken != Token.CloseBrace)
  661. {
  662. // Parse the key
  663. string key = null;
  664. if (_tokenizer.CurrentToken == Token.Identifier && (_options & JsonOptions.StrictParser)==0)
  665. {
  666. key = _tokenizer.String;
  667. }
  668. else if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.String)
  669. {
  670. key = (string)_tokenizer.LiteralValue;
  671. }
  672. else
  673. {
  674. throw new InvalidDataException("syntax error, expected string literal or identifier");
  675. }
  676. _tokenizer.NextToken();
  677. _tokenizer.Skip(Token.Colon);
  678. var pos = _tokenizer.CurrentTokenPosition;
  679. if (!callback(key))
  680. return;
  681. if (pos.Line==_tokenizer.CurrentTokenPosition.Line && pos.Offset == _tokenizer.CurrentTokenPosition.Offset)
  682. {
  683. // The callback didn't handle the key, so skip the value
  684. Parse(typeof(object));
  685. }
  686. if (_tokenizer.SkipIf(Token.Comma))
  687. {
  688. if ((_options & JsonOptions.StrictParser) != 0 && _tokenizer.CurrentToken == Token.CloseBrace)
  689. {
  690. throw new InvalidDataException("Trailing commas not allowed in strict mode");
  691. }
  692. continue;
  693. }
  694. break;
  695. }
  696. }
  697. public void ReadArray(Action callback)
  698. {
  699. _tokenizer.Skip(Token.OpenSquare);
  700. while (_tokenizer.CurrentToken != Token.CloseSquare)
  701. {
  702. callback();
  703. if (_tokenizer.SkipIf(Token.Comma))
  704. {
  705. if ((_options & JsonOptions.StrictParser)!=0 && _tokenizer.CurrentToken==Token.CloseSquare)
  706. {
  707. throw new InvalidDataException("Trailing commas not allowed in strict mode");
  708. }
  709. continue;
  710. }
  711. break;
  712. }
  713. _tokenizer.Skip(Token.CloseSquare);
  714. }
  715. public static Dictionary<Type, Func<IJsonReader, Type, object>> _typeParsers = new Dictionary<Type, Func<IJsonReader, Type, object>>();
  716. public static Dictionary<Type, Action<IJsonReader, object>> _typeIntoParsers = new Dictionary<Type, Action<IJsonReader, object>>();
  717. public static Func<Type, Action<IJsonReader, object>> _typeIntoParserResolver;
  718. public static Dictionary<Type, Func<IJsonReader, string, object>> _typeFactories = new Dictionary<Type, Func<IJsonReader, string, object>>();
  719. }
  720. public class Writer : IJsonWriter
  721. {
  722. static Writer()
  723. {
  724. _typeWriterResolver = ResolveTypeWriter;
  725. // Strings
  726. _typeWriters.Add(typeof(string), (w, o) => w.WriteStringLiteral((string)o));
  727. _typeWriters.Add(typeof(char), (w, o) => w.WriteStringLiteral(((char)o).ToString()));
  728. // Boolean
  729. _typeWriters.Add(typeof(bool), (w, o) => w.WriteRaw(((bool)o) ? "true" : "false"));
  730. // Integer
  731. Action<IJsonWriter, object> convertWriter = (w, o) => w.WriteRaw((string)Convert.ChangeType(o, typeof(string), System.Globalization.CultureInfo.InvariantCulture));
  732. _typeWriters.Add(typeof(int), convertWriter);
  733. _typeWriters.Add(typeof(uint), convertWriter);
  734. _typeWriters.Add(typeof(long), convertWriter);
  735. _typeWriters.Add(typeof(ulong), convertWriter);
  736. _typeWriters.Add(typeof(short), convertWriter);
  737. _typeWriters.Add(typeof(ushort), convertWriter);
  738. _typeWriters.Add(typeof(decimal), convertWriter);
  739. _typeWriters.Add(typeof(byte), convertWriter);
  740. _typeWriters.Add(typeof(sbyte), convertWriter);
  741. // Date
  742. _typeWriters.Add(typeof(DateTime), (w, o) => convertWriter(w, Utils.ToUnixMilliseconds((DateTime)o)));
  743. // Floating point
  744. _typeWriters.Add(typeof(float), (w, o) => w.WriteRaw(((float)o).ToString("R", System.Globalization.CultureInfo.InvariantCulture)));
  745. _typeWriters.Add(typeof(double), (w, o) => w.WriteRaw(((double)o).ToString("R", System.Globalization.CultureInfo.InvariantCulture)));
  746. // Byte array
  747. _typeWriters.Add(typeof(byte[]), (w, o) =>
  748. {
  749. w.WriteRaw("\"");
  750. w.WriteRaw(Convert.ToBase64String((byte[])o));
  751. w.WriteRaw("\"");
  752. });
  753. }
  754. public static Dictionary<Type, Action<IJsonWriter, object>> _typeWriters = new Dictionary<Type, Action<IJsonWriter, object>>();
  755. public static Func<Type, Action<IJsonWriter, object>> _typeWriterResolver;
  756. static Action<IJsonWriter, object> ResolveTypeWriter(Type type)
  757. {
  758. var ri = ReflectionInfo.GetReflectionInfo(type);
  759. if (ri != null)
  760. return ri.Write;
  761. else
  762. return null;
  763. }
  764. public Writer(TextWriter w, JsonOptions options)
  765. {
  766. _writer = w;
  767. _atStartOfLine = true;
  768. _needElementSeparator = false;
  769. _options = options;
  770. }
  771. TextWriter _writer;
  772. public int IndentLevel;
  773. bool _atStartOfLine;
  774. bool _needElementSeparator = false;
  775. JsonOptions _options;
  776. char _currentBlockKind = '\0';
  777. public void NextLine()
  778. {
  779. if (_atStartOfLine)
  780. return;
  781. if ((_options & JsonOptions.WriteWhitespace)!=0)
  782. {
  783. WriteRaw("\n");
  784. WriteRaw(new string('\t', IndentLevel));
  785. }
  786. _atStartOfLine = true;
  787. }
  788. void NextElement()
  789. {
  790. if (_needElementSeparator)
  791. {
  792. WriteRaw(",");
  793. NextLine();
  794. }
  795. else
  796. {
  797. NextLine();
  798. IndentLevel++;
  799. WriteRaw(_currentBlockKind.ToString());
  800. NextLine();
  801. }
  802. _needElementSeparator = true;
  803. }
  804. public void WriteElement()
  805. {
  806. if (_currentBlockKind != '[')
  807. throw new InvalidOperationException("Attempt to write array element when not in array block");
  808. NextElement();
  809. }
  810. public void WriteKey(string key)
  811. {
  812. if (_currentBlockKind != '{')
  813. throw new InvalidOperationException("Attempt to write dictionary element when not in dictionary block");
  814. NextElement();
  815. WriteStringLiteral(key);
  816. WriteRaw(((_options & JsonOptions.WriteWhitespace) != 0) ? ": " : ":");
  817. }
  818. public void WriteKeyNoEscaping(string key)
  819. {
  820. if (_currentBlockKind != '{')
  821. throw new InvalidOperationException("Attempt to write dictionary element when not in dictionary block");
  822. NextElement();
  823. WriteRaw("\"");
  824. WriteRaw(key);
  825. WriteRaw("\"");
  826. WriteRaw(((_options & JsonOptions.WriteWhitespace) != 0) ? ": " : ":");
  827. }
  828. public void WriteRaw(string str)
  829. {
  830. _atStartOfLine = false;
  831. _writer.Write(str);
  832. }
  833. static char[] _charsToEscape = new char[] { '\"', '\r', '\n', '\t', '\f', '\0', '\\', '\'' };
  834. public void WriteStringLiteral(string str)
  835. {
  836. _writer.Write("\"");
  837. int pos = 0;
  838. int escapePos;
  839. while ((escapePos = str.IndexOfAny(_charsToEscape, pos)) >= 0)
  840. {
  841. if (escapePos > pos)
  842. _writer.Write(str.Substring(pos, escapePos - pos));
  843. switch (str[escapePos])
  844. {
  845. case '\"': _writer.Write("\\\""); break;
  846. case '\r': _writer.Write("\\r"); break;
  847. case '\n': _writer.Write("\\n"); break;
  848. case '\t': _writer.Write("\\t"); break;
  849. case '\f': _writer.Write("\\f"); break;
  850. case '\0': _writer.Write("\\0"); break;
  851. case '\\': _writer.Write("\\\\"); break;
  852. case '\'': _writer.Write("\\'"); break;
  853. }
  854. pos = escapePos + 1;
  855. }
  856. if (str.Length > pos)
  857. _writer.Write(str.Substring(pos));
  858. _writer.Write("\"");
  859. }
  860. public void WriteStringLiteralX(string str)
  861. {
  862. _writer.Write("\"");
  863. foreach (var ch in str)
  864. {
  865. switch (ch)
  866. {
  867. case '\"': _writer.Write("\\\""); break;
  868. case '\r': _writer.Write("\\r"); break;
  869. case '\n': _writer.Write("\\n"); break;
  870. case '\t': _writer.Write("\\t"); break;
  871. case '\0': _writer.Write("\\0"); break;
  872. case '\\': _writer.Write("\\\\"); break;
  873. case '\'': _writer.Write("\\'"); break;
  874. default: _writer.Write(ch); break;
  875. }
  876. }
  877. _writer.Write("\"");
  878. }
  879. void WriteBlock(string open, string close, Action callback)
  880. {
  881. var prevBlockKind = _currentBlockKind;
  882. _currentBlockKind = open[0];
  883. var didNeedElementSeparator = _needElementSeparator;
  884. _needElementSeparator = false;
  885. callback();
  886. if (_needElementSeparator)
  887. {
  888. IndentLevel--;
  889. NextLine();
  890. }
  891. else
  892. {
  893. WriteRaw(open);
  894. }
  895. WriteRaw(close);
  896. _needElementSeparator = didNeedElementSeparator;
  897. _currentBlockKind = prevBlockKind;
  898. }
  899. public void WriteArray(Action callback)
  900. {
  901. WriteBlock("[", "]", callback);
  902. }
  903. public void WriteDictionary(Action callback)
  904. {
  905. WriteBlock("{", "}", callback);
  906. }
  907. public void WriteValue(object value)
  908. {
  909. // Special handling for null
  910. if (value == null)
  911. {
  912. _writer.Write("null");
  913. return;
  914. }
  915. var type = value.GetType();
  916. // Handle nullable types
  917. var typeUnderlying = Nullable.GetUnderlyingType(type);
  918. if (typeUnderlying != null)
  919. type = typeUnderlying;
  920. // Look up type writer
  921. Action<IJsonWriter, object> typeWriter;
  922. if (_typeWriters.TryGetValue(type, out typeWriter))
  923. {
  924. // Write it
  925. typeWriter(this, value);
  926. return;
  927. }
  928. // Enumerated type?
  929. if (type.IsEnum)
  930. {
  931. WriteStringLiteral(value.ToString());
  932. return;
  933. }
  934. // Dictionary?
  935. var d = value as System.Collections.IDictionary;
  936. if (d != null)
  937. {
  938. WriteDictionary(() =>
  939. {
  940. foreach (var key in d.Keys)
  941. {
  942. WriteKey(key.ToString());
  943. WriteValue(d[key]);
  944. }
  945. });
  946. return;
  947. }
  948. // Array?
  949. var e = value as System.Collections.IEnumerable;
  950. if (e != null)
  951. {
  952. WriteArray(() =>
  953. {
  954. foreach (var i in e)
  955. {
  956. WriteElement();
  957. WriteValue(i);
  958. }
  959. });
  960. return;
  961. }
  962. // Try using reflection
  963. var tw = _typeWriterResolver(type);
  964. if (tw != null)
  965. {
  966. _typeWriters[type] = tw;
  967. tw(this, value);
  968. return;
  969. }
  970. // What the?
  971. throw new InvalidDataException(string.Format("Don't know how to write '{0}' to json", value.GetType()));
  972. }
  973. }
  974. public class JsonMemberInfo
  975. {
  976. public string JsonKey;
  977. public bool KeepInstance;
  978. MemberInfo _mi;
  979. public MemberInfo Member
  980. {
  981. get { return _mi; }
  982. set
  983. {
  984. _mi = value;
  985. if (_mi is PropertyInfo)
  986. {
  987. GetValue = CreateGetter((PropertyInfo)_mi);
  988. SetValue = CreateSetter((PropertyInfo)_mi);
  989. }
  990. else
  991. {
  992. GetValue = CreateGetter((FieldInfo)_mi);
  993. SetValue = CreateSetter((FieldInfo)_mi);
  994. }
  995. }
  996. }
  997. public Type MemberType
  998. {
  999. get
  1000. {
  1001. if (Member is PropertyInfo)
  1002. {
  1003. return ((PropertyInfo)Member).PropertyType;
  1004. }
  1005. else
  1006. {
  1007. return ((FieldInfo)Member).FieldType;
  1008. }
  1009. }
  1010. }
  1011. public Action<object, object> SetValue;
  1012. public Func<object, object> GetValue;
  1013. public static Action<object, object> CreateSetter(PropertyInfo pi) { return (obj, val) => pi.SetValue(obj, val, null); }
  1014. public static Action<object, object> CreateSetter(FieldInfo fi) { return fi.SetValue; }
  1015. public static Func<object, object> CreateGetter(PropertyInfo pi) { return (obj) => pi.GetValue(obj, null); }
  1016. public static Func<object, object> CreateGetter(FieldInfo fi) { return fi.GetValue; }
  1017. }
  1018. public class ReflectionInfo
  1019. {
  1020. public List<JsonMemberInfo> Members;
  1021. static Dictionary<Type, ReflectionInfo> _cache = new Dictionary<Type, ReflectionInfo>();
  1022. public void Write(IJsonWriter w, object val)
  1023. {
  1024. w.WriteDictionary(() =>
  1025. {
  1026. var writing = val as IJsonWriting;
  1027. if (writing != null)
  1028. writing.OnJsonWriting(w);
  1029. foreach (var jmi in Members)
  1030. {
  1031. w.WriteKeyNoEscaping(jmi.JsonKey);
  1032. w.WriteValue(jmi.GetValue(val));
  1033. }
  1034. var written = val as IJsonWritten;
  1035. if (written != null)
  1036. written.OnJsonWritten(w);
  1037. });
  1038. }
  1039. public void ParseInto(IJsonReader r, object into)
  1040. {
  1041. var loading = into as IJsonLoading;
  1042. r.ReadDictionary(key =>
  1043. {
  1044. if (loading != null)
  1045. {
  1046. loading.OnJsonLoading(r);
  1047. loading = null;
  1048. }
  1049. ParseFieldOrProperty(r, into, key);
  1050. });
  1051. var loaded = into as IJsonLoaded;
  1052. if (loaded != null)
  1053. loaded.OnJsonLoaded(r);
  1054. }
  1055. // The member info is stored in a list (as opposed to a dictionary) so that
  1056. // the json is written in the same order as the fields/properties are defined
  1057. // On loading, we assume the fields will be in the same order, but need to
  1058. // handle if they're not. This function performs a linear search, but
  1059. // starts after the last found item as an optimization that should work
  1060. // most of the time.
  1061. int _lastFoundIndex = 0;
  1062. bool FindMemberInfo(string name, out JsonMemberInfo found)
  1063. {
  1064. for (int i = 0; i < Members.Count; i++)
  1065. {
  1066. int index = (i + _lastFoundIndex) % Members.Count;
  1067. var jmi = Members[index];
  1068. if (jmi.JsonKey == name)
  1069. {
  1070. _lastFoundIndex = index;
  1071. found = jmi;
  1072. return true;
  1073. }
  1074. }
  1075. found = null;
  1076. return false;
  1077. }
  1078. public void ParseFieldOrProperty(IJsonReader r, object into, string key)
  1079. {
  1080. var lf = into as IJsonLoadField;
  1081. if (lf != null)
  1082. {
  1083. if (lf.OnJsonField(r, key))
  1084. return;
  1085. }
  1086. JsonMemberInfo jmi;
  1087. if (FindMemberInfo(key, out jmi))
  1088. {
  1089. if (jmi.KeepInstance)
  1090. {
  1091. var subInto = jmi.GetValue(into);
  1092. if (subInto != null)
  1093. {
  1094. r.ParseInto(subInto);
  1095. return;
  1096. }
  1097. }
  1098. var val = r.Parse(jmi.MemberType);
  1099. jmi.SetValue(into, val);
  1100. return;
  1101. }
  1102. }
  1103. public static ReflectionInfo GetReflectionInfo(Type type)
  1104. {
  1105. // Already created?
  1106. ReflectionInfo existing;
  1107. if (_cache.TryGetValue(type, out existing))
  1108. return existing;
  1109. // Does type have a [Json] attribute
  1110. bool typeMarked = type.GetCustomAttributes(typeof(JsonAttribute), true).OfType<JsonAttribute>().Any();
  1111. // Do any members have a [Json] attribute
  1112. bool anyFieldsMarked = GetAllFieldsAndProperties(type).Any(x => x.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().Any());
  1113. // Should we serialize all public methods?
  1114. bool serializeAllPublics = typeMarked || !anyFieldsMarked;
  1115. // Build
  1116. var ri = CreateReflectionInfo(type, mi =>
  1117. {
  1118. // Explicitly excluded?
  1119. if (mi.GetCustomAttributes(typeof(JsonExcludeAttribute), false).OfType<JsonExcludeAttribute>().Any())
  1120. return null;
  1121. // Get attributes
  1122. var attr = mi.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().FirstOrDefault();
  1123. if (attr != null)
  1124. {
  1125. return new JsonMemberInfo()
  1126. {
  1127. Member = mi,
  1128. JsonKey = attr.Key ?? mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
  1129. KeepInstance = attr.KeepInstance,
  1130. };
  1131. }
  1132. // Serialize all publics?
  1133. if (serializeAllPublics && IsPublic(mi))
  1134. {
  1135. return new JsonMemberInfo()
  1136. {
  1137. Member = mi,
  1138. JsonKey = mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
  1139. };
  1140. }
  1141. return null;
  1142. });
  1143. // Cache it
  1144. _cache[type] = ri;
  1145. return ri;
  1146. }
  1147. static bool IsPublic(MemberInfo mi)
  1148. {
  1149. // Public field
  1150. var fi = mi as FieldInfo;
  1151. if (fi!=null)
  1152. return fi.IsPublic;
  1153. // Public property
  1154. // (We only check the get method so we can work with anonymous types)
  1155. var pi = mi as PropertyInfo;
  1156. if (pi != null)
  1157. {
  1158. var gm = pi.GetGetMethod();
  1159. return (gm != null && gm.IsPublic);
  1160. }
  1161. return false;
  1162. }
  1163. public static ReflectionInfo CreateReflectionInfo(Type type, Func<MemberInfo, JsonMemberInfo> callback)
  1164. {
  1165. // Already created?
  1166. ReflectionInfo existing;
  1167. if (_cache.TryGetValue(type, out existing))
  1168. return existing;
  1169. // Work out properties and fields
  1170. var members = GetAllFieldsAndProperties(type).Select(x => callback(x)).Where(x => x != null).ToList();
  1171. var invalid = members.FirstOrDefault(x => x.KeepInstance && x.MemberType.IsValueType);
  1172. if (invalid!=null)
  1173. {
  1174. throw new InvalidOperationException(string.Format("KeepInstance=true can only be applied to reference types ({0}.{1})", type.FullName, invalid.Member));
  1175. }
  1176. // Must have some members
  1177. if (!members.Any())
  1178. return null;
  1179. // Create reflection info
  1180. var ri = new ReflectionInfo()
  1181. {
  1182. Members = members,
  1183. };
  1184. return ri;
  1185. }
  1186. static IEnumerable<MemberInfo> GetAllFieldsAndProperties(Type t)
  1187. {
  1188. if (t == null)
  1189. return Enumerable.Empty<FieldInfo>();
  1190. BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;
  1191. return t.GetMembers(flags).Where(x => x is FieldInfo || x is PropertyInfo).Concat(GetAllFieldsAndProperties(t.BaseType));
  1192. }
  1193. }
  1194. internal static class Utils
  1195. {
  1196. public static long ToUnixMilliseconds(DateTime This)
  1197. {
  1198. return (long)This.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
  1199. }
  1200. public static DateTime FromUnixMilliseconds(long timeStamp)
  1201. {
  1202. return new DateTime(1970, 1, 1).AddMilliseconds(timeStamp);
  1203. }
  1204. }
  1205. public class RewindableTextReader
  1206. {
  1207. public RewindableTextReader(TextReader underlying)
  1208. {
  1209. _underlying = underlying;
  1210. FillBuffer();
  1211. }
  1212. TextReader _underlying;
  1213. char[] _buf = new char[4096];
  1214. int _pos;
  1215. int _bufUsed;
  1216. StringBuilder _rewindBuffer;
  1217. int _rewindBufferPos;
  1218. void FillBuffer()
  1219. {
  1220. _bufUsed = _underlying.Read(_buf, 0, _buf.Length);
  1221. _pos = 0;
  1222. }
  1223. public char ReadChar()
  1224. {
  1225. if (_rewindBuffer == null)
  1226. {
  1227. if (_pos >= _bufUsed)
  1228. {
  1229. if (_bufUsed > 0)
  1230. {
  1231. FillBuffer();
  1232. }
  1233. if (_bufUsed == 0)
  1234. {
  1235. return '\0';
  1236. }
  1237. }
  1238. // Next
  1239. return _buf[_pos++];
  1240. }
  1241. if (_rewindBufferPos < _rewindBuffer.Length)
  1242. {
  1243. return _rewindBuffer[_rewindBufferPos++];
  1244. }
  1245. else
  1246. {
  1247. if (_pos >= _bufUsed && _bufUsed > 0)
  1248. FillBuffer();
  1249. char ch = _bufUsed == 0 ? '\0' : _buf[_pos++];
  1250. _rewindBuffer.Append(ch);
  1251. _rewindBufferPos++;
  1252. return ch;
  1253. }
  1254. }
  1255. Stack<int> _bookmarks = new Stack<int>();
  1256. public void CreateBookmark()
  1257. {
  1258. if (_rewindBuffer == null)
  1259. {
  1260. _rewindBuffer = new StringBuilder();
  1261. _rewindBufferPos = 0;
  1262. }
  1263. _bookmarks.Push(_rewindBufferPos);
  1264. }
  1265. public void RewindToBookmark()
  1266. {
  1267. _rewindBufferPos = _bookmarks.Pop();
  1268. }
  1269. public void DiscardBookmark()
  1270. {
  1271. _bookmarks.Pop();
  1272. if (_bookmarks.Count == 0)
  1273. {
  1274. _rewindBuffer = null;
  1275. _rewindBufferPos = 0;
  1276. }
  1277. }
  1278. }
  1279. public class Tokenizer
  1280. {
  1281. public Tokenizer(TextReader r, JsonOptions options)
  1282. {
  1283. _reader = new RewindableTextReader(r);
  1284. _options = options;
  1285. // Load up
  1286. NextChar();
  1287. NextToken();
  1288. }
  1289. RewindableTextReader _reader;
  1290. JsonOptions _options;
  1291. StringBuilder _sb = new StringBuilder();
  1292. JsonLineOffset _currentCharPos;
  1293. JsonLineOffset CurrentTokenPos;
  1294. char _currentChar;
  1295. char _pendingChar;
  1296. public Token CurrentToken;
  1297. public LiteralKind LiteralKind;
  1298. public string String;
  1299. public object LiteralValue
  1300. {
  1301. get
  1302. {
  1303. if (CurrentToken != Token.Literal)
  1304. throw new InvalidOperationException("token is not a literal");
  1305. switch (LiteralKind)
  1306. {
  1307. case LiteralKind.Null: return null;
  1308. case LiteralKind.False: return false;
  1309. case LiteralKind.True: return true;
  1310. case LiteralKind.String: return String;
  1311. case LiteralKind.SignedInteger: return long.Parse(String, CultureInfo.InvariantCulture);
  1312. case LiteralKind.UnsignedInteger: return ulong.Parse(String, CultureInfo.InvariantCulture);
  1313. case LiteralKind.FloatingPoint: return double.Parse(String, CultureInfo.InvariantCulture);
  1314. }
  1315. return null;
  1316. }
  1317. }
  1318. public Type LiteralType
  1319. {
  1320. get
  1321. {
  1322. if (CurrentToken != Token.Literal)
  1323. throw new InvalidOperationException("token is not a literal");
  1324. switch (LiteralKind)
  1325. {
  1326. case LiteralKind.Null: return typeof(Object);
  1327. case LiteralKind.False: return typeof(Boolean);
  1328. case LiteralKind.True: return typeof(Boolean);
  1329. case LiteralKind.String: return typeof(string);
  1330. case LiteralKind.SignedInteger: return typeof(long);
  1331. case LiteralKind.UnsignedInteger: return typeof(ulong);
  1332. case LiteralKind.FloatingPoint: return typeof(double);
  1333. }
  1334. return null;
  1335. }
  1336. }
  1337. // this object represents the entire state of the reader
  1338. // which when combined with the RewindableTextReader allows
  1339. // use to rewind to an arbitrary point in the token stream
  1340. struct ReaderState
  1341. {
  1342. public ReaderState(Tokenizer tokenizer)
  1343. {
  1344. _currentCharPos = tokenizer._currentCharPos;
  1345. CurrentTokenPos = tokenizer.CurrentTokenPos;
  1346. _currentChar = tokenizer._currentChar;
  1347. _pendingChar = tokenizer._pendingChar;
  1348. CurrentToken = tokenizer.CurrentToken;
  1349. _string = tokenizer.String;
  1350. _literalKind = tokenizer.LiteralKind;
  1351. }
  1352. public void Apply(Tokenizer tokenizer)
  1353. {
  1354. tokenizer._currentCharPos = _currentCharPos;
  1355. tokenizer.CurrentTokenPos = CurrentTokenPos;
  1356. tokenizer._currentChar = _currentChar;
  1357. tokenizer._pendingChar = _pendingChar;
  1358. tokenizer.CurrentToken = CurrentToken;
  1359. tokenizer.String = _string;
  1360. tokenizer.LiteralKind = _literalKind;
  1361. }
  1362. public JsonLineOffset _currentCharPos;
  1363. public JsonLineOffset CurrentTokenPos;
  1364. public char _currentChar;
  1365. public char _pendingChar;
  1366. public Token CurrentToken;
  1367. public LiteralKind _literalKind;
  1368. public string _string;
  1369. }
  1370. Stack<ReaderState> _bookmarks = new Stack<ReaderState>();
  1371. public void CreateBookmark()
  1372. {
  1373. _bookmarks.Push(new ReaderState(this));
  1374. _reader.CreateBookmark();
  1375. }
  1376. public void DiscardBookmark()
  1377. {
  1378. _bookmarks.Pop();
  1379. _reader.DiscardBookmark();
  1380. }
  1381. public void RewindToBookmark()
  1382. {
  1383. _bookmarks.Pop().Apply(this);
  1384. _reader.RewindToBookmark();
  1385. }
  1386. char NextChar()
  1387. {
  1388. _currentCharPos.Offset++;
  1389. return _currentChar = _reader.ReadChar();
  1390. }
  1391. public void NextToken()
  1392. {
  1393. while (true)
  1394. {
  1395. while (true)
  1396. {
  1397. if (_currentChar == '\r')
  1398. {
  1399. if (NextChar() == '\n')
  1400. {
  1401. NextChar();
  1402. }
  1403. _currentCharPos.Line++;
  1404. _currentCharPos.Offset = 0;
  1405. }
  1406. else if (_currentChar == '\n')
  1407. {
  1408. if (NextChar() == '\r')
  1409. {
  1410. NextChar();
  1411. }
  1412. _currentCharPos.Line++;
  1413. _currentCharPos.Offset = 0;
  1414. }
  1415. else if (_currentChar == ' ')
  1416. {
  1417. NextChar();
  1418. }
  1419. else if (_currentChar == '\t')
  1420. {
  1421. NextChar();
  1422. }
  1423. else
  1424. break;
  1425. }
  1426. CurrentTokenPos = _currentCharPos;
  1427. if (IsIdentifierLeadChar(_currentChar))
  1428. {
  1429. _sb.Length = 0;
  1430. while (IsIdentifierChar(_currentChar))
  1431. {
  1432. _sb.Append(_currentChar);
  1433. NextChar();
  1434. }
  1435. String = _sb.ToString();
  1436. switch (String)
  1437. {
  1438. case "true":
  1439. LiteralKind = LiteralKind.True;
  1440. CurrentToken = Token.Literal;
  1441. break;
  1442. case "false":
  1443. LiteralKind = LiteralKind.False;
  1444. CurrentToken = Token.Literal;
  1445. break;
  1446. case "null":
  1447. LiteralKind = LiteralKind.Null;
  1448. CurrentToken = Token.Literal;
  1449. break;
  1450. default:
  1451. CurrentToken = Token.Identifier;
  1452. break;
  1453. }
  1454. return;
  1455. }
  1456. if (char.IsDigit(_currentChar) || _currentChar == '-')
  1457. {
  1458. TokenizeNumber();
  1459. CurrentToken = Token.Literal;
  1460. return;
  1461. }
  1462. switch (_currentChar)
  1463. {
  1464. case '/':
  1465. if ((_options & JsonOptions.StrictParser)!=0)
  1466. {
  1467. // Comments not support in strict mode
  1468. throw new InvalidDataException(string.Format("syntax error - unexpected character '{0}'", _currentChar));
  1469. }
  1470. else
  1471. {
  1472. NextChar();
  1473. switch (_currentChar)
  1474. {
  1475. case '/':
  1476. NextChar();
  1477. while (_currentChar!='\0' && _currentChar != '\r' && _currentChar != '\n')
  1478. {
  1479. NextChar();
  1480. }
  1481. break;
  1482. case '*':
  1483. bool endFound = false;
  1484. while (!endFound && _currentChar!='\0')
  1485. {
  1486. if (_currentChar == '*')
  1487. {
  1488. NextChar();
  1489. if (_currentChar == '/')
  1490. {
  1491. endFound = true;
  1492. }
  1493. }
  1494. NextChar();
  1495. }
  1496. break;
  1497. default:
  1498. throw new InvalidDataException("syntax error - unexpected character after slash");
  1499. }
  1500. }
  1501. break;
  1502. case '\"':
  1503. case '\'':
  1504. {
  1505. _sb.Length = 0;
  1506. var quoteKind = _currentChar;
  1507. NextChar();
  1508. while (_currentChar!='\0')
  1509. {
  1510. if (_currentChar == '\\')
  1511. {
  1512. NextChar();
  1513. var escape = _currentChar;
  1514. switch (escape)
  1515. {
  1516. case '\'': _sb.Append('\''); break;
  1517. case '\"': _sb.Append('\"'); break;
  1518. case '\\': _sb.Append('\\'); break;
  1519. case 'r': _sb.Append('\r'); break;
  1520. case 'f': _sb.Append('\f'); break;
  1521. case 'n': _sb.Append('\n'); break;
  1522. case 't': _sb.Append('\t'); break;
  1523. case '0': _sb.Append('\0'); break;
  1524. case 'u':
  1525. var sbHex = new StringBuilder();
  1526. for (int i = 0; i < 4; i++)
  1527. {
  1528. NextChar();
  1529. sbHex.Append(_currentChar);
  1530. }
  1531. _sb.Append((char)Convert.ToUInt16(sbHex.ToString(), 16));
  1532. break;
  1533. default:
  1534. throw new InvalidDataException(string.Format("Invalid escape sequence in string literal: '\\{0}'", _currentChar));
  1535. }
  1536. }
  1537. else if (_currentChar == quoteKind)
  1538. {
  1539. String = _sb.ToString();
  1540. CurrentToken = Token.Literal;
  1541. LiteralKind = LiteralKind.String;
  1542. NextChar();
  1543. return;
  1544. }
  1545. else
  1546. {
  1547. _sb.Append(_currentChar);
  1548. }
  1549. NextChar();
  1550. }
  1551. throw new InvalidDataException("syntax error - unterminated string literal");
  1552. }
  1553. case '\0':
  1554. CurrentToken = Token.EOF;
  1555. return;
  1556. case '{': CurrentToken = Token.OpenBrace; NextChar(); return;
  1557. case '}': CurrentToken = Token.CloseBrace; NextChar(); return;
  1558. case '[': CurrentToken = Token.OpenSquare; NextChar(); return;
  1559. case ']': CurrentToken = Token.CloseSquare; NextChar(); return;
  1560. case '=': CurrentToken = Token.Equal; NextChar(); return;
  1561. case ':': CurrentToken = Token.Colon; NextChar(); return;
  1562. case ';': CurrentToken = Token.SemiColon; NextChar(); return;
  1563. case ',': CurrentToken = Token.Comma; NextChar(); return;
  1564. default:
  1565. throw new InvalidDataException(string.Format("syntax error - unexpected character '{0}'", _currentChar));
  1566. }
  1567. }
  1568. }
  1569. void TokenizeNumber()
  1570. {
  1571. _sb.Length = 0;
  1572. // Leading -
  1573. bool signed = false;
  1574. if (_currentChar == '-')
  1575. {
  1576. signed = true;
  1577. _sb.Append(_currentChar);
  1578. NextChar();
  1579. if (!Char.IsDigit(_currentChar))
  1580. {
  1581. throw new InvalidDataException("syntax error - expected digit to follow negative sign");
  1582. }
  1583. }
  1584. // Parse all digits
  1585. bool fp = false;
  1586. while (char.IsDigit(_currentChar) || _currentChar == '.' || _currentChar == 'e' || _currentChar == 'E' || _currentChar == 'x' || _currentChar == 'X')
  1587. {
  1588. if (_currentChar == 'e' || _currentChar == 'E')
  1589. {
  1590. fp = true;
  1591. _sb.Append(_currentChar);
  1592. NextChar();
  1593. if (_currentChar == '-' || _currentChar == '+')
  1594. {
  1595. _sb.Append(_currentChar);
  1596. NextChar();
  1597. }
  1598. }
  1599. else
  1600. {
  1601. if (_currentChar == '.')
  1602. fp = true;
  1603. _sb.Append(_currentChar);
  1604. NextChar();
  1605. }
  1606. }
  1607. Type type = fp ? typeof(double) : (signed ? typeof(long) : typeof(ulong));
  1608. if (char.IsLetterOrDigit(_currentChar))
  1609. throw new InvalidDataException(string.Format("syntax error - invalid character following number '{0}'", _currentChar));
  1610. String = _sb.ToString();
  1611. CurrentToken = Token.Literal;
  1612. if (fp)
  1613. {
  1614. LiteralKind = LiteralKind.FloatingPoint;
  1615. }
  1616. else if (signed)
  1617. {
  1618. LiteralKind = LiteralKind.SignedInteger;
  1619. }
  1620. else
  1621. {
  1622. LiteralKind = LiteralKind.UnsignedInteger;
  1623. }
  1624. /*
  1625. }
  1626. catch
  1627. {
  1628. throw new InvalidDataException(string.Format("syntax error - incorrectly formatted number '{0}'", _sb.ToString()));
  1629. }
  1630. */
  1631. }
  1632. public void Check(Token tokenRequired)
  1633. {
  1634. if (tokenRequired != CurrentToken)
  1635. {
  1636. throw new InvalidDataException(string.Format("syntax error - expected {0} found {1}", tokenRequired, CurrentToken));
  1637. }
  1638. }
  1639. public void Skip(Token tokenRequired)
  1640. {
  1641. Check(tokenRequired);
  1642. NextToken();
  1643. }
  1644. public bool SkipIf(Token tokenRequired)
  1645. {
  1646. if (tokenRequired == CurrentToken)
  1647. {
  1648. NextToken();
  1649. return true;
  1650. }
  1651. return false;
  1652. }
  1653. public JsonLineOffset CurrentTokenPosition
  1654. {
  1655. get { return CurrentTokenPos; }
  1656. }
  1657. public static bool IsIdentifierChar(char ch)
  1658. {
  1659. return Char.IsLetterOrDigit(ch) || ch == '_' || ch == '$';
  1660. }
  1661. public static bool IsIdentifierLeadChar(char ch)
  1662. {
  1663. return Char.IsLetter(ch) || ch == '_' || ch == '$';
  1664. }
  1665. }
  1666. }
  1667. }