JsonReader.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. // JsonKit v0.5 - A simple but flexible Json library in a single .cs file.
  2. //
  3. // Copyright (C) 2014 Topten Software (contact@toptensoftware.com) All rights reserved.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this product
  6. // except in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed under the
  11. // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  12. // either express or implied. See the License for the specific language governing permissions
  13. // and limitations under the License.
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Linq;
  17. using System.IO;
  18. using System.Globalization;
  19. using System.Collections;
  20. using System.Dynamic;
  21. namespace Topten.JsonKit
  22. {
  23. /// <summary>
  24. /// Implements the IJsonReader interface
  25. /// </summary>
  26. public class JsonReader : IJsonReader
  27. {
  28. static JsonReader()
  29. {
  30. // Setup default resolvers
  31. _parserResolver = ResolveParser;
  32. _intoParserResolver = ResolveIntoParser;
  33. Func<IJsonReader, Type, object> simpleConverter = (reader, type) =>
  34. {
  35. return reader.ReadLiteral(literal => Convert.ChangeType(literal, type, CultureInfo.InvariantCulture));
  36. };
  37. Func<IJsonReader, Type, object> numberConverter = (reader, type) =>
  38. {
  39. switch (reader.GetLiteralKind())
  40. {
  41. case LiteralKind.SignedInteger:
  42. case LiteralKind.UnsignedInteger:
  43. {
  44. var str = reader.GetLiteralString();
  45. if (str.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase))
  46. {
  47. var tempValue = Convert.ToUInt64(str.Substring(2), 16);
  48. object val = Convert.ChangeType(tempValue, type, CultureInfo.InvariantCulture);
  49. reader.NextToken();
  50. return val;
  51. }
  52. else
  53. {
  54. object val = Convert.ChangeType(str, type, CultureInfo.InvariantCulture);
  55. reader.NextToken();
  56. return val;
  57. }
  58. }
  59. case LiteralKind.FloatingPoint:
  60. {
  61. object val = Convert.ChangeType(reader.GetLiteralString(), type, CultureInfo.InvariantCulture);
  62. reader.NextToken();
  63. return val;
  64. }
  65. }
  66. throw new InvalidDataException("expected a numeric literal");
  67. };
  68. // Default type handlers
  69. _parsers.Set(typeof(string), simpleConverter);
  70. _parsers.Set(typeof(char), simpleConverter);
  71. _parsers.Set(typeof(bool), simpleConverter);
  72. _parsers.Set(typeof(byte), numberConverter);
  73. _parsers.Set(typeof(sbyte), numberConverter);
  74. _parsers.Set(typeof(short), numberConverter);
  75. _parsers.Set(typeof(ushort), numberConverter);
  76. _parsers.Set(typeof(int), numberConverter);
  77. _parsers.Set(typeof(uint), numberConverter);
  78. _parsers.Set(typeof(long), numberConverter);
  79. _parsers.Set(typeof(ulong), numberConverter);
  80. _parsers.Set(typeof(decimal), numberConverter);
  81. _parsers.Set(typeof(float), numberConverter);
  82. _parsers.Set(typeof(double), numberConverter);
  83. _parsers.Set(typeof(DateTime), (reader, type) =>
  84. {
  85. return reader.ReadLiteral(literal => Utils.FromUnixMilliseconds((long)Convert.ChangeType(literal, typeof(long), CultureInfo.InvariantCulture)));
  86. });
  87. _parsers.Set(typeof(byte[]), (reader, type) =>
  88. {
  89. if (reader.CurrentToken == Token.OpenSquare)
  90. throw new CancelReaderException();
  91. return reader.ReadLiteral(literal => Convert.FromBase64String((string)Convert.ChangeType(literal, typeof(string), CultureInfo.InvariantCulture)));
  92. });
  93. }
  94. /// <summary>
  95. /// Constructs a new JsonReader
  96. /// </summary>
  97. /// <param name="r">The input TextReader stream</param>
  98. /// <param name="options">Options controlling parsing behaviour</param>
  99. public JsonReader(TextReader r, JsonOptions options)
  100. {
  101. _tokenizer = new Tokenizer(r, options);
  102. _options = options;
  103. }
  104. Tokenizer _tokenizer;
  105. JsonOptions _options;
  106. List<string> _contextStack = new List<string>();
  107. /// <summary>
  108. /// Gets the current parse context (ie: parent key path)
  109. /// </summary>
  110. public string Context
  111. {
  112. get
  113. {
  114. return string.Join(".", _contextStack);
  115. }
  116. }
  117. static Action<IJsonReader, object> ResolveIntoParser(Type type)
  118. {
  119. var ri = ReflectionInfo.GetReflectionInfo(type);
  120. if (ri != null)
  121. return ri.ParseInto;
  122. else
  123. return null;
  124. }
  125. static Func<IJsonReader, Type, object> ResolveParser(Type type)
  126. {
  127. // See if the Type has a static parser method - T ParseJson(IJsonReader)
  128. var parseJson = ReflectionInfo.FindParseJson(type);
  129. if (parseJson != null)
  130. {
  131. if (parseJson.GetParameters()[0].ParameterType == typeof(IJsonReader))
  132. {
  133. return (r, t) => parseJson.Invoke(null, new Object[] { r });
  134. }
  135. else
  136. {
  137. return (r, t) =>
  138. {
  139. if (r.GetLiteralKind() == LiteralKind.String)
  140. {
  141. var o = parseJson.Invoke(null, new Object[] { r.GetLiteralString() });
  142. r.NextToken();
  143. return o;
  144. }
  145. throw new InvalidDataException(string.Format("Expected string literal for type {0}", type.FullName));
  146. };
  147. }
  148. }
  149. return (r, t) =>
  150. {
  151. var into = DecoratingActivator.CreateInstance(type);
  152. r.ParseInto(into);
  153. return into;
  154. };
  155. }
  156. /// <summary>
  157. /// Gets the current position in the input stream
  158. /// </summary>
  159. public LineOffset CurrentTokenPosition
  160. {
  161. get { return _tokenizer.CurrentTokenPosition; }
  162. }
  163. /// <inheritdoc />
  164. public Token CurrentToken
  165. {
  166. get { return _tokenizer.CurrentToken; }
  167. }
  168. // ReadLiteral is implemented with a converter callback so that any
  169. // errors on converting to the target type are thrown before the tokenizer
  170. // is advanced to the next token. This ensures error location is reported
  171. // at the start of the literal, not the following token.
  172. /// <inheritdoc />
  173. public object ReadLiteral(Func<object, object> converter)
  174. {
  175. _tokenizer.Check(Token.Literal);
  176. var retv = converter(_tokenizer.LiteralValue);
  177. _tokenizer.NextToken();
  178. return retv;
  179. }
  180. /// <summary>
  181. /// Checks for EOF and throws an exception if not
  182. /// </summary>
  183. public void CheckEOF()
  184. {
  185. _tokenizer.Check(Token.EOF);
  186. }
  187. /// <inheritdoc />
  188. public object Parse(Type type)
  189. {
  190. // Null?
  191. if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.Null)
  192. {
  193. _tokenizer.NextToken();
  194. return null;
  195. }
  196. // Handle nullable types
  197. var typeUnderlying = Nullable.GetUnderlyingType(type);
  198. if (typeUnderlying != null)
  199. type = typeUnderlying;
  200. // See if we have a reader
  201. Func<IJsonReader, Type, object> parser;
  202. if (JsonReader._parsers.TryGetValue(type, out parser))
  203. {
  204. try
  205. {
  206. return parser(this, type);
  207. }
  208. catch (CancelReaderException)
  209. {
  210. // Reader aborted trying to read this format
  211. }
  212. }
  213. // See if we have factory
  214. Func<IJsonReader, string, object> factory;
  215. if (JsonReader._typeFactories.TryGetValue(type, out factory))
  216. {
  217. // Try first without passing dictionary keys
  218. object into = factory(this, null);
  219. if (into == null)
  220. {
  221. // This is a awkward situation. The factory requires a value from the dictionary
  222. // in order to create the target object (typically an abstract class with the class
  223. // kind recorded in the Json). Since there's no guarantee of order in a json dictionary
  224. // we can't assume the required key is first.
  225. // So, create a bookmark on the tokenizer, read keys until the factory returns an
  226. // object instance and then rewind the tokenizer and continue
  227. // Create a bookmark so we can rewind
  228. _tokenizer.CreateBookmark();
  229. // Skip the opening brace
  230. _tokenizer.Skip(Token.OpenBrace);
  231. // First pass to work out type
  232. ParseDictionaryKeys(key =>
  233. {
  234. // Try to instantiate the object
  235. into = factory(this, key);
  236. return into == null;
  237. });
  238. // Move back to start of the dictionary
  239. _tokenizer.RewindToBookmark();
  240. // Quit if still didn't get an object from the factory
  241. if (into == null)
  242. throw new InvalidOperationException("Factory didn't create object instance (probably due to a missing key in the Json)");
  243. }
  244. // Second pass
  245. ParseInto(into);
  246. // Done
  247. return into;
  248. }
  249. // Do we already have an into parser?
  250. Action<IJsonReader, object> intoParser;
  251. if (JsonReader._intoParsers.TryGetValue(type, out intoParser))
  252. {
  253. var into = DecoratingActivator.CreateInstance(type);
  254. ParseInto(into);
  255. return into;
  256. }
  257. // Enumerated type?
  258. if (type.IsEnum)
  259. {
  260. if (type.GetCustomAttributes(typeof(FlagsAttribute), false).Any())
  261. return ReadLiteral(literal => {
  262. try
  263. {
  264. return Enum.Parse(type, (string)literal);
  265. }
  266. catch
  267. {
  268. return Enum.ToObject(type, literal);
  269. }
  270. });
  271. else
  272. return ReadLiteral(literal => {
  273. try
  274. {
  275. return Enum.Parse(type, (string)literal);
  276. }
  277. catch (Exception)
  278. {
  279. var attr = type.GetCustomAttributes(typeof(JsonUnknownAttribute), false).FirstOrDefault();
  280. if (attr==null)
  281. throw;
  282. return ((JsonUnknownAttribute)attr).UnknownValue;
  283. }
  284. });
  285. }
  286. // Array?
  287. if (type.IsArray && type.GetArrayRank() == 1)
  288. {
  289. // First parse as a List<>
  290. var listType = typeof(List<>).MakeGenericType(type.GetElementType());
  291. var list = DecoratingActivator.CreateInstance(listType);
  292. ParseInto(list);
  293. return listType.GetMethod("ToArray").Invoke(list, null);
  294. }
  295. // IEnumerable
  296. if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
  297. {
  298. // First parse as a List<>
  299. var declType = type.GetGenericArguments()[0];
  300. var listType = typeof(List<>).MakeGenericType(declType);
  301. var list = DecoratingActivator.CreateInstance(listType);
  302. ParseInto(list);
  303. return list;
  304. }
  305. // Convert interfaces to concrete types
  306. if (type.IsInterface)
  307. type = Utils.ResolveInterfaceToClass(type);
  308. // Untyped dictionary?
  309. if (_tokenizer.CurrentToken == Token.OpenBrace && (type.IsAssignableFrom(typeof(IDictionary<string, object>))))
  310. {
  311. var container = (new ExpandoObject()) as IDictionary<string, object>;
  312. ParseDictionary(key =>
  313. {
  314. container[key] = Parse(typeof(Object));
  315. });
  316. return container;
  317. }
  318. // Untyped list?
  319. if (_tokenizer.CurrentToken == Token.OpenSquare && (type.IsAssignableFrom(typeof(List<object>))))
  320. {
  321. var container = new List<object>();
  322. ParseArray(() =>
  323. {
  324. container.Add(Parse(typeof(Object)));
  325. });
  326. return container;
  327. }
  328. // Untyped literal?
  329. if (_tokenizer.CurrentToken == Token.Literal && type.IsAssignableFrom(_tokenizer.LiteralType))
  330. {
  331. var lit = _tokenizer.LiteralValue;
  332. _tokenizer.NextToken();
  333. return lit;
  334. }
  335. // Call value type resolver
  336. if (type.IsValueType)
  337. {
  338. var tp = _parsers.Get(type, () => _parserResolver(type));
  339. if (tp != null)
  340. {
  341. return tp(this, type);
  342. }
  343. }
  344. // Call reference type resolver
  345. if (type.IsClass && type != typeof(object))
  346. {
  347. var into = DecoratingActivator.CreateInstance(type);
  348. ParseInto(into);
  349. return into;
  350. }
  351. // Give up
  352. throw new InvalidDataException(string.Format("syntax error, unexpected token {0}", _tokenizer.CurrentToken));
  353. }
  354. /// <inheritdoc />
  355. public void ParseInto(object into)
  356. {
  357. if (into == null)
  358. return;
  359. if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.Null)
  360. {
  361. throw new InvalidOperationException("can't parse null into existing instance");
  362. //return;
  363. }
  364. var type = into.GetType();
  365. // Existing parse into handler?
  366. Action<IJsonReader,object> parseInto;
  367. if (_intoParsers.TryGetValue(type, out parseInto))
  368. {
  369. parseInto(this, into);
  370. return;
  371. }
  372. // Generic dictionary?
  373. var dictType = Utils.FindGenericInterface(type, typeof(IDictionary<,>));
  374. if (dictType!=null)
  375. {
  376. // Get the key and value types
  377. var typeKey = dictType.GetGenericArguments()[0];
  378. var typeValue = dictType.GetGenericArguments()[1];
  379. // Parse it
  380. IDictionary dict = (IDictionary)into;
  381. dict.Clear();
  382. ParseDictionary(key =>
  383. {
  384. dict.Add(Convert.ChangeType(key, typeKey), Parse(typeValue));
  385. });
  386. return;
  387. }
  388. // Generic list
  389. var listType = Utils.FindGenericInterface(type, typeof(IList<>));
  390. if (listType!=null)
  391. {
  392. // Get element type
  393. var typeElement = listType.GetGenericArguments()[0];
  394. // Parse it
  395. IList list = (IList)into;
  396. list.Clear();
  397. ParseArray(() =>
  398. {
  399. list.Add(Parse(typeElement));
  400. });
  401. return;
  402. }
  403. // Untyped dictionary
  404. var objDict = into as IDictionary;
  405. if (objDict != null)
  406. {
  407. objDict.Clear();
  408. ParseDictionary(key =>
  409. {
  410. objDict[key] = Parse(typeof(Object));
  411. });
  412. return;
  413. }
  414. // Untyped list
  415. var objList = into as IList;
  416. if (objList!=null)
  417. {
  418. objList.Clear();
  419. ParseArray(() =>
  420. {
  421. objList.Add(Parse(typeof(Object)));
  422. });
  423. return;
  424. }
  425. // Try to resolve a parser
  426. var intoParser = _intoParsers.Get(type, () => _intoParserResolver(type));
  427. if (intoParser != null)
  428. {
  429. intoParser(this, into);
  430. return;
  431. }
  432. throw new InvalidOperationException(string.Format("Don't know how to parse into type '{0}'", type.FullName));
  433. }
  434. /// <inheritdoc />
  435. public T Parse<T>()
  436. {
  437. return (T)Parse(typeof(T));
  438. }
  439. /// <inheritdoc />
  440. public LiteralKind GetLiteralKind()
  441. {
  442. return _tokenizer.LiteralKind;
  443. }
  444. /// <inheritdoc />
  445. public string GetLiteralString()
  446. {
  447. return _tokenizer.String;
  448. }
  449. /// <inheritdoc />
  450. public void NextToken()
  451. {
  452. _tokenizer.NextToken();
  453. }
  454. /// <inheritdoc />
  455. public void ParseDictionary(Action<string> callback)
  456. {
  457. _tokenizer.Skip(Token.OpenBrace);
  458. ParseDictionaryKeys(key => { callback(key); return true; });
  459. _tokenizer.Skip(Token.CloseBrace);
  460. }
  461. // Parse dictionary keys, calling callback for each one. Continues until end of input
  462. // or when callback returns false
  463. private void ParseDictionaryKeys(Func<string, bool> callback)
  464. {
  465. // End?
  466. while (_tokenizer.CurrentToken != Token.CloseBrace)
  467. {
  468. // Parse the key
  469. string key = null;
  470. if (_tokenizer.CurrentToken == Token.Identifier && (_options & JsonOptions.StrictParser)==0)
  471. {
  472. key = _tokenizer.String;
  473. }
  474. else if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.String)
  475. {
  476. key = (string)_tokenizer.LiteralValue;
  477. }
  478. else
  479. {
  480. throw new InvalidDataException("syntax error, expected string literal or identifier");
  481. }
  482. _tokenizer.NextToken();
  483. _tokenizer.Skip(Token.Colon);
  484. // Remember current position
  485. var pos = _tokenizer.CurrentTokenPosition;
  486. // Call the callback, quit if cancelled
  487. _contextStack.Add(key);
  488. bool doDefaultProcessing = callback(key);
  489. _contextStack.RemoveAt(_contextStack.Count-1);
  490. if (!doDefaultProcessing)
  491. return;
  492. // If the callback didn't read anything from the tokenizer, then skip it ourself
  493. if (pos.Line == _tokenizer.CurrentTokenPosition.Line && pos.Offset == _tokenizer.CurrentTokenPosition.Offset)
  494. {
  495. Parse(typeof(object));
  496. }
  497. // Separating/trailing comma
  498. if (_tokenizer.SkipIf(Token.Comma))
  499. {
  500. if ((_options & JsonOptions.StrictParser) != 0 && _tokenizer.CurrentToken == Token.CloseBrace)
  501. {
  502. throw new InvalidDataException("Trailing commas not allowed in strict mode");
  503. }
  504. continue;
  505. }
  506. // End
  507. break;
  508. }
  509. }
  510. /// <inheritdoc />
  511. public void ParseArray(Action callback)
  512. {
  513. _tokenizer.Skip(Token.OpenSquare);
  514. int index = 0;
  515. while (_tokenizer.CurrentToken != Token.CloseSquare)
  516. {
  517. _contextStack.Add(string.Format("[{0}]", index));
  518. callback();
  519. _contextStack.RemoveAt(_contextStack.Count-1);
  520. if (_tokenizer.SkipIf(Token.Comma))
  521. {
  522. if ((_options & JsonOptions.StrictParser)!=0 && _tokenizer.CurrentToken==Token.CloseSquare)
  523. {
  524. throw new InvalidDataException("Trailing commas not allowed in strict mode");
  525. }
  526. continue;
  527. }
  528. break;
  529. }
  530. _tokenizer.Skip(Token.CloseSquare);
  531. }
  532. // Yikes!
  533. internal static Func<Type, Action<IJsonReader, object>> _intoParserResolver;
  534. internal static Func<Type, Func<IJsonReader, Type, object>> _parserResolver;
  535. internal static ThreadSafeCache<Type, Func<IJsonReader, Type, object>> _parsers = new ThreadSafeCache<Type, Func<IJsonReader, Type, object>>();
  536. internal static ThreadSafeCache<Type, Action<IJsonReader, object>> _intoParsers = new ThreadSafeCache<Type, Action<IJsonReader, object>>();
  537. internal static ThreadSafeCache<Type, Func<IJsonReader, string, object>> _typeFactories = new ThreadSafeCache<Type, Func<IJsonReader, string, object>>();
  538. }
  539. }