JsonReader.cs 21 KB

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