PetaJson.cs 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846
  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. public void WriteStringLiteral(string str)
  773. {
  774. _writer.Write("\"");
  775. foreach (var ch in str)
  776. {
  777. switch (ch)
  778. {
  779. case '\"': _writer.Write("\\\""); break;
  780. case '\r': _writer.Write("\\r"); break;
  781. case '\n': _writer.Write("\\n"); break;
  782. case '\t': _writer.Write("\\t"); break;
  783. case '\0': _writer.Write("\\0"); break;
  784. case '\\': _writer.Write("\\\\"); break;
  785. case '\'': _writer.Write("\\'"); break;
  786. default: _writer.Write(ch); break;
  787. }
  788. }
  789. _writer.Write("\"");
  790. }
  791. void WriteBlock(string open, string close, Action callback)
  792. {
  793. var prevBlockKind = _currentBlockKind;
  794. _currentBlockKind = open[0];
  795. var didNeedElementSeparator = _needElementSeparator;
  796. _needElementSeparator = false;
  797. callback();
  798. if (_needElementSeparator)
  799. {
  800. IndentLevel--;
  801. NextLine();
  802. }
  803. else
  804. {
  805. WriteRaw(open);
  806. }
  807. WriteRaw(close);
  808. _needElementSeparator = didNeedElementSeparator;
  809. _currentBlockKind = prevBlockKind;
  810. }
  811. public void WriteArray(Action callback)
  812. {
  813. WriteBlock("[", "]", callback);
  814. }
  815. public void WriteDictionary(Action callback)
  816. {
  817. WriteBlock("{", "}", callback);
  818. }
  819. public void WriteValue(object value)
  820. {
  821. // Special handling for null
  822. if (value == null)
  823. {
  824. _writer.Write("null");
  825. return;
  826. }
  827. var type = value.GetType();
  828. // Handle nullable types
  829. var typeUnderlying = Nullable.GetUnderlyingType(type);
  830. if (typeUnderlying != null)
  831. type = typeUnderlying;
  832. // Look up type writer
  833. Action<IJsonWriter, object> typeWriter;
  834. if (_typeWriters.TryGetValue(type, out typeWriter))
  835. {
  836. // Write it
  837. typeWriter(this, value);
  838. return;
  839. }
  840. // Enumerated type?
  841. if (type.IsEnum)
  842. {
  843. WriteStringLiteral(value.ToString());
  844. return;
  845. }
  846. // Dictionary?
  847. var d = value as System.Collections.IDictionary;
  848. if (d != null)
  849. {
  850. WriteDictionary(() =>
  851. {
  852. foreach (var key in d.Keys)
  853. {
  854. WriteKey(key.ToString());
  855. WriteValue(d[key]);
  856. }
  857. });
  858. return;
  859. }
  860. // Array?
  861. var e = value as System.Collections.IEnumerable;
  862. if (e != null)
  863. {
  864. WriteArray(() =>
  865. {
  866. foreach (var i in e)
  867. {
  868. WriteElement();
  869. WriteValue(i);
  870. }
  871. });
  872. return;
  873. }
  874. // Try using reflection
  875. var ri = ReflectionInfo.GetReflectionInfo(type);
  876. if (ri != null)
  877. {
  878. ri.Write(this, value);
  879. return;
  880. }
  881. // What the?
  882. throw new InvalidDataException(string.Format("Don't know how to write '{0}' to json", value.GetType()));
  883. }
  884. }
  885. class JsonMemberInfo
  886. {
  887. public MemberInfo Member;
  888. public string JsonKey;
  889. public bool KeepInstance;
  890. public Type MemberType
  891. {
  892. get
  893. {
  894. if (Member is PropertyInfo)
  895. {
  896. return ((PropertyInfo)Member).PropertyType;
  897. }
  898. else
  899. {
  900. return ((FieldInfo)Member).FieldType;
  901. }
  902. }
  903. }
  904. public void SetValue(object target, object value)
  905. {
  906. if (Member is PropertyInfo)
  907. {
  908. ((PropertyInfo)Member).SetValue(target, value, null);
  909. }
  910. else
  911. {
  912. ((FieldInfo)Member).SetValue(target, value);
  913. }
  914. }
  915. public object GetValue(object target)
  916. {
  917. if (Member is PropertyInfo)
  918. {
  919. return ((PropertyInfo)Member).GetValue(target, null);
  920. }
  921. else
  922. {
  923. return ((FieldInfo)Member).GetValue(target);
  924. }
  925. }
  926. }
  927. class ReflectionInfo
  928. {
  929. List<JsonMemberInfo> _members;
  930. static Dictionary<Type, ReflectionInfo> _cache = new Dictionary<Type, ReflectionInfo>();
  931. public void Write(Writer w, object val)
  932. {
  933. w.WriteDictionary(() =>
  934. {
  935. var writing = val as IJsonWriting;
  936. if (writing != null)
  937. writing.OnJsonWriting(w);
  938. foreach (var jmi in _members)
  939. {
  940. w.WriteKey(jmi.JsonKey);
  941. w.WriteValue(jmi.GetValue(val));
  942. }
  943. var written = val as IJsonWritten;
  944. if (written != null)
  945. written.OnJsonWritten(w);
  946. });
  947. }
  948. // The member info is stored in a list (as opposed to a dictionary) so that
  949. // the json is written in the same order as the fields/properties are defined
  950. // On loading, we assume the fields will be in the same order, but need to
  951. // handle if they're not. This function performs a linear search, but
  952. // starts after the last found item as an optimization that should work
  953. // most of the time.
  954. int _lastFoundIndex = 0;
  955. bool FindMemberInfo(string name, out JsonMemberInfo found)
  956. {
  957. for (int i = 0; i < _members.Count; i++)
  958. {
  959. int index = (i + _lastFoundIndex) % _members.Count;
  960. var jmi = _members[index];
  961. if (jmi.JsonKey == name)
  962. {
  963. _lastFoundIndex = index;
  964. found = jmi;
  965. return true;
  966. }
  967. }
  968. found = null;
  969. return false;
  970. }
  971. public void ParseFieldOrProperty(Reader r, object into, string key)
  972. {
  973. var lf = into as IJsonLoadField;
  974. if (lf != null)
  975. {
  976. if (lf.OnJsonField(r, key))
  977. return;
  978. }
  979. JsonMemberInfo jmi;
  980. if (FindMemberInfo(key, out jmi))
  981. {
  982. if (jmi.KeepInstance && Reader.CanParseInto(jmi.MemberType))
  983. {
  984. var subInto = jmi.GetValue(into);
  985. if (subInto != null)
  986. {
  987. r.ParseInto(subInto);
  988. return;
  989. }
  990. }
  991. var val = r.Parse(jmi.MemberType);
  992. jmi.SetValue(into, val);
  993. return;
  994. }
  995. }
  996. public void ParseInto(Reader r, object into)
  997. {
  998. var loading = into as IJsonLoading;
  999. r.ReadDictionary(key => {
  1000. if (loading != null)
  1001. {
  1002. loading.OnJsonLoading(r);
  1003. loading = null;
  1004. }
  1005. ParseFieldOrProperty(r, into, key);
  1006. });
  1007. var loaded = into as IJsonLoaded;
  1008. if (loaded != null)
  1009. loaded.OnJsonLoaded(r);
  1010. }
  1011. public static ReflectionInfo GetReflectionInfo(Type type)
  1012. {
  1013. // Already created?
  1014. ReflectionInfo existing;
  1015. if (_cache.TryGetValue(type, out existing))
  1016. return existing;
  1017. // Does type have a [Json] attribute
  1018. bool typeMarked = type.GetCustomAttributes(typeof(JsonAttribute), true).OfType<JsonAttribute>().Any();
  1019. // Do any members have a [Json] attribute
  1020. bool anyFieldsMarked = GetAllFieldsAndProperties(type).Any(x => x.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().Any());
  1021. // Should we serialize all public methods?
  1022. bool serializeAllPublics = typeMarked || !anyFieldsMarked;
  1023. // Build
  1024. var ri = CreateReflectionInfo(type, mi =>
  1025. {
  1026. // Explicitly excluded?
  1027. if (mi.GetCustomAttributes(typeof(JsonExcludeAttribute), false).OfType<JsonExcludeAttribute>().Any())
  1028. return null;
  1029. // Get attributes
  1030. var attr = mi.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().FirstOrDefault();
  1031. if (attr != null)
  1032. {
  1033. return new JsonMemberInfo()
  1034. {
  1035. Member = mi,
  1036. JsonKey = attr.Key ?? mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
  1037. KeepInstance = attr.KeepInstance,
  1038. };
  1039. }
  1040. // Serialize all publics?
  1041. if (serializeAllPublics && IsPublic(mi))
  1042. {
  1043. return new JsonMemberInfo()
  1044. {
  1045. Member = mi,
  1046. JsonKey = mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
  1047. };
  1048. }
  1049. return null;
  1050. });
  1051. // Cache it
  1052. _cache[type] = ri;
  1053. return ri;
  1054. }
  1055. static bool IsPublic(MemberInfo mi)
  1056. {
  1057. // Public field
  1058. var fi = mi as FieldInfo;
  1059. if (fi!=null)
  1060. return fi.IsPublic;
  1061. // Public property
  1062. // (We only check the get method so we can work with anonymous types)
  1063. var pi = mi as PropertyInfo;
  1064. if (pi != null)
  1065. {
  1066. var gm = pi.GetGetMethod();
  1067. return (gm != null && gm.IsPublic);
  1068. }
  1069. return false;
  1070. }
  1071. public static ReflectionInfo CreateReflectionInfo(Type type, Func<MemberInfo, JsonMemberInfo> callback)
  1072. {
  1073. // Already created?
  1074. ReflectionInfo existing;
  1075. if (_cache.TryGetValue(type, out existing))
  1076. return existing;
  1077. // Work out properties and fields
  1078. var members = GetAllFieldsAndProperties(type).Select(x => callback(x)).Where(x => x != null).ToList();
  1079. // Must have some members
  1080. if (!members.Any())
  1081. return null;
  1082. // Create reflection info
  1083. var ri = new ReflectionInfo()
  1084. {
  1085. _members = members,
  1086. };
  1087. return ri;
  1088. }
  1089. static IEnumerable<MemberInfo> GetAllFieldsAndProperties(Type t)
  1090. {
  1091. if (t == null)
  1092. return Enumerable.Empty<FieldInfo>();
  1093. BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;
  1094. return t.GetMembers(flags).Where(x => x is FieldInfo || x is PropertyInfo).Concat(GetAllFieldsAndProperties(t.BaseType));
  1095. }
  1096. }
  1097. internal static class Utils
  1098. {
  1099. public static long ToUnixMilliseconds(DateTime This)
  1100. {
  1101. return (long)This.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
  1102. }
  1103. public static DateTime FromUnixMilliseconds(long timeStamp)
  1104. {
  1105. return new DateTime(1970, 1, 1).AddMilliseconds(timeStamp);
  1106. }
  1107. }
  1108. public class RewindableTextReader
  1109. {
  1110. public RewindableTextReader(TextReader underlying)
  1111. {
  1112. _underlying = underlying;
  1113. ReadUnderlying();
  1114. }
  1115. TextReader _underlying;
  1116. char[] _buf = new char[1024];
  1117. int _pos;
  1118. int _bufUsed;
  1119. StringBuilder _rewindBuffer;
  1120. int _rewindBufferPos;
  1121. void ReadUnderlying()
  1122. {
  1123. _bufUsed = _underlying.Read(_buf, 0, _buf.Length);
  1124. _pos = 0;
  1125. }
  1126. char ReadUnderlyingChar()
  1127. {
  1128. if (_pos >= _bufUsed)
  1129. {
  1130. if (_bufUsed > 0)
  1131. {
  1132. ReadUnderlying();
  1133. }
  1134. if (_bufUsed == 0)
  1135. {
  1136. return '\0';
  1137. }
  1138. }
  1139. // Next
  1140. return _buf[_pos++];
  1141. }
  1142. public char ReadChar()
  1143. {
  1144. if (_rewindBuffer == null)
  1145. return ReadUnderlyingChar();
  1146. if (_rewindBufferPos < _rewindBuffer.Length)
  1147. {
  1148. return _rewindBuffer[_rewindBufferPos++];
  1149. }
  1150. else
  1151. {
  1152. char ch = ReadUnderlyingChar();
  1153. _rewindBuffer.Append(ch);
  1154. _rewindBufferPos++;
  1155. return ch;
  1156. }
  1157. }
  1158. Stack<int> _bookmarks = new Stack<int>();
  1159. public void CreateBookmark()
  1160. {
  1161. if (_rewindBuffer == null)
  1162. {
  1163. _rewindBuffer = new StringBuilder();
  1164. _rewindBufferPos = 0;
  1165. }
  1166. _bookmarks.Push(_rewindBufferPos);
  1167. }
  1168. public void RewindToBookmark()
  1169. {
  1170. _rewindBufferPos = _bookmarks.Pop();
  1171. }
  1172. public void DiscardBookmark()
  1173. {
  1174. _bookmarks.Pop();
  1175. if (_bookmarks.Count == 0)
  1176. {
  1177. _rewindBuffer = null;
  1178. _rewindBufferPos = 0;
  1179. }
  1180. }
  1181. }
  1182. public class Tokenizer
  1183. {
  1184. public Tokenizer(TextReader r, JsonOptions options)
  1185. {
  1186. _reader = new RewindableTextReader(r);
  1187. _options = options;
  1188. _state._nextCharPos.Line = 0;
  1189. _state._nextCharPos.Offset = 0;
  1190. _state._currentCharPos = _state._nextCharPos;
  1191. // Load up
  1192. NextChar();
  1193. NextToken();
  1194. }
  1195. RewindableTextReader _reader;
  1196. JsonOptions _options;
  1197. StringBuilder _sb = new StringBuilder();
  1198. ReaderState _state;
  1199. // this object represents the entire state of the reader
  1200. // which when combined with the RewindableTextReader allows
  1201. // use to rewind to an arbitrary point in the token stream
  1202. struct ReaderState
  1203. {
  1204. public JsonLineOffset _nextCharPos;
  1205. public JsonLineOffset _currentCharPos;
  1206. public JsonLineOffset _currentTokenPos;
  1207. public char _currentChar;
  1208. public char _pendingChar;
  1209. public Token _currentToken;
  1210. public string _string;
  1211. public object _literal;
  1212. }
  1213. Stack<ReaderState> _bookmarks = new Stack<ReaderState>();
  1214. public void CreateBookmark()
  1215. {
  1216. _bookmarks.Push(_state);
  1217. _reader.CreateBookmark();
  1218. }
  1219. public void DiscardBookmark()
  1220. {
  1221. _bookmarks.Pop();
  1222. _reader.DiscardBookmark();
  1223. }
  1224. public void RewindToBookmark()
  1225. {
  1226. _state = _bookmarks.Pop();
  1227. _reader.RewindToBookmark();
  1228. }
  1229. char NextChar()
  1230. {
  1231. // Normalize line endings to '\n'
  1232. char ch;
  1233. if (_state._pendingChar != '\0')
  1234. {
  1235. ch = _state._pendingChar;
  1236. }
  1237. else
  1238. {
  1239. ch = _reader.ReadChar();
  1240. if (ch == '\r')
  1241. {
  1242. ch = _reader.ReadChar();
  1243. if (ch != '\n')
  1244. {
  1245. _state._pendingChar = ch;
  1246. ch = '\n';
  1247. }
  1248. }
  1249. }
  1250. _state._currentCharPos = _state._nextCharPos;
  1251. // Update line position counter
  1252. if (ch == '\n')
  1253. {
  1254. _state._nextCharPos.Line++;
  1255. _state._nextCharPos.Offset = 0;
  1256. }
  1257. else
  1258. {
  1259. _state._nextCharPos.Offset++;
  1260. }
  1261. return _state._currentChar = ch;
  1262. }
  1263. public bool DidMove
  1264. {
  1265. get;
  1266. set;
  1267. }
  1268. public void NextToken()
  1269. {
  1270. DidMove = true;
  1271. _sb.Length = 0;
  1272. State state = State.Initial;
  1273. _state._currentTokenPos = _state._currentCharPos;
  1274. while (true)
  1275. {
  1276. switch (state)
  1277. {
  1278. case State.Initial:
  1279. if (IsIdentifierLeadChar(_state._currentChar))
  1280. {
  1281. state = State.Identifier;
  1282. break;
  1283. }
  1284. else if (char.IsDigit(_state._currentChar) || _state._currentChar == '-')
  1285. {
  1286. TokenizeNumber();
  1287. _state._currentToken = Token.Literal;
  1288. return;
  1289. }
  1290. else if (char.IsWhiteSpace(_state._currentChar))
  1291. {
  1292. NextChar();
  1293. _state._currentTokenPos = _state._currentCharPos;
  1294. break;
  1295. }
  1296. switch (_state._currentChar)
  1297. {
  1298. case '/':
  1299. if ((_options & JsonOptions.StrictParser)!=0)
  1300. {
  1301. // Comments not support in strict mode
  1302. throw new InvalidDataException(string.Format("syntax error - unexpected character '{0}'", _state._currentChar));
  1303. }
  1304. else
  1305. {
  1306. NextChar();
  1307. state = State.Slash;
  1308. }
  1309. break;
  1310. case '\"':
  1311. NextChar();
  1312. _sb.Length = 0;
  1313. state = State.QuotedString;
  1314. break;
  1315. case '\'':
  1316. NextChar();
  1317. _sb.Length = 0;
  1318. state = State.QuotedChar;
  1319. break;
  1320. case '\0':
  1321. _state._currentToken = Token.EOF;
  1322. return;
  1323. case '{': _state._currentToken = Token.OpenBrace; NextChar(); return;
  1324. case '}': _state._currentToken = Token.CloseBrace; NextChar(); return;
  1325. case '[': _state._currentToken = Token.OpenSquare; NextChar(); return;
  1326. case ']': _state._currentToken = Token.CloseSquare; NextChar(); return;
  1327. case '=': _state._currentToken = Token.Equal; NextChar(); return;
  1328. case ':': _state._currentToken = Token.Colon; NextChar(); return;
  1329. case ';': _state._currentToken = Token.SemiColon; NextChar(); return;
  1330. case ',': _state._currentToken = Token.Comma; NextChar(); return;
  1331. default:
  1332. throw new InvalidDataException(string.Format("syntax error - unexpected character '{0}'", _state._currentChar));
  1333. }
  1334. break;
  1335. case State.Slash:
  1336. switch (_state._currentChar)
  1337. {
  1338. case '/':
  1339. NextChar();
  1340. state = State.SingleLineComment;
  1341. break;
  1342. case '*':
  1343. NextChar();
  1344. state = State.BlockComment;
  1345. break;
  1346. default:
  1347. throw new InvalidDataException("syntax error - unexpected character after slash");
  1348. }
  1349. break;
  1350. case State.SingleLineComment:
  1351. if (_state._currentChar == '\r' || _state._currentChar == '\n')
  1352. {
  1353. state = State.Initial;
  1354. }
  1355. NextChar();
  1356. break;
  1357. case State.BlockComment:
  1358. if (_state._currentChar == '*')
  1359. {
  1360. NextChar();
  1361. if (_state._currentChar == '/')
  1362. {
  1363. state = State.Initial;
  1364. }
  1365. }
  1366. NextChar();
  1367. break;
  1368. case State.Identifier:
  1369. if (IsIdentifierChar(_state._currentChar))
  1370. {
  1371. _sb.Append(_state._currentChar);
  1372. NextChar();
  1373. }
  1374. else
  1375. {
  1376. _state._string = _sb.ToString();
  1377. switch (this.String)
  1378. {
  1379. case "true":
  1380. _state._literal = true;
  1381. _state._currentToken = Token.Literal;
  1382. break;
  1383. case "false":
  1384. _state._literal = false;
  1385. _state._currentToken = Token.Literal;
  1386. break;
  1387. case "null":
  1388. _state._literal = null;
  1389. _state._currentToken = Token.Literal;
  1390. break;
  1391. default:
  1392. _state._currentToken = Token.Identifier;
  1393. break;
  1394. }
  1395. return;
  1396. }
  1397. break;
  1398. case State.QuotedString:
  1399. if (_state._currentChar == '\\')
  1400. {
  1401. AppendSpecialChar();
  1402. }
  1403. else if (_state._currentChar == '\"')
  1404. {
  1405. _state._literal = _sb.ToString();
  1406. _state._currentToken = Token.Literal;
  1407. NextChar();
  1408. return;
  1409. }
  1410. else
  1411. {
  1412. _sb.Append(_state._currentChar);
  1413. NextChar();
  1414. continue;
  1415. }
  1416. break;
  1417. case State.QuotedChar:
  1418. if (_state._currentChar == '\\')
  1419. {
  1420. AppendSpecialChar();
  1421. }
  1422. else if (_state._currentChar == '\'')
  1423. {
  1424. _state._literal = _sb.ToString();
  1425. _state._currentToken = Token.Literal;
  1426. NextChar();
  1427. return;
  1428. }
  1429. else
  1430. {
  1431. _sb.Append(_state._currentChar);
  1432. NextChar();
  1433. continue;
  1434. }
  1435. break;
  1436. }
  1437. }
  1438. }
  1439. void TokenizeNumber()
  1440. {
  1441. _sb.Length = 0;
  1442. // Leading -
  1443. bool signed = false;
  1444. if (_state._currentChar == '-')
  1445. {
  1446. signed = true;
  1447. _sb.Append(_state._currentChar);
  1448. NextChar();
  1449. if (!Char.IsDigit(_state._currentChar))
  1450. {
  1451. throw new InvalidDataException("syntax error - expected digit to follow negative sign");
  1452. }
  1453. }
  1454. // Parse all digits
  1455. bool fp = false;
  1456. while (char.IsDigit(_state._currentChar) || _state._currentChar == '.' || _state._currentChar == 'e' || _state._currentChar == 'E' || _state._currentChar == 'x' || _state._currentChar == 'X')
  1457. {
  1458. if (_state._currentChar == 'e' || _state._currentChar == 'E')
  1459. {
  1460. fp = true;
  1461. _sb.Append(_state._currentChar);
  1462. NextChar();
  1463. if (_state._currentChar == '-' || _state._currentChar == '+')
  1464. {
  1465. _sb.Append(_state._currentChar);
  1466. NextChar();
  1467. }
  1468. }
  1469. else
  1470. {
  1471. if (_state._currentChar == '.')
  1472. fp = true;
  1473. _sb.Append(_state._currentChar);
  1474. NextChar();
  1475. }
  1476. }
  1477. Type type = fp ? typeof(double) : (signed ? typeof(long) : typeof(ulong));
  1478. if (char.IsLetterOrDigit(_state._currentChar))
  1479. throw new InvalidDataException(string.Format("syntax error - invalid character following number '{0}'", _state._currentChar));
  1480. // Convert type
  1481. try
  1482. {
  1483. _state._literal = Convert.ChangeType(_sb.ToString(), type, System.Globalization.CultureInfo.InvariantCulture);
  1484. }
  1485. catch
  1486. {
  1487. throw new InvalidDataException(string.Format("syntax error - incorrectly formatted number '{0}'", _sb.ToString()));
  1488. }
  1489. }
  1490. public void Check(Token tokenRequired)
  1491. {
  1492. if (tokenRequired != CurrentToken)
  1493. {
  1494. throw new InvalidDataException(string.Format("syntax error - expected {0} found {1}", tokenRequired, CurrentToken));
  1495. }
  1496. }
  1497. public void Skip(Token tokenRequired)
  1498. {
  1499. Check(tokenRequired);
  1500. NextToken();
  1501. }
  1502. public bool SkipIf(Token tokenRequired)
  1503. {
  1504. if (tokenRequired == CurrentToken)
  1505. {
  1506. NextToken();
  1507. return true;
  1508. }
  1509. return false;
  1510. }
  1511. void AppendSpecialChar()
  1512. {
  1513. NextChar();
  1514. var escape = _state._currentChar;
  1515. NextChar();
  1516. switch (escape)
  1517. {
  1518. case '\'': _sb.Append('\''); break;
  1519. case '\"': _sb.Append('\"'); break;
  1520. case '\\': _sb.Append('\\'); break;
  1521. case 'r': _sb.Append('\r'); break;
  1522. case 'n': _sb.Append('\n'); break;
  1523. case 't': _sb.Append('\t'); break;
  1524. case '0': _sb.Append('\0'); break;
  1525. case 'u':
  1526. var sbHex = new StringBuilder();
  1527. for (int i = 0; i < 4; i++)
  1528. {
  1529. sbHex.Append(_state._currentChar);
  1530. NextChar();
  1531. }
  1532. _sb.Append((char)Convert.ToUInt16(sbHex.ToString(), 16));
  1533. break;
  1534. default:
  1535. throw new InvalidDataException(string.Format("Invalid escape sequence in string literal: '\\{0}'", _state._currentChar));
  1536. }
  1537. }
  1538. public Token CurrentToken
  1539. {
  1540. get { return _state._currentToken; }
  1541. }
  1542. public JsonLineOffset CurrentTokenPosition
  1543. {
  1544. get { return _state._currentTokenPos; }
  1545. }
  1546. public string String
  1547. {
  1548. get { return _state._string; }
  1549. }
  1550. public object Literal
  1551. {
  1552. get { return _state._literal; }
  1553. }
  1554. private enum State
  1555. {
  1556. Initial,
  1557. Slash,
  1558. SingleLineComment,
  1559. BlockComment,
  1560. Identifier,
  1561. QuotedString,
  1562. QuotedChar,
  1563. }
  1564. public static bool IsIdentifierChar(char ch)
  1565. {
  1566. return Char.IsLetterOrDigit(ch) || ch == '_' || ch == '$';
  1567. }
  1568. public static bool IsIdentifierLeadChar(char ch)
  1569. {
  1570. return Char.IsLetter(ch) || ch == '_' || ch == '$';
  1571. }
  1572. public static bool IsIdentifier(string str)
  1573. {
  1574. return IsIdentifierLeadChar(str[0]) && str.All(x => IsIdentifierChar(x));
  1575. }
  1576. }
  1577. }
  1578. }