You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

SimpleJson.cs 73 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902
  1. //-----------------------------------------------------------------------
  2. // <copyright file="SimpleJson.cs" company="The Outercurve Foundation">
  3. // Copyright (c) 2011, The Outercurve Foundation.
  4. //
  5. // Licensed under the MIT License (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. // http://www.opensource.org/licenses/mit-license.php
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. // </copyright>
  16. // <author>Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me)</author>
  17. // <website>https://github.com/facebook-csharp-sdk/simple-json</website>
  18. //-----------------------------------------------------------------------
  19. // VERSION:
  20. // NOTE: uncomment the following line to make SimpleJson class internal.
  21. //#define SIMPLE_JSON_INTERNAL
  22. // NOTE: uncomment the following line to make JsonArray and JsonObject class internal.
  23. //#define SIMPLE_JSON_OBJARRAYINTERNAL
  24. // NOTE: uncomment the following line to enable dynamic support.
  25. //#define SIMPLE_JSON_DYNAMIC
  26. // NOTE: uncomment the following line to enable DataContract support.
  27. //#define SIMPLE_JSON_DATACONTRACT
  28. // NOTE: uncomment the following line to use Reflection.Emit (better performance) instead of method.invoke().
  29. // don't enable ReflectionEmit for WinRT, Silverlight and WP7.
  30. //#define SIMPLE_JSON_REFLECTIONEMIT
  31. // NOTE: uncomment the following line if you are compiling under Window Metro style application/library.
  32. // usually already defined in properties
  33. //#define NETFX_CORE;
  34. // original json parsing code from http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
  35. using System;
  36. using System.Collections;
  37. using System.Collections.Generic;
  38. using System.ComponentModel;
  39. using System.Diagnostics.CodeAnalysis;
  40. #if SIMPLE_JSON_DYNAMIC
  41. using System.Dynamic;
  42. #endif
  43. using System.Globalization;
  44. using System.Reflection;
  45. #if SIMPLE_JSON_REFLECTIONEMIT
  46. using System.Reflection.Emit;
  47. #endif
  48. #if SIMPLE_JSON_DATACONTRACT
  49. using System.Runtime.Serialization;
  50. #endif
  51. using System.Text;
  52. using SimpleJson.Reflection;
  53. namespace SimpleJson
  54. {
  55. #region JsonArray
  56. /// <summary>
  57. /// Represents the json array.
  58. /// </summary>
  59. [EditorBrowsable(EditorBrowsableState.Never)]
  60. [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
  61. #if SIMPLE_JSON_OBJARRAYINTERNAL
  62. internal
  63. #else
  64. public
  65. #endif
  66. class JsonArray : List<object>
  67. {
  68. /// <summary>
  69. /// Initializes a new instance of the <see cref="JsonArray"/> class.
  70. /// </summary>
  71. public JsonArray() { }
  72. /// <summary>
  73. /// Initializes a new instance of the <see cref="JsonArray"/> class.
  74. /// </summary>
  75. /// <param name="capacity">The capacity of the json array.</param>
  76. public JsonArray(int capacity) : base(capacity) { }
  77. /// <summary>
  78. /// The json representation of the array.
  79. /// </summary>
  80. /// <returns>The json representation of the array.</returns>
  81. public override string ToString()
  82. {
  83. return SimpleJson.SerializeObject(this) ?? string.Empty;
  84. }
  85. }
  86. #endregion
  87. #region JsonObject
  88. /// <summary>
  89. /// Represents the json object.
  90. /// </summary>
  91. [EditorBrowsable(EditorBrowsableState.Never)]
  92. [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
  93. #if SIMPLE_JSON_OBJARRAYINTERNAL
  94. internal
  95. #else
  96. public
  97. #endif
  98. class JsonObject :
  99. #if SIMPLE_JSON_DYNAMIC
  100. DynamicObject,
  101. #endif
  102. IDictionary<string, object>
  103. {
  104. /// <summary>
  105. /// The internal member dictionary.
  106. /// </summary>
  107. private readonly Dictionary<string, object> _members = new Dictionary<string, object>();
  108. /// <summary>
  109. /// Gets the <see cref="System.Object"/> at the specified index.
  110. /// </summary>
  111. /// <value></value>
  112. public object this[int index]
  113. {
  114. get { return GetAtIndex(_members, index); }
  115. }
  116. internal static object GetAtIndex(IDictionary<string, object> obj, int index)
  117. {
  118. if (obj == null)
  119. throw new ArgumentNullException("obj");
  120. if (index >= obj.Count)
  121. throw new ArgumentOutOfRangeException("index");
  122. int i = 0;
  123. foreach (KeyValuePair<string, object> o in obj)
  124. if (i++ == index) return o.Value;
  125. return null;
  126. }
  127. /// <summary>
  128. /// Adds the specified key.
  129. /// </summary>
  130. /// <param name="key">The key.</param>
  131. /// <param name="value">The value.</param>
  132. public void Add(string key, object value)
  133. {
  134. _members.Add(key, value);
  135. }
  136. /// <summary>
  137. /// Determines whether the specified key contains key.
  138. /// </summary>
  139. /// <param name="key">The key.</param>
  140. /// <returns>
  141. /// <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
  142. /// </returns>
  143. public bool ContainsKey(string key)
  144. {
  145. return _members.ContainsKey(key);
  146. }
  147. /// <summary>
  148. /// Gets the keys.
  149. /// </summary>
  150. /// <value>The keys.</value>
  151. public ICollection<string> Keys
  152. {
  153. get { return _members.Keys; }
  154. }
  155. /// <summary>
  156. /// Removes the specified key.
  157. /// </summary>
  158. /// <param name="key">The key.</param>
  159. /// <returns></returns>
  160. public bool Remove(string key)
  161. {
  162. return _members.Remove(key);
  163. }
  164. /// <summary>
  165. /// Tries the get value.
  166. /// </summary>
  167. /// <param name="key">The key.</param>
  168. /// <param name="value">The value.</param>
  169. /// <returns></returns>
  170. public bool TryGetValue(string key, out object value)
  171. {
  172. return _members.TryGetValue(key, out value);
  173. }
  174. /// <summary>
  175. /// Gets the values.
  176. /// </summary>
  177. /// <value>The values.</value>
  178. public ICollection<object> Values
  179. {
  180. get { return _members.Values; }
  181. }
  182. /// <summary>
  183. /// Gets or sets the <see cref="System.Object"/> with the specified key.
  184. /// </summary>
  185. /// <value></value>
  186. public object this[string key]
  187. {
  188. get { return _members[key]; }
  189. set { _members[key] = value; }
  190. }
  191. /// <summary>
  192. /// Adds the specified item.
  193. /// </summary>
  194. /// <param name="item">The item.</param>
  195. public void Add(KeyValuePair<string, object> item)
  196. {
  197. _members.Add(item.Key, item.Value);
  198. }
  199. /// <summary>
  200. /// Clears this instance.
  201. /// </summary>
  202. public void Clear()
  203. {
  204. _members.Clear();
  205. }
  206. /// <summary>
  207. /// Determines whether [contains] [the specified item].
  208. /// </summary>
  209. /// <param name="item">The item.</param>
  210. /// <returns>
  211. /// <c>true</c> if [contains] [the specified item]; otherwise, <c>false</c>.
  212. /// </returns>
  213. public bool Contains(KeyValuePair<string, object> item)
  214. {
  215. return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value;
  216. }
  217. /// <summary>
  218. /// Copies to.
  219. /// </summary>
  220. /// <param name="array">The array.</param>
  221. /// <param name="arrayIndex">Index of the array.</param>
  222. public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
  223. {
  224. int num = Count;
  225. foreach (KeyValuePair<string, object> kvp in this)
  226. {
  227. array[arrayIndex++] = kvp;
  228. if (--num <= 0)
  229. return;
  230. }
  231. }
  232. /// <summary>
  233. /// Gets the count.
  234. /// </summary>
  235. /// <value>The count.</value>
  236. public int Count
  237. {
  238. get { return _members.Count; }
  239. }
  240. /// <summary>
  241. /// Gets a value indicating whether this instance is read only.
  242. /// </summary>
  243. /// <value>
  244. /// <c>true</c> if this instance is read only; otherwise, <c>false</c>.
  245. /// </value>
  246. public bool IsReadOnly
  247. {
  248. get { return false; }
  249. }
  250. /// <summary>
  251. /// Removes the specified item.
  252. /// </summary>
  253. /// <param name="item">The item.</param>
  254. /// <returns></returns>
  255. public bool Remove(KeyValuePair<string, object> item)
  256. {
  257. return _members.Remove(item.Key);
  258. }
  259. /// <summary>
  260. /// Gets the enumerator.
  261. /// </summary>
  262. /// <returns></returns>
  263. public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
  264. {
  265. return _members.GetEnumerator();
  266. }
  267. /// <summary>
  268. /// Returns an enumerator that iterates through a collection.
  269. /// </summary>
  270. /// <returns>
  271. /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
  272. /// </returns>
  273. IEnumerator IEnumerable.GetEnumerator()
  274. {
  275. return _members.GetEnumerator();
  276. }
  277. /// <summary>
  278. /// Returns a json <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
  279. /// </summary>
  280. /// <returns>
  281. /// A json <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
  282. /// </returns>
  283. public override string ToString()
  284. {
  285. return SimpleJson.SerializeObject(this);
  286. }
  287. #if SIMPLE_JSON_DYNAMIC
  288. /// <summary>
  289. /// Provides implementation for type conversion operations. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations that convert an object from one type to another.
  290. /// </summary>
  291. /// <param name="binder">Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Type returns the <see cref="T:System.String"/> type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion.</param>
  292. /// <param name="result">The result of the type conversion operation.</param>
  293. /// <returns>
  294. /// Alwasy returns true.
  295. /// </returns>
  296. public override bool TryConvert(ConvertBinder binder, out object result)
  297. {
  298. // <pex>
  299. if (binder == (ConvertBinder)null)
  300. throw new ArgumentNullException("binder");
  301. // </pex>
  302. Type targetType = binder.Type;
  303. if ((targetType == typeof(IEnumerable)) ||
  304. (targetType == typeof(IEnumerable<KeyValuePair<string, object>>)) ||
  305. (targetType == typeof(IDictionary<string, object>)) ||
  306. #if NETFX_CORE
  307. (targetType == typeof(IDictionary<,>))
  308. #else
  309. (targetType == typeof(IDictionary))
  310. #endif
  311. )
  312. {
  313. result = this;
  314. return true;
  315. }
  316. return base.TryConvert(binder, out result);
  317. }
  318. /// <summary>
  319. /// Provides the implementation for operations that delete an object member. This method is not intended for use in C# or Visual Basic.
  320. /// </summary>
  321. /// <param name="binder">Provides information about the deletion.</param>
  322. /// <returns>
  323. /// Alwasy returns true.
  324. /// </returns>
  325. public override bool TryDeleteMember(DeleteMemberBinder binder)
  326. {
  327. // <pex>
  328. if (binder == (DeleteMemberBinder)null)
  329. throw new ArgumentNullException("binder");
  330. // </pex>
  331. return _members.Remove(binder.Name);
  332. }
  333. /// <summary>
  334. /// Provides the implementation for operations that get a value by index. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for indexing operations.
  335. /// </summary>
  336. /// <param name="binder">Provides information about the operation.</param>
  337. /// <param name="indexes">The indexes that are used in the operation. For example, for the sampleObject[3] operation in C# (sampleObject(3) in Visual Basic), where sampleObject is derived from the DynamicObject class, <paramref name="indexes"/> is equal to 3.</param>
  338. /// <param name="result">The result of the index operation.</param>
  339. /// <returns>
  340. /// Alwasy returns true.
  341. /// </returns>
  342. public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
  343. {
  344. if (indexes.Length == 1)
  345. {
  346. result = ((IDictionary<string, object>)this)[(string)indexes[0]];
  347. return true;
  348. }
  349. result = (object)null;
  350. return true;
  351. }
  352. /// <summary>
  353. /// Provides the implementation for operations that get member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as getting a value for a property.
  354. /// </summary>
  355. /// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>
  356. /// <param name="result">The result of the get operation. For example, if the method is called for a property, you can assign the property value to <paramref name="result"/>.</param>
  357. /// <returns>
  358. /// Alwasy returns true.
  359. /// </returns>
  360. public override bool TryGetMember(GetMemberBinder binder, out object result)
  361. {
  362. object value;
  363. if (_members.TryGetValue(binder.Name, out value))
  364. {
  365. result = value;
  366. return true;
  367. }
  368. result = (object)null;
  369. return true;
  370. }
  371. /// <summary>
  372. /// Provides the implementation for operations that set a value by index. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations that access objects by a specified index.
  373. /// </summary>
  374. /// <param name="binder">Provides information about the operation.</param>
  375. /// <param name="indexes">The indexes that are used in the operation. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, <paramref name="indexes"/> is equal to 3.</param>
  376. /// <param name="value">The value to set to the object that has the specified index. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, <paramref name="value"/> is equal to 10.</param>
  377. /// <returns>
  378. /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.
  379. /// </returns>
  380. public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
  381. {
  382. if (indexes.Length == 1)
  383. {
  384. ((IDictionary<string, object>)this)[(string)indexes[0]] = value;
  385. return true;
  386. }
  387. return base.TrySetIndex(binder, indexes, value);
  388. }
  389. /// <summary>
  390. /// Provides the implementation for operations that set member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as setting a value for a property.
  391. /// </summary>
  392. /// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>
  393. /// <param name="value">The value to set to the member. For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, the <paramref name="value"/> is "Test".</param>
  394. /// <returns>
  395. /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)
  396. /// </returns>
  397. public override bool TrySetMember(SetMemberBinder binder, object value)
  398. {
  399. // <pex>
  400. if (binder == (SetMemberBinder)null)
  401. throw new ArgumentNullException("binder");
  402. // </pex>
  403. _members[binder.Name] = value;
  404. return true;
  405. }
  406. /// <summary>
  407. /// Returns the enumeration of all dynamic member names.
  408. /// </summary>
  409. /// <returns>
  410. /// A sequence that contains dynamic member names.
  411. /// </returns>
  412. public override IEnumerable<string> GetDynamicMemberNames()
  413. {
  414. foreach (var key in Keys)
  415. yield return key;
  416. }
  417. #endif
  418. }
  419. #endregion
  420. }
  421. namespace SimpleJson
  422. {
  423. #region JsonParser
  424. /// <summary>
  425. /// This class encodes and decodes JSON strings.
  426. /// Spec. details, see http://www.json.org/
  427. ///
  428. /// JSON uses Arrays and Objects. These correspond here to the datatypes JsonArray(IList&lt;object>) and JsonObject(IDictionary&lt;string,object>).
  429. /// All numbers are parsed to doubles.
  430. /// </summary>
  431. #if SIMPLE_JSON_INTERNAL
  432. internal
  433. #else
  434. public
  435. #endif
  436. class SimpleJson
  437. {
  438. private const int TOKEN_NONE = 0;
  439. private const int TOKEN_CURLY_OPEN = 1;
  440. private const int TOKEN_CURLY_CLOSE = 2;
  441. private const int TOKEN_SQUARED_OPEN = 3;
  442. private const int TOKEN_SQUARED_CLOSE = 4;
  443. private const int TOKEN_COLON = 5;
  444. private const int TOKEN_COMMA = 6;
  445. private const int TOKEN_STRING = 7;
  446. private const int TOKEN_NUMBER = 8;
  447. private const int TOKEN_TRUE = 9;
  448. private const int TOKEN_FALSE = 10;
  449. private const int TOKEN_NULL = 11;
  450. private const int BUILDER_CAPACITY = 2000;
  451. /// <summary>
  452. /// Parses the string json into a value
  453. /// </summary>
  454. /// <param name="json">A JSON string.</param>
  455. /// <returns>An IList&lt;object>, a IDictionary&lt;string,object>, a double, a string, null, true, or false</returns>
  456. public static object DeserializeObject(string json)
  457. {
  458. object @object;
  459. if (TryDeserializeObject(json, out @object))
  460. return @object;
  461. throw new System.Runtime.Serialization.SerializationException("Invalid JSON string");
  462. }
  463. /// <summary>
  464. /// Try parsing the json string into a value.
  465. /// </summary>
  466. /// <param name="json">
  467. /// A JSON string.
  468. /// </param>
  469. /// <param name="object">
  470. /// The object.
  471. /// </param>
  472. /// <returns>
  473. /// Returns true if successfull otherwise false.
  474. /// </returns>
  475. public static bool TryDeserializeObject(string json, out object @object)
  476. {
  477. bool success = true;
  478. if (json != null)
  479. {
  480. char[] charArray = json.ToCharArray();
  481. int index = 0;
  482. @object = ParseValue(charArray, ref index, ref success);
  483. }
  484. else
  485. @object = null;
  486. return success;
  487. }
  488. public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy)
  489. {
  490. object jsonObject = DeserializeObject(json);
  491. return type == null || jsonObject != null &&
  492. #if NETFX_CORE
  493. jsonObject.GetType().GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())
  494. #else
  495. jsonObject.GetType().IsAssignableFrom(type)
  496. #endif
  497. ? jsonObject
  498. : (jsonSerializerStrategy ?? CurrentJsonSerializerStrategy).DeserializeObject(jsonObject, type);
  499. }
  500. public static object DeserializeObject(string json, Type type)
  501. {
  502. return DeserializeObject(json, type, null);
  503. }
  504. public static T DeserializeObject<T>(string json, IJsonSerializerStrategy jsonSerializerStrategy)
  505. {
  506. return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy);
  507. }
  508. public static T DeserializeObject<T>(string json)
  509. {
  510. return (T)DeserializeObject(json, typeof(T), null);
  511. }
  512. /// <summary>
  513. /// Converts a IDictionary&lt;string,object> / IList&lt;object> object into a JSON string
  514. /// </summary>
  515. /// <param name="json">A IDictionary&lt;string,object> / IList&lt;object></param>
  516. /// <param name="jsonSerializerStrategy">Serializer strategy to use</param>
  517. /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
  518. public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy)
  519. {
  520. StringBuilder builder = new StringBuilder(BUILDER_CAPACITY);
  521. bool success = SerializeValue(jsonSerializerStrategy, json, 0, builder);
  522. return (success ? builder.ToString() : null);
  523. }
  524. public static string SerializeObject(object json)
  525. {
  526. return SerializeObject(json, CurrentJsonSerializerStrategy);
  527. }
  528. protected static IDictionary<string, object> ParseObject(char[] json, ref int index, ref bool success)
  529. {
  530. IDictionary<string, object> table = new JsonObject();
  531. int token;
  532. // {
  533. NextToken(json, ref index);
  534. bool done = false;
  535. while (!done)
  536. {
  537. token = LookAhead(json, index);
  538. if (token == TOKEN_NONE)
  539. {
  540. success = false;
  541. return null;
  542. }
  543. else if (token == TOKEN_COMMA)
  544. NextToken(json, ref index);
  545. else if (token == TOKEN_CURLY_CLOSE)
  546. {
  547. NextToken(json, ref index);
  548. return table;
  549. }
  550. else
  551. {
  552. // name
  553. string name = ParseString(json, ref index, ref success);
  554. if (!success)
  555. {
  556. success = false;
  557. return null;
  558. }
  559. // :
  560. token = NextToken(json, ref index);
  561. if (token != TOKEN_COLON)
  562. {
  563. success = false;
  564. return null;
  565. }
  566. // value
  567. object value = ParseValue(json, ref index, ref success);
  568. if (!success)
  569. {
  570. success = false;
  571. return null;
  572. }
  573. table[name] = value;
  574. }
  575. }
  576. return table;
  577. }
  578. protected static JsonArray ParseArray(char[] json, ref int index, ref bool success)
  579. {
  580. JsonArray array = new JsonArray();
  581. // [
  582. NextToken(json, ref index);
  583. bool done = false;
  584. while (!done)
  585. {
  586. int token = LookAhead(json, index);
  587. if (token == TOKEN_NONE)
  588. {
  589. success = false;
  590. return null;
  591. }
  592. else if (token == TOKEN_COMMA)
  593. NextToken(json, ref index);
  594. else if (token == TOKEN_SQUARED_CLOSE)
  595. {
  596. NextToken(json, ref index);
  597. break;
  598. }
  599. else
  600. {
  601. object value = ParseValue(json, ref index, ref success);
  602. if (!success)
  603. return null;
  604. array.Add(value);
  605. }
  606. }
  607. return array;
  608. }
  609. protected static object ParseValue(char[] json, ref int index, ref bool success)
  610. {
  611. switch (LookAhead(json, index))
  612. {
  613. case TOKEN_STRING:
  614. return ParseString(json, ref index, ref success);
  615. case TOKEN_NUMBER:
  616. return ParseNumber(json, ref index, ref success);
  617. case TOKEN_CURLY_OPEN:
  618. return ParseObject(json, ref index, ref success);
  619. case TOKEN_SQUARED_OPEN:
  620. return ParseArray(json, ref index, ref success);
  621. case TOKEN_TRUE:
  622. NextToken(json, ref index);
  623. return true;
  624. case TOKEN_FALSE:
  625. NextToken(json, ref index);
  626. return false;
  627. case TOKEN_NULL:
  628. NextToken(json, ref index);
  629. return null;
  630. case TOKEN_NONE:
  631. break;
  632. }
  633. success = false;
  634. return null;
  635. }
  636. protected static string ParseString(char[] json, ref int index, ref bool success)
  637. {
  638. StringBuilder s = new StringBuilder(BUILDER_CAPACITY);
  639. char c;
  640. EatWhitespace(json, ref index);
  641. // "
  642. c = json[index++];
  643. bool complete = false;
  644. while (!complete)
  645. {
  646. if (index == json.Length)
  647. {
  648. break;
  649. }
  650. c = json[index++];
  651. if (c == '"')
  652. {
  653. complete = true;
  654. break;
  655. }
  656. else if (c == '\\')
  657. {
  658. if (index == json.Length)
  659. break;
  660. c = json[index++];
  661. if (c == '"')
  662. s.Append('"');
  663. else if (c == '\\')
  664. s.Append('\\');
  665. else if (c == '/')
  666. s.Append('/');
  667. else if (c == 'b')
  668. s.Append('\b');
  669. else if (c == 'f')
  670. s.Append('\f');
  671. else if (c == 'n')
  672. s.Append('\n');
  673. else if (c == 'r')
  674. s.Append('\r');
  675. else if (c == 't')
  676. s.Append('\t');
  677. else if (c == 'u')
  678. {
  679. int remainingLength = json.Length - index;
  680. if (remainingLength >= 4)
  681. {
  682. // parse the 32 bit hex into an integer codepoint
  683. uint codePoint;
  684. if (
  685. !(success =
  686. UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber,
  687. CultureInfo.InvariantCulture, out codePoint)))
  688. return "";
  689. // convert the integer codepoint to a unicode char and add to string
  690. if (0xD800 <= codePoint && codePoint <= 0xDBFF) // if high surrogate
  691. {
  692. index += 4; // skip 4 chars
  693. remainingLength = json.Length - index;
  694. if (remainingLength >= 6)
  695. {
  696. uint lowCodePoint;
  697. if (new string(json, index, 2) == "\\u" &&
  698. UInt32.TryParse(new string(json, index + 2, 4), NumberStyles.HexNumber,
  699. CultureInfo.InvariantCulture, out lowCodePoint))
  700. {
  701. if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF) // if low surrogate
  702. {
  703. s.Append((char)codePoint);
  704. s.Append((char)lowCodePoint);
  705. index += 6; // skip 6 chars
  706. continue;
  707. }
  708. }
  709. }
  710. success = false; // invalid surrogate pair
  711. return "";
  712. }
  713. #if SILVERLIGHT
  714. s.Append(ConvertFromUtf32((int)codePoint));
  715. #else
  716. s.Append(Char.ConvertFromUtf32((int)codePoint));
  717. #endif
  718. // skip 4 chars
  719. index += 4;
  720. }
  721. else
  722. break;
  723. }
  724. }
  725. else
  726. s.Append(c);
  727. }
  728. if (!complete)
  729. {
  730. success = false;
  731. return null;
  732. }
  733. return s.ToString();
  734. }
  735. #if SILVERLIGHT
  736. private static string ConvertFromUtf32(int utf32)
  737. {
  738. // http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System/System/Char.cs.htm
  739. if (utf32 < 0 || utf32 > 0x10FFFF)
  740. throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF.");
  741. if (0xD800 <= utf32 && utf32 <= 0xDFFF)
  742. throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range.");
  743. if (utf32 < 0x10000)
  744. return new string((char)utf32, 1);
  745. utf32 -= 0x10000;
  746. return new string(new char[] {(char) ((utf32 >> 10) + 0xD800),(char) (utf32 % 0x0400 + 0xDC00)});
  747. }
  748. #endif
  749. protected static object ParseNumber(char[] json, ref int index, ref bool success)
  750. {
  751. EatWhitespace(json, ref index);
  752. int lastIndex = GetLastIndexOfNumber(json, index);
  753. int charLength = (lastIndex - index) + 1;
  754. object returnNumber;
  755. string str = new string(json, index, charLength);
  756. if (str.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || str.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1)
  757. {
  758. double number;
  759. success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
  760. returnNumber = number;
  761. }
  762. else
  763. {
  764. long number;
  765. success = long.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
  766. returnNumber = number;
  767. }
  768. index = lastIndex + 1;
  769. return returnNumber;
  770. }
  771. protected static int GetLastIndexOfNumber(char[] json, int index)
  772. {
  773. int lastIndex;
  774. for (lastIndex = index; lastIndex < json.Length; lastIndex++)
  775. if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) break;
  776. return lastIndex - 1;
  777. }
  778. protected static void EatWhitespace(char[] json, ref int index)
  779. {
  780. for (; index < json.Length; index++)
  781. if (" \t\n\r\b\f".IndexOf(json[index]) == -1) break;
  782. }
  783. protected static int LookAhead(char[] json, int index)
  784. {
  785. int saveIndex = index;
  786. return NextToken(json, ref saveIndex);
  787. }
  788. [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
  789. protected static int NextToken(char[] json, ref int index)
  790. {
  791. EatWhitespace(json, ref index);
  792. if (index == json.Length)
  793. return TOKEN_NONE;
  794. char c = json[index];
  795. index++;
  796. switch (c)
  797. {
  798. case '{':
  799. return TOKEN_CURLY_OPEN;
  800. case '}':
  801. return TOKEN_CURLY_CLOSE;
  802. case '[':
  803. return TOKEN_SQUARED_OPEN;
  804. case ']':
  805. return TOKEN_SQUARED_CLOSE;
  806. case ',':
  807. return TOKEN_COMMA;
  808. case '"':
  809. return TOKEN_STRING;
  810. case '0':
  811. case '1':
  812. case '2':
  813. case '3':
  814. case '4':
  815. case '5':
  816. case '6':
  817. case '7':
  818. case '8':
  819. case '9':
  820. case '-':
  821. return TOKEN_NUMBER;
  822. case ':':
  823. return TOKEN_COLON;
  824. }
  825. index--;
  826. int remainingLength = json.Length - index;
  827. // false
  828. if (remainingLength >= 5)
  829. {
  830. if (json[index] == 'f' &&
  831. json[index + 1] == 'a' &&
  832. json[index + 2] == 'l' &&
  833. json[index + 3] == 's' &&
  834. json[index + 4] == 'e')
  835. {
  836. index += 5;
  837. return TOKEN_FALSE;
  838. }
  839. }
  840. // true
  841. if (remainingLength >= 4)
  842. {
  843. if (json[index] == 't' &&
  844. json[index + 1] == 'r' &&
  845. json[index + 2] == 'u' &&
  846. json[index + 3] == 'e')
  847. {
  848. index += 4;
  849. return TOKEN_TRUE;
  850. }
  851. }
  852. // null
  853. if (remainingLength >= 4)
  854. {
  855. if (json[index] == 'n' &&
  856. json[index + 1] == 'u' &&
  857. json[index + 2] == 'l' &&
  858. json[index + 3] == 'l')
  859. {
  860. index += 4;
  861. return TOKEN_NULL;
  862. }
  863. }
  864. return TOKEN_NONE;
  865. }
  866. protected static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, int level, StringBuilder builder)
  867. {
  868. bool success = true;
  869. if (value is string)
  870. success = SerializeString((string)value, builder);
  871. else if (value is IDictionary<string, object>)
  872. {
  873. IDictionary<string, object> dict = (IDictionary<string, object>)value;
  874. success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, level, builder);
  875. }
  876. else if (value is IDictionary<string, string>)
  877. {
  878. IDictionary<string, string> dict = (IDictionary<string, string>)value;
  879. success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, level, builder);
  880. }
  881. else if (value is IEnumerable)
  882. success = SerializeArray(jsonSerializerStrategy, (IEnumerable)value, level, builder);
  883. else if (IsNumeric(value))
  884. success = SerializeNumber(value, builder);
  885. else if (value is Boolean)
  886. builder.Append((bool)value ? "true" : "false");
  887. else if (value == null)
  888. builder.Append("null");
  889. else
  890. {
  891. object serializedObject;
  892. success = jsonSerializerStrategy.SerializeNonPrimitiveObject(value, out serializedObject);
  893. if (success)
  894. SerializeValue(jsonSerializerStrategy, serializedObject, level, builder);
  895. }
  896. return success;
  897. }
  898. protected static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, int level, StringBuilder builder)
  899. {
  900. builder.Append("{\r\n");
  901. level++;
  902. IEnumerator ke = keys.GetEnumerator();
  903. IEnumerator ve = values.GetEnumerator();
  904. bool first = true;
  905. while (ke.MoveNext() && ve.MoveNext())
  906. {
  907. object key = ke.Current;
  908. object value = ve.Current;
  909. if (!first)
  910. builder.Append(",\r\n");
  911. FeedIndent(level, builder);
  912. if (key is string)
  913. SerializeString((string)key, builder);
  914. else
  915. if (!SerializeValue(jsonSerializerStrategy, value, level, builder)) return false;
  916. builder.Append(" : ");
  917. if (!SerializeValue(jsonSerializerStrategy, value, level, builder))
  918. return false;
  919. first = false;
  920. }
  921. builder.Append("\r\n");
  922. FeedIndent(level - 1, builder);
  923. builder.Append("}");
  924. return true;
  925. }
  926. protected static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, int level, StringBuilder builder)
  927. {
  928. builder.Append("[\r\n");
  929. level++;
  930. bool first = true;
  931. foreach (object value in anArray)
  932. {
  933. if (!first)
  934. builder.Append(",\r\n");
  935. FeedIndent(level, builder);
  936. if (!SerializeValue(jsonSerializerStrategy, value, level, builder))
  937. return false;
  938. first = false;
  939. }
  940. builder.Append("\r\n");
  941. FeedIndent(level - 1, builder);
  942. builder.Append("]");
  943. return true;
  944. }
  945. protected static bool SerializeString(string aString, StringBuilder builder)
  946. {
  947. builder.Append("\"");
  948. char[] charArray = aString.ToCharArray();
  949. for (int i = 0; i < charArray.Length; i++)
  950. {
  951. char c = charArray[i];
  952. if (c == '"')
  953. builder.Append("\\\"");
  954. else if (c == '\\')
  955. builder.Append("\\\\");
  956. else if (c == '\b')
  957. builder.Append("\\b");
  958. else if (c == '\f')
  959. builder.Append("\\f");
  960. else if (c == '\n')
  961. builder.Append("\\n");
  962. else if (c == '\r')
  963. builder.Append("\\r");
  964. else if (c == '\t')
  965. builder.Append("\\t");
  966. else
  967. builder.Append(c);
  968. }
  969. builder.Append("\"");
  970. return true;
  971. }
  972. protected static bool SerializeNumber(object number, StringBuilder builder)
  973. {
  974. if (number is long)
  975. {
  976. builder.Append(((long)number).ToString(CultureInfo.InvariantCulture));
  977. }
  978. else if (number is ulong)
  979. {
  980. builder.Append(((ulong)number).ToString(CultureInfo.InvariantCulture));
  981. }
  982. else if (number is int)
  983. {
  984. builder.Append(((int)number).ToString(CultureInfo.InvariantCulture));
  985. }
  986. else if (number is uint)
  987. {
  988. builder.Append(((uint)number).ToString(CultureInfo.InvariantCulture));
  989. }
  990. else if (number is decimal)
  991. {
  992. builder.Append(((decimal)number).ToString(CultureInfo.InvariantCulture));
  993. }
  994. else if (number is float)
  995. {
  996. builder.Append(((float)number).ToString(CultureInfo.InvariantCulture));
  997. }
  998. else
  999. {
  1000. builder.Append(Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString("r", CultureInfo.InvariantCulture));
  1001. }
  1002. return true;
  1003. }
  1004. protected static void FeedIndent(int level, StringBuilder builder)
  1005. {
  1006. for (int i = 0; i < level * 2; i++)
  1007. builder.Append(" ");
  1008. }
  1009. /// <summary>
  1010. /// Determines if a given object is numeric in any way
  1011. /// (can be integer, double, null, etc).
  1012. /// </summary>
  1013. protected static bool IsNumeric(object value)
  1014. {
  1015. if (value is sbyte) return true;
  1016. if (value is byte) return true;
  1017. if (value is short) return true;
  1018. if (value is ushort) return true;
  1019. if (value is int) return true;
  1020. if (value is uint) return true;
  1021. if (value is long) return true;
  1022. if (value is ulong) return true;
  1023. if (value is float) return true;
  1024. if (value is double) return true;
  1025. if (value is decimal) return true;
  1026. return false;
  1027. }
  1028. private static IJsonSerializerStrategy currentJsonSerializerStrategy;
  1029. public static IJsonSerializerStrategy CurrentJsonSerializerStrategy
  1030. {
  1031. get
  1032. {
  1033. // todo: implement locking mechanism.
  1034. return currentJsonSerializerStrategy ??
  1035. (currentJsonSerializerStrategy =
  1036. #if SIMPLE_JSON_DATACONTRACT
  1037. DataContractJsonSerializerStrategy
  1038. #else
  1039. PocoJsonSerializerStrategy
  1040. #endif
  1041. );
  1042. }
  1043. set
  1044. {
  1045. currentJsonSerializerStrategy = value;
  1046. }
  1047. }
  1048. private static PocoJsonSerializerStrategy pocoJsonSerializerStrategy;
  1049. [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
  1050. public static PocoJsonSerializerStrategy PocoJsonSerializerStrategy
  1051. {
  1052. get
  1053. {
  1054. // todo: implement locking mechanism.
  1055. return pocoJsonSerializerStrategy ?? (pocoJsonSerializerStrategy = new PocoJsonSerializerStrategy());
  1056. }
  1057. }
  1058. #if SIMPLE_JSON_DATACONTRACT
  1059. private static DataContractJsonSerializerStrategy dataContractJsonSerializerStrategy;
  1060. [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
  1061. public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrategy
  1062. {
  1063. get
  1064. {
  1065. // todo: implement locking mechanism.
  1066. return dataContractJsonSerializerStrategy ?? (dataContractJsonSerializerStrategy = new DataContractJsonSerializerStrategy());
  1067. }
  1068. }
  1069. #endif
  1070. }
  1071. #endregion
  1072. #region Simple Json Serializer Strategies
  1073. #if SIMPLE_JSON_INTERNAL
  1074. internal
  1075. #else
  1076. public
  1077. #endif
  1078. interface IJsonSerializerStrategy
  1079. {
  1080. bool SerializeNonPrimitiveObject(object input, out object output);
  1081. object DeserializeObject(object value, Type type);
  1082. }
  1083. #if SIMPLE_JSON_INTERNAL
  1084. internal
  1085. #else
  1086. public
  1087. #endif
  1088. class PocoJsonSerializerStrategy : IJsonSerializerStrategy
  1089. {
  1090. internal CacheResolver CacheResolver;
  1091. private static readonly string[] Iso8601Format = new string[]
  1092. {
  1093. @"yyyy-MM-dd\THH:mm:ss.FFFFFFF\Z",
  1094. @"yyyy-MM-dd\THH:mm:ss\Z",
  1095. @"yyyy-MM-dd\THH:mm:ssK"
  1096. };
  1097. public PocoJsonSerializerStrategy()
  1098. {
  1099. CacheResolver = new CacheResolver(BuildMap);
  1100. }
  1101. protected virtual void BuildMap(Type type, SafeDictionary<string, CacheResolver.MemberMap> memberMaps)
  1102. {
  1103. #if NETFX_CORE
  1104. foreach (PropertyInfo info in type.GetTypeInfo().DeclaredProperties) {
  1105. var getMethod = info.GetMethod;
  1106. if(getMethod==null || !getMethod.IsPublic || getMethod.IsStatic) continue;
  1107. #else
  1108. foreach (PropertyInfo info in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
  1109. {
  1110. #endif
  1111. memberMaps.Add(info.Name, new CacheResolver.MemberMap(info));
  1112. }
  1113. #if NETFX_CORE
  1114. foreach (FieldInfo info in type.GetTypeInfo().DeclaredFields) {
  1115. if(!info.IsPublic || info.IsStatic) continue;
  1116. #else
  1117. foreach (FieldInfo info in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
  1118. {
  1119. #endif
  1120. memberMaps.Add(info.Name, new CacheResolver.MemberMap(info));
  1121. }
  1122. }
  1123. public virtual bool SerializeNonPrimitiveObject(object input, out object output)
  1124. {
  1125. return TrySerializeKnownTypes(input, out output) || TrySerializeUnknownTypes(input, out output);
  1126. }
  1127. [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
  1128. public virtual object DeserializeObject(object value, Type type)
  1129. {
  1130. object obj = null;
  1131. if (value is string)
  1132. {
  1133. string str = value as string;
  1134. if (!string.IsNullOrEmpty(str))
  1135. {
  1136. if (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime)))
  1137. obj = DateTime.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
  1138. else if (type == typeof(Guid) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid)))
  1139. obj = new Guid(str);
  1140. else
  1141. obj = str;
  1142. }
  1143. else
  1144. {
  1145. if (type == typeof(Guid))
  1146. obj= default(Guid);
  1147. else if(ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))
  1148. obj = null;
  1149. else
  1150. obj = str;
  1151. }
  1152. }
  1153. else if (value is bool)
  1154. obj = value;
  1155. else if (value == null)
  1156. obj = null;
  1157. else if ((value is long && type == typeof(long)) || (value is double && type == typeof(double)))
  1158. obj = value;
  1159. else if ((value is double && type != typeof(double)) || (value is long && type != typeof(long)))
  1160. {
  1161. obj =
  1162. #if NETFX_CORE
  1163. type == typeof(int) || type == typeof(long) || type == typeof(double) ||type == typeof(float) || type == typeof(bool) || type == typeof(decimal) ||type == typeof(byte) || type == typeof(short)
  1164. #else
  1165. typeof(IConvertible).IsAssignableFrom(type)
  1166. #endif
  1167. ? Convert.ChangeType(value, type, CultureInfo.InvariantCulture) : value;
  1168. }
  1169. else
  1170. {
  1171. if (value is IDictionary<string, object>)
  1172. {
  1173. IDictionary<string, object> jsonObject = (IDictionary<string, object>)value;
  1174. if (ReflectionUtils.IsTypeDictionary(type))
  1175. {
  1176. // if dictionary then
  1177. #if NETFX_CORE
  1178. Type keyType = type.GetTypeInfo().GenericTypeArguments[0];
  1179. Type valueType = type.GetTypeInfo().GenericTypeArguments[1];
  1180. #else
  1181. Type keyType = type.GetGenericArguments()[0];
  1182. Type valueType = type.GetGenericArguments()[1];
  1183. #endif
  1184. Type genericType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
  1185. #if NETFX_CORE
  1186. dynamic dict = CacheResolver.GetNewInstance(genericType);
  1187. #else
  1188. IDictionary dict = (IDictionary)CacheResolver.GetNewInstance(genericType);
  1189. #endif
  1190. foreach (KeyValuePair<string, object> kvp in jsonObject)
  1191. {
  1192. dict.Add(kvp.Key, DeserializeObject(kvp.Value, valueType));
  1193. }
  1194. obj = dict;
  1195. }
  1196. else
  1197. {
  1198. obj = CacheResolver.GetNewInstance(type);
  1199. SafeDictionary<string, CacheResolver.MemberMap> maps = CacheResolver.LoadMaps(type);
  1200. if (maps == null)
  1201. {
  1202. obj = value;
  1203. }
  1204. else
  1205. {
  1206. foreach (KeyValuePair<string, CacheResolver.MemberMap> keyValuePair in maps)
  1207. {
  1208. CacheResolver.MemberMap v = keyValuePair.Value;
  1209. if (v.Setter == null)
  1210. continue;
  1211. string jsonKey = keyValuePair.Key;
  1212. if (jsonObject.ContainsKey(jsonKey))
  1213. {
  1214. object jsonValue = DeserializeObject(jsonObject[jsonKey], v.Type);
  1215. v.Setter(obj, jsonValue);
  1216. }
  1217. }
  1218. }
  1219. }
  1220. }
  1221. else if (value is IList<object>)
  1222. {
  1223. IList<object> jsonObject = (IList<object>)value;
  1224. IList list = null;
  1225. if (type.IsArray)
  1226. {
  1227. list = (IList)Activator.CreateInstance(type, jsonObject.Count);
  1228. int i = 0;
  1229. foreach (object o in jsonObject)
  1230. list[i++] = DeserializeObject(o, type.GetElementType());
  1231. }
  1232. else if (ReflectionUtils.IsTypeGenericeCollectionInterface(type) ||
  1233. #if NETFX_CORE
  1234. typeof(IList).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())
  1235. #else
  1236. typeof(IList).IsAssignableFrom(type)
  1237. #endif
  1238. )
  1239. {
  1240. #if NETFX_CORE
  1241. Type innerType = type.GetTypeInfo().GenericTypeArguments[0];
  1242. #else
  1243. Type innerType = type.GetGenericArguments()[0];
  1244. #endif
  1245. Type genericType = typeof(List<>).MakeGenericType(innerType);
  1246. list = (IList)CacheResolver.GetNewInstance(genericType);
  1247. foreach (object o in jsonObject)
  1248. list.Add(DeserializeObject(o, innerType));
  1249. }
  1250. obj = list;
  1251. }
  1252. return obj;
  1253. }
  1254. if (ReflectionUtils.IsNullableType(type))
  1255. return ReflectionUtils.ToNullableType(obj, type);
  1256. if (obj == null)
  1257. {
  1258. if (type == typeof(Guid))
  1259. return default(Guid);
  1260. }
  1261. return obj;
  1262. }
  1263. protected virtual object SerializeEnum(Enum p)
  1264. {
  1265. return Convert.ToDouble(p, CultureInfo.InvariantCulture);
  1266. }
  1267. protected virtual bool TrySerializeKnownTypes(object input, out object output)
  1268. {
  1269. bool returnValue = true;
  1270. if (input is DateTime)
  1271. output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);
  1272. else if (input is Guid)
  1273. output = ((Guid)input).ToString("D");
  1274. else if (input is Uri)
  1275. output = input.ToString();
  1276. else if (input is Enum)
  1277. output = SerializeEnum((Enum)input);
  1278. else
  1279. {
  1280. returnValue = false;
  1281. output = null;
  1282. }
  1283. return returnValue;
  1284. }
  1285. protected virtual bool TrySerializeUnknownTypes(object input, out object output)
  1286. {
  1287. output = null;
  1288. // todo: implement caching for types
  1289. Type type = input.GetType();
  1290. if (type.FullName == null)
  1291. return false;
  1292. IDictionary<string, object> obj = new JsonObject();
  1293. SafeDictionary<string, CacheResolver.MemberMap> maps = CacheResolver.LoadMaps(type);
  1294. foreach (KeyValuePair<string, CacheResolver.MemberMap> keyValuePair in maps)
  1295. {
  1296. if (keyValuePair.Value.Getter != null)
  1297. obj.Add(keyValuePair.Key, keyValuePair.Value.Getter(input));
  1298. }
  1299. output = obj;
  1300. return true;
  1301. }
  1302. }
  1303. #if SIMPLE_JSON_DATACONTRACT
  1304. #if SIMPLE_JSON_INTERNAL
  1305. internal
  1306. #else
  1307. public
  1308. #endif
  1309. class DataContractJsonSerializerStrategy : PocoJsonSerializerStrategy
  1310. {
  1311. public DataContractJsonSerializerStrategy()
  1312. {
  1313. CacheResolver = new CacheResolver(BuildMap);
  1314. }
  1315. protected override void BuildMap(Type type, SafeDictionary<string, CacheResolver.MemberMap> map)
  1316. {
  1317. bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null;
  1318. if (!hasDataContract)
  1319. {
  1320. base.BuildMap(type, map);
  1321. return;
  1322. }
  1323. string jsonKey;
  1324. #if NETFX_CORE
  1325. foreach (PropertyInfo info in type.GetTypeInfo().DeclaredProperties)
  1326. #else
  1327. foreach (PropertyInfo info in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
  1328. #endif
  1329. {
  1330. if (CanAdd(info, out jsonKey))
  1331. map.Add(jsonKey, new CacheResolver.MemberMap(info));
  1332. }
  1333. #if NETFX_CORE
  1334. foreach (FieldInfo info in type.GetTypeInfo().DeclaredFields)
  1335. #else
  1336. foreach (FieldInfo info in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
  1337. #endif
  1338. {
  1339. if (CanAdd(info, out jsonKey))
  1340. map.Add(jsonKey, new CacheResolver.MemberMap(info));
  1341. }
  1342. // todo implement sorting for DATACONTRACT.
  1343. }
  1344. private static bool CanAdd(MemberInfo info, out string jsonKey)
  1345. {
  1346. jsonKey = null;
  1347. if (ReflectionUtils.GetAttribute(info, typeof(IgnoreDataMemberAttribute)) != null)
  1348. return false;
  1349. DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)ReflectionUtils.GetAttribute(info, typeof(DataMemberAttribute));
  1350. if (dataMemberAttribute == null)
  1351. return false;
  1352. jsonKey = string.IsNullOrEmpty(dataMemberAttribute.Name) ? info.Name : dataMemberAttribute.Name;
  1353. return true;
  1354. }
  1355. }
  1356. #endif
  1357. #endregion
  1358. #region Reflection helpers
  1359. namespace Reflection
  1360. {
  1361. #if SIMPLE_JSON_INTERNAL
  1362. internal
  1363. #else
  1364. public
  1365. #endif
  1366. class ReflectionUtils
  1367. {
  1368. public static Attribute GetAttribute(MemberInfo info, Type type)
  1369. {
  1370. #if NETFX_CORE
  1371. if (info == null || type == null || !info.IsDefined(type))
  1372. return null;
  1373. return info.GetCustomAttribute(type);
  1374. #else
  1375. if (info == null || type == null || !Attribute.IsDefined(info, type))
  1376. return null;
  1377. return Attribute.GetCustomAttribute(info, type);
  1378. #endif
  1379. }
  1380. public static Attribute GetAttribute(Type objectType, Type attributeType)
  1381. {
  1382. #if NETFX_CORE
  1383. if (objectType == null || attributeType == null || !objectType.GetTypeInfo().IsDefined(attributeType))
  1384. return null;
  1385. return objectType.GetTypeInfo().GetCustomAttribute(attributeType);
  1386. #else
  1387. if (objectType == null || attributeType == null || !Attribute.IsDefined(objectType, attributeType))
  1388. return null;
  1389. return Attribute.GetCustomAttribute(objectType, attributeType);
  1390. #endif
  1391. }
  1392. public static bool IsTypeGenericeCollectionInterface(Type type)
  1393. {
  1394. #if NETFX_CORE
  1395. if (!type.GetTypeInfo().IsGenericType)
  1396. #else
  1397. if (!type.IsGenericType)
  1398. #endif
  1399. return false;
  1400. Type genericDefinition = type.GetGenericTypeDefinition();
  1401. return (genericDefinition == typeof(IList<>) || genericDefinition == typeof(ICollection<>) || genericDefinition == typeof(IEnumerable<>));
  1402. }
  1403. public static bool IsTypeDictionary(Type type)
  1404. {
  1405. #if NETFX_CORE
  1406. if (typeof(IDictionary<,>).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
  1407. return true;
  1408. if (!type.GetTypeInfo().IsGenericType)
  1409. return false;
  1410. #else
  1411. if (typeof(IDictionary).IsAssignableFrom(type))
  1412. return true;
  1413. if (!type.IsGenericType)
  1414. return false;
  1415. #endif
  1416. Type genericDefinition = type.GetGenericTypeDefinition();
  1417. return genericDefinition == typeof(IDictionary<,>);
  1418. }
  1419. public static bool IsNullableType(Type type)
  1420. {
  1421. return
  1422. #if NETFX_CORE
  1423. type.GetTypeInfo().IsGenericType
  1424. #else
  1425. type.IsGenericType
  1426. #endif
  1427. && type.GetGenericTypeDefinition() == typeof(Nullable<>);
  1428. }
  1429. public static object ToNullableType(object obj, Type nullableType)
  1430. {
  1431. return obj == null ? null : Convert.ChangeType(obj, Nullable.GetUnderlyingType(nullableType), CultureInfo.InvariantCulture);
  1432. }
  1433. }
  1434. #if SIMPLE_JSON_INTERNAL
  1435. internal
  1436. #else
  1437. public
  1438. #endif
  1439. delegate object GetHandler(object source);
  1440. #if SIMPLE_JSON_INTERNAL
  1441. internal
  1442. #else
  1443. public
  1444. #endif
  1445. delegate void SetHandler(object source, object value);
  1446. #if SIMPLE_JSON_INTERNAL
  1447. internal
  1448. #else
  1449. public
  1450. #endif
  1451. delegate void MemberMapLoader(Type type, SafeDictionary<string, CacheResolver.MemberMap> memberMaps);
  1452. #if SIMPLE_JSON_INTERNAL
  1453. internal
  1454. #else
  1455. public
  1456. #endif
  1457. class CacheResolver
  1458. {
  1459. private readonly MemberMapLoader _memberMapLoader;
  1460. private readonly SafeDictionary<Type, SafeDictionary<string, MemberMap>> _memberMapsCache = new SafeDictionary<Type, SafeDictionary<string, MemberMap>>();
  1461. delegate object CtorDelegate();
  1462. readonly static SafeDictionary<Type, CtorDelegate> ConstructorCache = new SafeDictionary<Type, CtorDelegate>();
  1463. public CacheResolver(MemberMapLoader memberMapLoader)
  1464. {
  1465. _memberMapLoader = memberMapLoader;
  1466. }
  1467. [SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
  1468. public static object GetNewInstance(Type type)
  1469. {
  1470. CtorDelegate c;
  1471. if (ConstructorCache.TryGetValue(type, out c))
  1472. return c();
  1473. #if SIMPLE_JSON_REFLECTIONEMIT
  1474. DynamicMethod dynamicMethod = new DynamicMethod("Create" + type.FullName, typeof(object), Type.EmptyTypes, type, true);
  1475. dynamicMethod.InitLocals = true;
  1476. ILGenerator generator = dynamicMethod.GetILGenerator();
  1477. if (type.IsValueType)
  1478. {
  1479. generator.DeclareLocal(type);
  1480. generator.Emit(OpCodes.Ldloc_0);
  1481. generator.Emit(OpCodes.Box, type);
  1482. }
  1483. else
  1484. {
  1485. ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
  1486. if (constructorInfo == null)
  1487. throw new Exception(string.Format(CultureInfo.InvariantCulture, "Could not get constructor for {0}.", type));
  1488. generator.Emit(OpCodes.Newobj, constructorInfo);
  1489. }
  1490. generator.Emit(OpCodes.Ret);
  1491. c = (CtorDelegate)dynamicMethod.CreateDelegate(typeof(CtorDelegate));
  1492. ConstructorCache.Add(type, c);
  1493. return c();
  1494. #else
  1495. #if NETFX_CORE
  1496. IEnumerable<ConstructorInfo> constructorInfos = type.GetTypeInfo().DeclaredConstructors;
  1497. ConstructorInfo constructorInfo = null;
  1498. foreach (ConstructorInfo item in constructorInfos) // FirstOrDefault()
  1499. {
  1500. if (item.GetParameters().Length == 0) // Default ctor - make sure it doesn't contain any parameters
  1501. {
  1502. constructorInfo = item;
  1503. break;
  1504. }
  1505. }
  1506. #else
  1507. ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
  1508. #endif
  1509. c = delegate { return constructorInfo.Invoke(null); };
  1510. ConstructorCache.Add(type, c);
  1511. return c();
  1512. #endif
  1513. }
  1514. public SafeDictionary<string, MemberMap> LoadMaps(Type type)
  1515. {
  1516. if (type == null || type == typeof(object))
  1517. return null;
  1518. SafeDictionary<string, MemberMap> maps;
  1519. if (_memberMapsCache.TryGetValue(type, out maps))
  1520. return maps;
  1521. maps = new SafeDictionary<string, MemberMap>();
  1522. _memberMapLoader(type, maps);
  1523. _memberMapsCache.Add(type, maps);
  1524. return maps;
  1525. }
  1526. #if SIMPLE_JSON_REFLECTIONEMIT
  1527. static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner)
  1528. {
  1529. DynamicMethod dynamicMethod = !owner.IsInterface
  1530. ? new DynamicMethod(name, returnType, parameterTypes, owner, true)
  1531. : new DynamicMethod(name, returnType, parameterTypes, (Module)null, true);
  1532. return dynamicMethod;
  1533. }
  1534. #endif
  1535. static GetHandler CreateGetHandler(FieldInfo fieldInfo)
  1536. {
  1537. #if SIMPLE_JSON_REFLECTIONEMIT
  1538. Type type = fieldInfo.FieldType;
  1539. DynamicMethod dynamicGet = CreateDynamicMethod("Get" + fieldInfo.Name, fieldInfo.DeclaringType, new Type[] { typeof(object) }, fieldInfo.DeclaringType);
  1540. ILGenerator getGenerator = dynamicGet.GetILGenerator();
  1541. getGenerator.Emit(OpCodes.Ldarg_0);
  1542. getGenerator.Emit(OpCodes.Ldfld, fieldInfo);
  1543. if (type.IsValueType)
  1544. getGenerator.Emit(OpCodes.Box, type);
  1545. getGenerator.Emit(OpCodes.Ret);
  1546. return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler));
  1547. #else
  1548. return delegate(object instance) { return fieldInfo.GetValue(instance); };
  1549. #endif
  1550. }
  1551. static SetHandler CreateSetHandler(FieldInfo fieldInfo)
  1552. {
  1553. if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral)
  1554. return null;
  1555. #if SIMPLE_JSON_REFLECTIONEMIT
  1556. Type type = fieldInfo.FieldType;
  1557. DynamicMethod dynamicSet = CreateDynamicMethod("Set" + fieldInfo.Name, null, new Type[] { typeof(object), typeof(object) }, fieldInfo.DeclaringType);
  1558. ILGenerator setGenerator = dynamicSet.GetILGenerator();
  1559. setGenerator.Emit(OpCodes.Ldarg_0);
  1560. setGenerator.Emit(OpCodes.Ldarg_1);
  1561. if (type.IsValueType)
  1562. setGenerator.Emit(OpCodes.Unbox_Any, type);
  1563. setGenerator.Emit(OpCodes.Stfld, fieldInfo);
  1564. setGenerator.Emit(OpCodes.Ret);
  1565. return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler));
  1566. #else
  1567. return delegate(object instance, object value) { fieldInfo.SetValue(instance, value); };
  1568. #endif
  1569. }
  1570. static GetHandler CreateGetHandler(PropertyInfo propertyInfo)
  1571. {
  1572. #if NETFX_CORE
  1573. MethodInfo getMethodInfo = propertyInfo.GetMethod;
  1574. #else
  1575. MethodInfo getMethodInfo = propertyInfo.GetGetMethod(true);
  1576. #endif
  1577. if (getMethodInfo == null)
  1578. return null;
  1579. #if SIMPLE_JSON_REFLECTIONEMIT
  1580. Type type = propertyInfo.PropertyType;
  1581. DynamicMethod dynamicGet = CreateDynamicMethod("Get" + propertyInfo.Name, propertyInfo.DeclaringType, new Type[] { typeof(object) }, propertyInfo.DeclaringType);
  1582. ILGenerator getGenerator = dynamicGet.GetILGenerator();
  1583. getGenerator.Emit(OpCodes.Ldarg_0);
  1584. getGenerator.Emit(OpCodes.Call, getMethodInfo);
  1585. if (type.IsValueType)
  1586. getGenerator.Emit(OpCodes.Box, type);
  1587. getGenerator.Emit(OpCodes.Ret);
  1588. return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler));
  1589. #else
  1590. #if NETFX_CORE
  1591. return delegate(object instance) { return getMethodInfo.Invoke(instance, new Type[] { }); };
  1592. #else
  1593. return delegate(object instance) { return getMethodInfo.Invoke(instance, Type.EmptyTypes); };
  1594. #endif
  1595. #endif
  1596. }
  1597. static SetHandler CreateSetHandler(PropertyInfo propertyInfo)
  1598. {
  1599. #if NETFX_CORE
  1600. MethodInfo setMethodInfo = propertyInfo.SetMethod;
  1601. #else
  1602. MethodInfo setMethodInfo = propertyInfo.GetSetMethod(true);
  1603. #endif
  1604. if (setMethodInfo == null)
  1605. return null;
  1606. #if SIMPLE_JSON_REFLECTIONEMIT
  1607. Type type = propertyInfo.PropertyType;
  1608. DynamicMethod dynamicSet = CreateDynamicMethod("Set" + propertyInfo.Name, null, new Type[] { typeof(object), typeof(object) }, propertyInfo.DeclaringType);
  1609. ILGenerator setGenerator = dynamicSet.GetILGenerator();
  1610. setGenerator.Emit(OpCodes.Ldarg_0);
  1611. setGenerator.Emit(OpCodes.Ldarg_1);
  1612. if (type.IsValueType)
  1613. setGenerator.Emit(OpCodes.Unbox_Any, type);
  1614. setGenerator.Emit(OpCodes.Call, setMethodInfo);
  1615. setGenerator.Emit(OpCodes.Ret);
  1616. return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler));
  1617. #else
  1618. return delegate(object instance, object value) { setMethodInfo.Invoke(instance, new[] { value }); };
  1619. #endif
  1620. }
  1621. #if SIMPLE_JSON_INTERNAL
  1622. internal
  1623. #else
  1624. public
  1625. #endif
  1626. sealed class MemberMap
  1627. {
  1628. public readonly MemberInfo MemberInfo;
  1629. public readonly Type Type;
  1630. public readonly GetHandler Getter;
  1631. public readonly SetHandler Setter;
  1632. public MemberMap(PropertyInfo propertyInfo)
  1633. {
  1634. MemberInfo = propertyInfo;
  1635. Type = propertyInfo.PropertyType;
  1636. Getter = CreateGetHandler(propertyInfo);
  1637. Setter = CreateSetHandler(propertyInfo);
  1638. }
  1639. public MemberMap(FieldInfo fieldInfo)
  1640. {
  1641. MemberInfo = fieldInfo;
  1642. Type = fieldInfo.FieldType;
  1643. Getter = CreateGetHandler(fieldInfo);
  1644. Setter = CreateSetHandler(fieldInfo);
  1645. }
  1646. }
  1647. }
  1648. #if SIMPLE_JSON_INTERNAL
  1649. internal
  1650. #else
  1651. public
  1652. #endif
  1653. class SafeDictionary<TKey, TValue>
  1654. {
  1655. private readonly object _padlock = new object();
  1656. private readonly Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();
  1657. public bool TryGetValue(TKey key, out TValue value)
  1658. {
  1659. return _dictionary.TryGetValue(key, out value);
  1660. }
  1661. public TValue this[TKey key]
  1662. {
  1663. get { return _dictionary[key]; }
  1664. }
  1665. public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
  1666. {
  1667. return ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).GetEnumerator();
  1668. }
  1669. public void Add(TKey key, TValue value)
  1670. {
  1671. lock (_padlock)
  1672. {
  1673. if (_dictionary.ContainsKey(key) == false)
  1674. _dictionary.Add(key, value);
  1675. }
  1676. }
  1677. }
  1678. }
  1679. #endregion
  1680. }