JsonReader.cs 21 KB

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