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 72 kB

10 years ago
10 years ago
10 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883
  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, 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, 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, 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, builder);
  880. }
  881. else if (value is IEnumerable)
  882. success = SerializeArray(jsonSerializerStrategy, (IEnumerable)value, 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, builder);
  895. }
  896. return success;
  897. }
  898. protected static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder)
  899. {
  900. builder.Append("{\r\n");
  901. IEnumerator ke = keys.GetEnumerator();
  902. IEnumerator ve = values.GetEnumerator();
  903. bool first = true;
  904. while (ke.MoveNext() && ve.MoveNext())
  905. {
  906. object key = ke.Current;
  907. object value = ve.Current;
  908. if (!first)
  909. builder.Append(",\r\n");
  910. if (key is string)
  911. SerializeString((string)key, builder);
  912. else
  913. if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false;
  914. builder.Append(" : ");
  915. if (!SerializeValue(jsonSerializerStrategy, value, builder))
  916. return false;
  917. first = false;
  918. }
  919. builder.Append("}\r\n");
  920. return true;
  921. }
  922. protected static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder)
  923. {
  924. builder.Append("[\r\n ");
  925. bool first = true;
  926. foreach (object value in anArray)
  927. {
  928. if (!first)
  929. builder.Append(",\r\n ");
  930. if (!SerializeValue(jsonSerializerStrategy, value, builder))
  931. return false;
  932. first = false;
  933. }
  934. builder.Append("\r\n]");
  935. return true;
  936. }
  937. protected static bool SerializeString(string aString, StringBuilder builder)
  938. {
  939. builder.Append("\"");
  940. char[] charArray = aString.ToCharArray();
  941. for (int i = 0; i < charArray.Length; i++)
  942. {
  943. char c = charArray[i];
  944. if (c == '"')
  945. builder.Append("\\\"");
  946. else if (c == '\\')
  947. builder.Append("\\\\");
  948. else if (c == '\b')
  949. builder.Append("\\b");
  950. else if (c == '\f')
  951. builder.Append("\\f");
  952. else if (c == '\n')
  953. builder.Append("\\n");
  954. else if (c == '\r')
  955. builder.Append("\\r");
  956. else if (c == '\t')
  957. builder.Append("\\t");
  958. else
  959. builder.Append(c);
  960. }
  961. builder.Append("\"");
  962. return true;
  963. }
  964. protected static bool SerializeNumber(object number, StringBuilder builder)
  965. {
  966. if (number is long)
  967. {
  968. builder.Append(((long)number).ToString(CultureInfo.InvariantCulture));
  969. }
  970. else if (number is ulong)
  971. {
  972. builder.Append(((ulong)number).ToString(CultureInfo.InvariantCulture));
  973. }
  974. else if (number is int)
  975. {
  976. builder.Append(((int)number).ToString(CultureInfo.InvariantCulture));
  977. }
  978. else if (number is uint)
  979. {
  980. builder.Append(((uint)number).ToString(CultureInfo.InvariantCulture));
  981. }
  982. else if (number is decimal)
  983. {
  984. builder.Append(((decimal)number).ToString(CultureInfo.InvariantCulture));
  985. }
  986. else if (number is float)
  987. {
  988. builder.Append(((float)number).ToString(CultureInfo.InvariantCulture));
  989. }
  990. else
  991. {
  992. builder.Append(Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString("r", CultureInfo.InvariantCulture));
  993. }
  994. return true;
  995. }
  996. /// <summary>
  997. /// Determines if a given object is numeric in any way
  998. /// (can be integer, double, null, etc).
  999. /// </summary>
  1000. protected static bool IsNumeric(object value)
  1001. {
  1002. if (value is sbyte) return true;
  1003. if (value is byte) return true;
  1004. if (value is short) return true;
  1005. if (value is ushort) return true;
  1006. if (value is int) return true;
  1007. if (value is uint) return true;
  1008. if (value is long) return true;
  1009. if (value is ulong) return true;
  1010. if (value is float) return true;
  1011. if (value is double) return true;
  1012. if (value is decimal) return true;
  1013. return false;
  1014. }
  1015. private static IJsonSerializerStrategy currentJsonSerializerStrategy;
  1016. public static IJsonSerializerStrategy CurrentJsonSerializerStrategy
  1017. {
  1018. get
  1019. {
  1020. // todo: implement locking mechanism.
  1021. return currentJsonSerializerStrategy ??
  1022. (currentJsonSerializerStrategy =
  1023. #if SIMPLE_JSON_DATACONTRACT
  1024. DataContractJsonSerializerStrategy
  1025. #else
  1026. PocoJsonSerializerStrategy
  1027. #endif
  1028. );
  1029. }
  1030. set
  1031. {
  1032. currentJsonSerializerStrategy = value;
  1033. }
  1034. }
  1035. private static PocoJsonSerializerStrategy pocoJsonSerializerStrategy;
  1036. [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
  1037. public static PocoJsonSerializerStrategy PocoJsonSerializerStrategy
  1038. {
  1039. get
  1040. {
  1041. // todo: implement locking mechanism.
  1042. return pocoJsonSerializerStrategy ?? (pocoJsonSerializerStrategy = new PocoJsonSerializerStrategy());
  1043. }
  1044. }
  1045. #if SIMPLE_JSON_DATACONTRACT
  1046. private static DataContractJsonSerializerStrategy dataContractJsonSerializerStrategy;
  1047. [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
  1048. public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrategy
  1049. {
  1050. get
  1051. {
  1052. // todo: implement locking mechanism.
  1053. return dataContractJsonSerializerStrategy ?? (dataContractJsonSerializerStrategy = new DataContractJsonSerializerStrategy());
  1054. }
  1055. }
  1056. #endif
  1057. }
  1058. #endregion
  1059. #region Simple Json Serializer Strategies
  1060. #if SIMPLE_JSON_INTERNAL
  1061. internal
  1062. #else
  1063. public
  1064. #endif
  1065. interface IJsonSerializerStrategy
  1066. {
  1067. bool SerializeNonPrimitiveObject(object input, out object output);
  1068. object DeserializeObject(object value, Type type);
  1069. }
  1070. #if SIMPLE_JSON_INTERNAL
  1071. internal
  1072. #else
  1073. public
  1074. #endif
  1075. class PocoJsonSerializerStrategy : IJsonSerializerStrategy
  1076. {
  1077. internal CacheResolver CacheResolver;
  1078. private static readonly string[] Iso8601Format = new string[]
  1079. {
  1080. @"yyyy-MM-dd\THH:mm:ss.FFFFFFF\Z",
  1081. @"yyyy-MM-dd\THH:mm:ss\Z",
  1082. @"yyyy-MM-dd\THH:mm:ssK"
  1083. };
  1084. public PocoJsonSerializerStrategy()
  1085. {
  1086. CacheResolver = new CacheResolver(BuildMap);
  1087. }
  1088. protected virtual void BuildMap(Type type, SafeDictionary<string, CacheResolver.MemberMap> memberMaps)
  1089. {
  1090. #if NETFX_CORE
  1091. foreach (PropertyInfo info in type.GetTypeInfo().DeclaredProperties) {
  1092. var getMethod = info.GetMethod;
  1093. if(getMethod==null || !getMethod.IsPublic || getMethod.IsStatic) continue;
  1094. #else
  1095. foreach (PropertyInfo info in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
  1096. {
  1097. #endif
  1098. memberMaps.Add(info.Name, new CacheResolver.MemberMap(info));
  1099. }
  1100. #if NETFX_CORE
  1101. foreach (FieldInfo info in type.GetTypeInfo().DeclaredFields) {
  1102. if(!info.IsPublic || info.IsStatic) continue;
  1103. #else
  1104. foreach (FieldInfo info in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
  1105. {
  1106. #endif
  1107. memberMaps.Add(info.Name, new CacheResolver.MemberMap(info));
  1108. }
  1109. }
  1110. public virtual bool SerializeNonPrimitiveObject(object input, out object output)
  1111. {
  1112. return TrySerializeKnownTypes(input, out output) || TrySerializeUnknownTypes(input, out output);
  1113. }
  1114. [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
  1115. public virtual object DeserializeObject(object value, Type type)
  1116. {
  1117. object obj = null;
  1118. if (value is string)
  1119. {
  1120. string str = value as string;
  1121. if (!string.IsNullOrEmpty(str))
  1122. {
  1123. if (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime)))
  1124. obj = DateTime.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
  1125. else if (type == typeof(Guid) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid)))
  1126. obj = new Guid(str);
  1127. else
  1128. obj = str;
  1129. }
  1130. else
  1131. {
  1132. if (type == typeof(Guid))
  1133. obj= default(Guid);
  1134. else if(ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))
  1135. obj = null;
  1136. else
  1137. obj = str;
  1138. }
  1139. }
  1140. else if (value is bool)
  1141. obj = value;
  1142. else if (value == null)
  1143. obj = null;
  1144. else if ((value is long && type == typeof(long)) || (value is double && type == typeof(double)))
  1145. obj = value;
  1146. else if ((value is double && type != typeof(double)) || (value is long && type != typeof(long)))
  1147. {
  1148. obj =
  1149. #if NETFX_CORE
  1150. type == typeof(int) || type == typeof(long) || type == typeof(double) ||type == typeof(float) || type == typeof(bool) || type == typeof(decimal) ||type == typeof(byte) || type == typeof(short)
  1151. #else
  1152. typeof(IConvertible).IsAssignableFrom(type)
  1153. #endif
  1154. ? Convert.ChangeType(value, type, CultureInfo.InvariantCulture) : value;
  1155. }
  1156. else
  1157. {
  1158. if (value is IDictionary<string, object>)
  1159. {
  1160. IDictionary<string, object> jsonObject = (IDictionary<string, object>)value;
  1161. if (ReflectionUtils.IsTypeDictionary(type))
  1162. {
  1163. // if dictionary then
  1164. #if NETFX_CORE
  1165. Type keyType = type.GetTypeInfo().GenericTypeArguments[0];
  1166. Type valueType = type.GetTypeInfo().GenericTypeArguments[1];
  1167. #else
  1168. Type keyType = type.GetGenericArguments()[0];
  1169. Type valueType = type.GetGenericArguments()[1];
  1170. #endif
  1171. Type genericType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
  1172. #if NETFX_CORE
  1173. dynamic dict = CacheResolver.GetNewInstance(genericType);
  1174. #else
  1175. IDictionary dict = (IDictionary)CacheResolver.GetNewInstance(genericType);
  1176. #endif
  1177. foreach (KeyValuePair<string, object> kvp in jsonObject)
  1178. {
  1179. dict.Add(kvp.Key, DeserializeObject(kvp.Value, valueType));
  1180. }
  1181. obj = dict;
  1182. }
  1183. else
  1184. {
  1185. obj = CacheResolver.GetNewInstance(type);
  1186. SafeDictionary<string, CacheResolver.MemberMap> maps = CacheResolver.LoadMaps(type);
  1187. if (maps == null)
  1188. {
  1189. obj = value;
  1190. }
  1191. else
  1192. {
  1193. foreach (KeyValuePair<string, CacheResolver.MemberMap> keyValuePair in maps)
  1194. {
  1195. CacheResolver.MemberMap v = keyValuePair.Value;
  1196. if (v.Setter == null)
  1197. continue;
  1198. string jsonKey = keyValuePair.Key;
  1199. if (jsonObject.ContainsKey(jsonKey))
  1200. {
  1201. object jsonValue = DeserializeObject(jsonObject[jsonKey], v.Type);
  1202. v.Setter(obj, jsonValue);
  1203. }
  1204. }
  1205. }
  1206. }
  1207. }
  1208. else if (value is IList<object>)
  1209. {
  1210. IList<object> jsonObject = (IList<object>)value;
  1211. IList list = null;
  1212. if (type.IsArray)
  1213. {
  1214. list = (IList)Activator.CreateInstance(type, jsonObject.Count);
  1215. int i = 0;
  1216. foreach (object o in jsonObject)
  1217. list[i++] = DeserializeObject(o, type.GetElementType());
  1218. }
  1219. else if (ReflectionUtils.IsTypeGenericeCollectionInterface(type) ||
  1220. #if NETFX_CORE
  1221. typeof(IList).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())
  1222. #else
  1223. typeof(IList).IsAssignableFrom(type)
  1224. #endif
  1225. )
  1226. {
  1227. #if NETFX_CORE
  1228. Type innerType = type.GetTypeInfo().GenericTypeArguments[0];
  1229. #else
  1230. Type innerType = type.GetGenericArguments()[0];
  1231. #endif
  1232. Type genericType = typeof(List<>).MakeGenericType(innerType);
  1233. list = (IList)CacheResolver.GetNewInstance(genericType);
  1234. foreach (object o in jsonObject)
  1235. list.Add(DeserializeObject(o, innerType));
  1236. }
  1237. obj = list;
  1238. }
  1239. return obj;
  1240. }
  1241. if (ReflectionUtils.IsNullableType(type))
  1242. return ReflectionUtils.ToNullableType(obj, type);
  1243. if (obj == null)
  1244. {
  1245. if (type == typeof(Guid))
  1246. return default(Guid);
  1247. }
  1248. return obj;
  1249. }
  1250. protected virtual object SerializeEnum(Enum p)
  1251. {
  1252. return Convert.ToDouble(p, CultureInfo.InvariantCulture);
  1253. }
  1254. protected virtual bool TrySerializeKnownTypes(object input, out object output)
  1255. {
  1256. bool returnValue = true;
  1257. if (input is DateTime)
  1258. output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);
  1259. else if (input is Guid)
  1260. output = ((Guid)input).ToString("D");
  1261. else if (input is Uri)
  1262. output = input.ToString();
  1263. else if (input is Enum)
  1264. output = SerializeEnum((Enum)input);
  1265. else
  1266. {
  1267. returnValue = false;
  1268. output = null;
  1269. }
  1270. return returnValue;
  1271. }
  1272. protected virtual bool TrySerializeUnknownTypes(object input, out object output)
  1273. {
  1274. output = null;
  1275. // todo: implement caching for types
  1276. Type type = input.GetType();
  1277. if (type.FullName == null)
  1278. return false;
  1279. IDictionary<string, object> obj = new JsonObject();
  1280. SafeDictionary<string, CacheResolver.MemberMap> maps = CacheResolver.LoadMaps(type);
  1281. foreach (KeyValuePair<string, CacheResolver.MemberMap> keyValuePair in maps)
  1282. {
  1283. if (keyValuePair.Value.Getter != null)
  1284. obj.Add(keyValuePair.Key, keyValuePair.Value.Getter(input));
  1285. }
  1286. output = obj;
  1287. return true;
  1288. }
  1289. }
  1290. #if SIMPLE_JSON_DATACONTRACT
  1291. #if SIMPLE_JSON_INTERNAL
  1292. internal
  1293. #else
  1294. public
  1295. #endif
  1296. class DataContractJsonSerializerStrategy : PocoJsonSerializerStrategy
  1297. {
  1298. public DataContractJsonSerializerStrategy()
  1299. {
  1300. CacheResolver = new CacheResolver(BuildMap);
  1301. }
  1302. protected override void BuildMap(Type type, SafeDictionary<string, CacheResolver.MemberMap> map)
  1303. {
  1304. bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null;
  1305. if (!hasDataContract)
  1306. {
  1307. base.BuildMap(type, map);
  1308. return;
  1309. }
  1310. string jsonKey;
  1311. #if NETFX_CORE
  1312. foreach (PropertyInfo info in type.GetTypeInfo().DeclaredProperties)
  1313. #else
  1314. foreach (PropertyInfo info in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
  1315. #endif
  1316. {
  1317. if (CanAdd(info, out jsonKey))
  1318. map.Add(jsonKey, new CacheResolver.MemberMap(info));
  1319. }
  1320. #if NETFX_CORE
  1321. foreach (FieldInfo info in type.GetTypeInfo().DeclaredFields)
  1322. #else
  1323. foreach (FieldInfo info in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
  1324. #endif
  1325. {
  1326. if (CanAdd(info, out jsonKey))
  1327. map.Add(jsonKey, new CacheResolver.MemberMap(info));
  1328. }
  1329. // todo implement sorting for DATACONTRACT.
  1330. }
  1331. private static bool CanAdd(MemberInfo info, out string jsonKey)
  1332. {
  1333. jsonKey = null;
  1334. if (ReflectionUtils.GetAttribute(info, typeof(IgnoreDataMemberAttribute)) != null)
  1335. return false;
  1336. DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)ReflectionUtils.GetAttribute(info, typeof(DataMemberAttribute));
  1337. if (dataMemberAttribute == null)
  1338. return false;
  1339. jsonKey = string.IsNullOrEmpty(dataMemberAttribute.Name) ? info.Name : dataMemberAttribute.Name;
  1340. return true;
  1341. }
  1342. }
  1343. #endif
  1344. #endregion
  1345. #region Reflection helpers
  1346. namespace Reflection
  1347. {
  1348. #if SIMPLE_JSON_INTERNAL
  1349. internal
  1350. #else
  1351. public
  1352. #endif
  1353. class ReflectionUtils
  1354. {
  1355. public static Attribute GetAttribute(MemberInfo info, Type type)
  1356. {
  1357. #if NETFX_CORE
  1358. if (info == null || type == null || !info.IsDefined(type))
  1359. return null;
  1360. return info.GetCustomAttribute(type);
  1361. #else
  1362. if (info == null || type == null || !Attribute.IsDefined(info, type))
  1363. return null;
  1364. return Attribute.GetCustomAttribute(info, type);
  1365. #endif
  1366. }
  1367. public static Attribute GetAttribute(Type objectType, Type attributeType)
  1368. {
  1369. #if NETFX_CORE
  1370. if (objectType == null || attributeType == null || !objectType.GetTypeInfo().IsDefined(attributeType))
  1371. return null;
  1372. return objectType.GetTypeInfo().GetCustomAttribute(attributeType);
  1373. #else
  1374. if (objectType == null || attributeType == null || !Attribute.IsDefined(objectType, attributeType))
  1375. return null;
  1376. return Attribute.GetCustomAttribute(objectType, attributeType);
  1377. #endif
  1378. }
  1379. public static bool IsTypeGenericeCollectionInterface(Type type)
  1380. {
  1381. #if NETFX_CORE
  1382. if (!type.GetTypeInfo().IsGenericType)
  1383. #else
  1384. if (!type.IsGenericType)
  1385. #endif
  1386. return false;
  1387. Type genericDefinition = type.GetGenericTypeDefinition();
  1388. return (genericDefinition == typeof(IList<>) || genericDefinition == typeof(ICollection<>) || genericDefinition == typeof(IEnumerable<>));
  1389. }
  1390. public static bool IsTypeDictionary(Type type)
  1391. {
  1392. #if NETFX_CORE
  1393. if (typeof(IDictionary<,>).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
  1394. return true;
  1395. if (!type.GetTypeInfo().IsGenericType)
  1396. return false;
  1397. #else
  1398. if (typeof(IDictionary).IsAssignableFrom(type))
  1399. return true;
  1400. if (!type.IsGenericType)
  1401. return false;
  1402. #endif
  1403. Type genericDefinition = type.GetGenericTypeDefinition();
  1404. return genericDefinition == typeof(IDictionary<,>);
  1405. }
  1406. public static bool IsNullableType(Type type)
  1407. {
  1408. return
  1409. #if NETFX_CORE
  1410. type.GetTypeInfo().IsGenericType
  1411. #else
  1412. type.IsGenericType
  1413. #endif
  1414. && type.GetGenericTypeDefinition() == typeof(Nullable<>);
  1415. }
  1416. public static object ToNullableType(object obj, Type nullableType)
  1417. {
  1418. return obj == null ? null : Convert.ChangeType(obj, Nullable.GetUnderlyingType(nullableType), CultureInfo.InvariantCulture);
  1419. }
  1420. }
  1421. #if SIMPLE_JSON_INTERNAL
  1422. internal
  1423. #else
  1424. public
  1425. #endif
  1426. delegate object GetHandler(object source);
  1427. #if SIMPLE_JSON_INTERNAL
  1428. internal
  1429. #else
  1430. public
  1431. #endif
  1432. delegate void SetHandler(object source, object value);
  1433. #if SIMPLE_JSON_INTERNAL
  1434. internal
  1435. #else
  1436. public
  1437. #endif
  1438. delegate void MemberMapLoader(Type type, SafeDictionary<string, CacheResolver.MemberMap> memberMaps);
  1439. #if SIMPLE_JSON_INTERNAL
  1440. internal
  1441. #else
  1442. public
  1443. #endif
  1444. class CacheResolver
  1445. {
  1446. private readonly MemberMapLoader _memberMapLoader;
  1447. private readonly SafeDictionary<Type, SafeDictionary<string, MemberMap>> _memberMapsCache = new SafeDictionary<Type, SafeDictionary<string, MemberMap>>();
  1448. delegate object CtorDelegate();
  1449. readonly static SafeDictionary<Type, CtorDelegate> ConstructorCache = new SafeDictionary<Type, CtorDelegate>();
  1450. public CacheResolver(MemberMapLoader memberMapLoader)
  1451. {
  1452. _memberMapLoader = memberMapLoader;
  1453. }
  1454. [SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
  1455. public static object GetNewInstance(Type type)
  1456. {
  1457. CtorDelegate c;
  1458. if (ConstructorCache.TryGetValue(type, out c))
  1459. return c();
  1460. #if SIMPLE_JSON_REFLECTIONEMIT
  1461. DynamicMethod dynamicMethod = new DynamicMethod("Create" + type.FullName, typeof(object), Type.EmptyTypes, type, true);
  1462. dynamicMethod.InitLocals = true;
  1463. ILGenerator generator = dynamicMethod.GetILGenerator();
  1464. if (type.IsValueType)
  1465. {
  1466. generator.DeclareLocal(type);
  1467. generator.Emit(OpCodes.Ldloc_0);
  1468. generator.Emit(OpCodes.Box, type);
  1469. }
  1470. else
  1471. {
  1472. ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
  1473. if (constructorInfo == null)
  1474. throw new Exception(string.Format(CultureInfo.InvariantCulture, "Could not get constructor for {0}.", type));
  1475. generator.Emit(OpCodes.Newobj, constructorInfo);
  1476. }
  1477. generator.Emit(OpCodes.Ret);
  1478. c = (CtorDelegate)dynamicMethod.CreateDelegate(typeof(CtorDelegate));
  1479. ConstructorCache.Add(type, c);
  1480. return c();
  1481. #else
  1482. #if NETFX_CORE
  1483. IEnumerable<ConstructorInfo> constructorInfos = type.GetTypeInfo().DeclaredConstructors;
  1484. ConstructorInfo constructorInfo = null;
  1485. foreach (ConstructorInfo item in constructorInfos) // FirstOrDefault()
  1486. {
  1487. if (item.GetParameters().Length == 0) // Default ctor - make sure it doesn't contain any parameters
  1488. {
  1489. constructorInfo = item;
  1490. break;
  1491. }
  1492. }
  1493. #else
  1494. ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
  1495. #endif
  1496. c = delegate { return constructorInfo.Invoke(null); };
  1497. ConstructorCache.Add(type, c);
  1498. return c();
  1499. #endif
  1500. }
  1501. public SafeDictionary<string, MemberMap> LoadMaps(Type type)
  1502. {
  1503. if (type == null || type == typeof(object))
  1504. return null;
  1505. SafeDictionary<string, MemberMap> maps;
  1506. if (_memberMapsCache.TryGetValue(type, out maps))
  1507. return maps;
  1508. maps = new SafeDictionary<string, MemberMap>();
  1509. _memberMapLoader(type, maps);
  1510. _memberMapsCache.Add(type, maps);
  1511. return maps;
  1512. }
  1513. #if SIMPLE_JSON_REFLECTIONEMIT
  1514. static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner)
  1515. {
  1516. DynamicMethod dynamicMethod = !owner.IsInterface
  1517. ? new DynamicMethod(name, returnType, parameterTypes, owner, true)
  1518. : new DynamicMethod(name, returnType, parameterTypes, (Module)null, true);
  1519. return dynamicMethod;
  1520. }
  1521. #endif
  1522. static GetHandler CreateGetHandler(FieldInfo fieldInfo)
  1523. {
  1524. #if SIMPLE_JSON_REFLECTIONEMIT
  1525. Type type = fieldInfo.FieldType;
  1526. DynamicMethod dynamicGet = CreateDynamicMethod("Get" + fieldInfo.Name, fieldInfo.DeclaringType, new Type[] { typeof(object) }, fieldInfo.DeclaringType);
  1527. ILGenerator getGenerator = dynamicGet.GetILGenerator();
  1528. getGenerator.Emit(OpCodes.Ldarg_0);
  1529. getGenerator.Emit(OpCodes.Ldfld, fieldInfo);
  1530. if (type.IsValueType)
  1531. getGenerator.Emit(OpCodes.Box, type);
  1532. getGenerator.Emit(OpCodes.Ret);
  1533. return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler));
  1534. #else
  1535. return delegate(object instance) { return fieldInfo.GetValue(instance); };
  1536. #endif
  1537. }
  1538. static SetHandler CreateSetHandler(FieldInfo fieldInfo)
  1539. {
  1540. if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral)
  1541. return null;
  1542. #if SIMPLE_JSON_REFLECTIONEMIT
  1543. Type type = fieldInfo.FieldType;
  1544. DynamicMethod dynamicSet = CreateDynamicMethod("Set" + fieldInfo.Name, null, new Type[] { typeof(object), typeof(object) }, fieldInfo.DeclaringType);
  1545. ILGenerator setGenerator = dynamicSet.GetILGenerator();
  1546. setGenerator.Emit(OpCodes.Ldarg_0);
  1547. setGenerator.Emit(OpCodes.Ldarg_1);
  1548. if (type.IsValueType)
  1549. setGenerator.Emit(OpCodes.Unbox_Any, type);
  1550. setGenerator.Emit(OpCodes.Stfld, fieldInfo);
  1551. setGenerator.Emit(OpCodes.Ret);
  1552. return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler));
  1553. #else
  1554. return delegate(object instance, object value) { fieldInfo.SetValue(instance, value); };
  1555. #endif
  1556. }
  1557. static GetHandler CreateGetHandler(PropertyInfo propertyInfo)
  1558. {
  1559. #if NETFX_CORE
  1560. MethodInfo getMethodInfo = propertyInfo.GetMethod;
  1561. #else
  1562. MethodInfo getMethodInfo = propertyInfo.GetGetMethod(true);
  1563. #endif
  1564. if (getMethodInfo == null)
  1565. return null;
  1566. #if SIMPLE_JSON_REFLECTIONEMIT
  1567. Type type = propertyInfo.PropertyType;
  1568. DynamicMethod dynamicGet = CreateDynamicMethod("Get" + propertyInfo.Name, propertyInfo.DeclaringType, new Type[] { typeof(object) }, propertyInfo.DeclaringType);
  1569. ILGenerator getGenerator = dynamicGet.GetILGenerator();
  1570. getGenerator.Emit(OpCodes.Ldarg_0);
  1571. getGenerator.Emit(OpCodes.Call, getMethodInfo);
  1572. if (type.IsValueType)
  1573. getGenerator.Emit(OpCodes.Box, type);
  1574. getGenerator.Emit(OpCodes.Ret);
  1575. return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler));
  1576. #else
  1577. #if NETFX_CORE
  1578. return delegate(object instance) { return getMethodInfo.Invoke(instance, new Type[] { }); };
  1579. #else
  1580. return delegate(object instance) { return getMethodInfo.Invoke(instance, Type.EmptyTypes); };
  1581. #endif
  1582. #endif
  1583. }
  1584. static SetHandler CreateSetHandler(PropertyInfo propertyInfo)
  1585. {
  1586. #if NETFX_CORE
  1587. MethodInfo setMethodInfo = propertyInfo.SetMethod;
  1588. #else
  1589. MethodInfo setMethodInfo = propertyInfo.GetSetMethod(true);
  1590. #endif
  1591. if (setMethodInfo == null)
  1592. return null;
  1593. #if SIMPLE_JSON_REFLECTIONEMIT
  1594. Type type = propertyInfo.PropertyType;
  1595. DynamicMethod dynamicSet = CreateDynamicMethod("Set" + propertyInfo.Name, null, new Type[] { typeof(object), typeof(object) }, propertyInfo.DeclaringType);
  1596. ILGenerator setGenerator = dynamicSet.GetILGenerator();
  1597. setGenerator.Emit(OpCodes.Ldarg_0);
  1598. setGenerator.Emit(OpCodes.Ldarg_1);
  1599. if (type.IsValueType)
  1600. setGenerator.Emit(OpCodes.Unbox_Any, type);
  1601. setGenerator.Emit(OpCodes.Call, setMethodInfo);
  1602. setGenerator.Emit(OpCodes.Ret);
  1603. return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler));
  1604. #else
  1605. return delegate(object instance, object value) { setMethodInfo.Invoke(instance, new[] { value }); };
  1606. #endif
  1607. }
  1608. #if SIMPLE_JSON_INTERNAL
  1609. internal
  1610. #else
  1611. public
  1612. #endif
  1613. sealed class MemberMap
  1614. {
  1615. public readonly MemberInfo MemberInfo;
  1616. public readonly Type Type;
  1617. public readonly GetHandler Getter;
  1618. public readonly SetHandler Setter;
  1619. public MemberMap(PropertyInfo propertyInfo)
  1620. {
  1621. MemberInfo = propertyInfo;
  1622. Type = propertyInfo.PropertyType;
  1623. Getter = CreateGetHandler(propertyInfo);
  1624. Setter = CreateSetHandler(propertyInfo);
  1625. }
  1626. public MemberMap(FieldInfo fieldInfo)
  1627. {
  1628. MemberInfo = fieldInfo;
  1629. Type = fieldInfo.FieldType;
  1630. Getter = CreateGetHandler(fieldInfo);
  1631. Setter = CreateSetHandler(fieldInfo);
  1632. }
  1633. }
  1634. }
  1635. #if SIMPLE_JSON_INTERNAL
  1636. internal
  1637. #else
  1638. public
  1639. #endif
  1640. class SafeDictionary<TKey, TValue>
  1641. {
  1642. private readonly object _padlock = new object();
  1643. private readonly Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();
  1644. public bool TryGetValue(TKey key, out TValue value)
  1645. {
  1646. return _dictionary.TryGetValue(key, out value);
  1647. }
  1648. public TValue this[TKey key]
  1649. {
  1650. get { return _dictionary[key]; }
  1651. }
  1652. public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
  1653. {
  1654. return ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).GetEnumerator();
  1655. }
  1656. public void Add(TKey key, TValue value)
  1657. {
  1658. lock (_padlock)
  1659. {
  1660. if (_dictionary.ContainsKey(key) == false)
  1661. _dictionary.Add(key, value);
  1662. }
  1663. }
  1664. }
  1665. }
  1666. #endregion
  1667. }