PetaJson.cs 66 KB

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