SimpleJson.cs 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221
  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 enable IReadOnlyCollection<T> and IReadOnlyList<T> support.
  29. //#define SIMPLE_JSON_READONLY_COLLECTIONS
  30. // NOTE: uncomment the following line to disable linq expressions/compiled lambda (better performance) instead of method.invoke().
  31. // define if you are using .net framework <= 3.0 or < WP7.5
  32. //#define SIMPLE_JSON_NO_LINQ_EXPRESSION
  33. // NOTE: uncomment the following line if you are compiling under Window Metro style application/library.
  34. // usually already defined in properties
  35. //#define NETFX_CORE;
  36. // If you are targetting WinStore, WP8 and NET4.5+ PCL make sure to #define SIMPLE_JSON_TYPEINFO;
  37. // 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
  38. #if NETFX_CORE
  39. #define SIMPLE_JSON_TYPEINFO
  40. #endif
  41. using System;
  42. //using System.CodeDom.Compiler;
  43. using System.Collections;
  44. using System.Collections.Generic;
  45. #if !SIMPLE_JSON_NO_LINQ_EXPRESSION
  46. using System.Linq.Expressions;
  47. #endif
  48. using System.ComponentModel;
  49. using System.Diagnostics.CodeAnalysis;
  50. #if SIMPLE_JSON_DYNAMIC
  51. using System.Dynamic;
  52. #endif
  53. using System.Globalization;
  54. using System.Reflection;
  55. using System.Runtime.Serialization;
  56. using System.Text;
  57. //using SimpleJson.Reflection;
  58. // ReSharper disable LoopCanBeConvertedToQuery
  59. // ReSharper disable RedundantExplicitArrayCreation
  60. // ReSharper disable SuggestUseVarKeywordEvident
  61. namespace SimpleJson
  62. {
  63. /// <summary>
  64. /// Represents the json array.
  65. /// </summary>
  66. // [GeneratedCode("simple-json", "1.0.0")]
  67. [EditorBrowsable(EditorBrowsableState.Never)]
  68. [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
  69. #if SIMPLE_JSON_OBJARRAYINTERNAL
  70. internal
  71. #else
  72. public
  73. #endif
  74. class JsonArray : List<object>
  75. {
  76. /// <summary>
  77. /// Initializes a new instance of the <see cref="JsonArray"/> class.
  78. /// </summary>
  79. public JsonArray() { }
  80. /// <summary>
  81. /// Initializes a new instance of the <see cref="JsonArray"/> class.
  82. /// </summary>
  83. /// <param name="capacity">The capacity of the json array.</param>
  84. public JsonArray(int capacity) : base(capacity) { }
  85. /// <summary>
  86. /// The json representation of the array.
  87. /// </summary>
  88. /// <returns>The json representation of the array.</returns>
  89. public override string ToString()
  90. {
  91. return SimpleJson.SerializeObject(this) ?? string.Empty;
  92. }
  93. }
  94. /// <summary>
  95. /// Represents the json object.
  96. /// </summary>
  97. // [GeneratedCode("simple-json", "1.0.0")]
  98. [EditorBrowsable(EditorBrowsableState.Never)]
  99. [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
  100. #if SIMPLE_JSON_OBJARRAYINTERNAL
  101. internal
  102. #else
  103. public
  104. #endif
  105. class JsonObject :
  106. #if SIMPLE_JSON_DYNAMIC
  107. DynamicObject,
  108. #endif
  109. IDictionary<string, object>
  110. {
  111. /// <summary>
  112. /// The internal member dictionary.
  113. /// </summary>
  114. private readonly Dictionary<string, object> _members;
  115. /// <summary>
  116. /// Initializes a new instance of <see cref="JsonObject"/>.
  117. /// </summary>
  118. public JsonObject()
  119. {
  120. _members = new Dictionary<string, object>();
  121. }
  122. /// <summary>
  123. /// Initializes a new instance of <see cref="JsonObject"/>.
  124. /// </summary>
  125. /// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer`1"/> implementation to use when comparing keys, or null to use the default <see cref="T:System.Collections.Generic.EqualityComparer`1"/> for the type of the key.</param>
  126. public JsonObject(IEqualityComparer<string> comparer)
  127. {
  128. _members = new Dictionary<string, object>(comparer);
  129. }
  130. /// <summary>
  131. /// Gets the <see cref="System.Object"/> at the specified index.
  132. /// </summary>
  133. /// <value></value>
  134. public object this[int index]
  135. {
  136. get { return GetAtIndex(_members, index); }
  137. }
  138. internal static object GetAtIndex(IDictionary<string, object> obj, int index)
  139. {
  140. if (obj == null)
  141. throw new ArgumentNullException("obj");
  142. if (index >= obj.Count)
  143. throw new ArgumentOutOfRangeException("index");
  144. int i = 0;
  145. foreach (KeyValuePair<string, object> o in obj)
  146. if (i++ == index) return o.Value;
  147. return null;
  148. }
  149. /// <summary>
  150. /// Adds the specified key.
  151. /// </summary>
  152. /// <param name="key">The key.</param>
  153. /// <param name="value">The value.</param>
  154. public void Add(string key, object value)
  155. {
  156. _members.Add(key, value);
  157. }
  158. /// <summary>
  159. /// Determines whether the specified key contains key.
  160. /// </summary>
  161. /// <param name="key">The key.</param>
  162. /// <returns>
  163. /// <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
  164. /// </returns>
  165. public bool ContainsKey(string key)
  166. {
  167. return _members.ContainsKey(key);
  168. }
  169. /// <summary>
  170. /// Gets the keys.
  171. /// </summary>
  172. /// <value>The keys.</value>
  173. public ICollection<string> Keys
  174. {
  175. get { return _members.Keys; }
  176. }
  177. /// <summary>
  178. /// Removes the specified key.
  179. /// </summary>
  180. /// <param name="key">The key.</param>
  181. /// <returns></returns>
  182. public bool Remove(string key)
  183. {
  184. return _members.Remove(key);
  185. }
  186. /// <summary>
  187. /// Tries the get value.
  188. /// </summary>
  189. /// <param name="key">The key.</param>
  190. /// <param name="value">The value.</param>
  191. /// <returns></returns>
  192. public bool TryGetValue(string key, out object value)
  193. {
  194. try
  195. {
  196. return _members.TryGetValue(key, out value);
  197. }
  198. catch(Exception)
  199. {
  200. value = null;
  201. return false;
  202. }
  203. }
  204. /// <summary>
  205. /// Gets the values.
  206. /// </summary>
  207. /// <value>The values.</value>
  208. public ICollection<object> Values
  209. {
  210. get { return _members.Values; }
  211. }
  212. /// <summary>
  213. /// Gets or sets the <see cref="System.Object"/> with the specified key.
  214. /// </summary>
  215. /// <value></value>
  216. public object this[string key]
  217. {
  218. get { return _members[key]; }
  219. set { _members[key] = value; }
  220. }
  221. /// <summary>
  222. /// Adds the specified item.
  223. /// </summary>
  224. /// <param name="item">The item.</param>
  225. public void Add(KeyValuePair<string, object> item)
  226. {
  227. _members.Add(item.Key, item.Value);
  228. }
  229. /// <summary>
  230. /// Clears this instance.
  231. /// </summary>
  232. public void Clear()
  233. {
  234. _members.Clear();
  235. }
  236. /// <summary>
  237. /// Determines whether [contains] [the specified item].
  238. /// </summary>
  239. /// <param name="item">The item.</param>
  240. /// <returns>
  241. /// <c>true</c> if [contains] [the specified item]; otherwise, <c>false</c>.
  242. /// </returns>
  243. public bool Contains(KeyValuePair<string, object> item)
  244. {
  245. return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value;
  246. }
  247. /// <summary>
  248. /// Copies to.
  249. /// </summary>
  250. /// <param name="array">The array.</param>
  251. /// <param name="arrayIndex">Index of the array.</param>
  252. public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
  253. {
  254. if (array == null) throw new ArgumentNullException("array");
  255. int num = Count;
  256. foreach (KeyValuePair<string, object> kvp in this)
  257. {
  258. array[arrayIndex++] = kvp;
  259. if (--num <= 0)
  260. return;
  261. }
  262. }
  263. /// <summary>
  264. /// Gets the count.
  265. /// </summary>
  266. /// <value>The count.</value>
  267. public int Count
  268. {
  269. get { return _members.Count; }
  270. }
  271. /// <summary>
  272. /// Gets a value indicating whether this instance is read only.
  273. /// </summary>
  274. /// <value>
  275. /// <c>true</c> if this instance is read only; otherwise, <c>false</c>.
  276. /// </value>
  277. public bool IsReadOnly
  278. {
  279. get { return false; }
  280. }
  281. /// <summary>
  282. /// Removes the specified item.
  283. /// </summary>
  284. /// <param name="item">The item.</param>
  285. /// <returns></returns>
  286. public bool Remove(KeyValuePair<string, object> item)
  287. {
  288. return _members.Remove(item.Key);
  289. }
  290. /// <summary>
  291. /// Gets the enumerator.
  292. /// </summary>
  293. /// <returns></returns>
  294. public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
  295. {
  296. return _members.GetEnumerator();
  297. }
  298. /// <summary>
  299. /// Returns an enumerator that iterates through a collection.
  300. /// </summary>
  301. /// <returns>
  302. /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
  303. /// </returns>
  304. IEnumerator IEnumerable.GetEnumerator()
  305. {
  306. return _members.GetEnumerator();
  307. }
  308. /// <summary>
  309. /// Returns a json <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
  310. /// </summary>
  311. /// <returns>
  312. /// A json <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
  313. /// </returns>
  314. public override string ToString()
  315. {
  316. return SimpleJson.SerializeObject(this);
  317. }
  318. #if SIMPLE_JSON_DYNAMIC
  319. /// <summary>
  320. /// 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.
  321. /// </summary>
  322. /// <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>
  323. /// <param name="result">The result of the type conversion operation.</param>
  324. /// <returns>
  325. /// Alwasy returns true.
  326. /// </returns>
  327. public override bool TryConvert(ConvertBinder binder, out object result)
  328. {
  329. // <pex>
  330. if (binder == null)
  331. throw new ArgumentNullException("binder");
  332. // </pex>
  333. Type targetType = binder.Type;
  334. if ((targetType == typeof(IEnumerable)) ||
  335. (targetType == typeof(IEnumerable<KeyValuePair<string, object>>)) ||
  336. (targetType == typeof(IDictionary<string, object>)) ||
  337. (targetType == typeof(IDictionary)))
  338. {
  339. result = this;
  340. return true;
  341. }
  342. return base.TryConvert(binder, out result);
  343. }
  344. /// <summary>
  345. /// Provides the implementation for operations that delete an object member. This method is not intended for use in C# or Visual Basic.
  346. /// </summary>
  347. /// <param name="binder">Provides information about the deletion.</param>
  348. /// <returns>
  349. /// Alwasy returns true.
  350. /// </returns>
  351. public override bool TryDeleteMember(DeleteMemberBinder binder)
  352. {
  353. // <pex>
  354. if (binder == null)
  355. throw new ArgumentNullException("binder");
  356. // </pex>
  357. return _members.Remove(binder.Name);
  358. }
  359. /// <summary>
  360. /// 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.
  361. /// </summary>
  362. /// <param name="binder">Provides information about the operation.</param>
  363. /// <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>
  364. /// <param name="result">The result of the index operation.</param>
  365. /// <returns>
  366. /// Alwasy returns true.
  367. /// </returns>
  368. public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
  369. {
  370. if (indexes == null) throw new ArgumentNullException("indexes");
  371. if (indexes.Length == 1)
  372. {
  373. result = ((IDictionary<string, object>)this)[(string)indexes[0]];
  374. return true;
  375. }
  376. result = null;
  377. return true;
  378. }
  379. /// <summary>
  380. /// 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.
  381. /// </summary>
  382. /// <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>
  383. /// <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>
  384. /// <returns>
  385. /// Alwasy returns true.
  386. /// </returns>
  387. public override bool TryGetMember(GetMemberBinder binder, out object result)
  388. {
  389. object value;
  390. if (_members.TryGetValue(binder.Name, out value))
  391. {
  392. result = value;
  393. return true;
  394. }
  395. result = null;
  396. return true;
  397. }
  398. /// <summary>
  399. /// 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.
  400. /// </summary>
  401. /// <param name="binder">Provides information about the operation.</param>
  402. /// <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>
  403. /// <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>
  404. /// <returns>
  405. /// 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.
  406. /// </returns>
  407. public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
  408. {
  409. if (indexes == null) throw new ArgumentNullException("indexes");
  410. if (indexes.Length == 1)
  411. {
  412. ((IDictionary<string, object>)this)[(string)indexes[0]] = value;
  413. return true;
  414. }
  415. return base.TrySetIndex(binder, indexes, value);
  416. }
  417. /// <summary>
  418. /// 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.
  419. /// </summary>
  420. /// <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>
  421. /// <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>
  422. /// <returns>
  423. /// 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.)
  424. /// </returns>
  425. public override bool TrySetMember(SetMemberBinder binder, object value)
  426. {
  427. // <pex>
  428. if (binder == null)
  429. throw new ArgumentNullException("binder");
  430. // </pex>
  431. _members[binder.Name] = value;
  432. return true;
  433. }
  434. /// <summary>
  435. /// Returns the enumeration of all dynamic member names.
  436. /// </summary>
  437. /// <returns>
  438. /// A sequence that contains dynamic member names.
  439. /// </returns>
  440. public override IEnumerable<string> GetDynamicMemberNames()
  441. {
  442. foreach (var key in Keys)
  443. yield return key;
  444. }
  445. #endif
  446. }
  447. }
  448. namespace SimpleJson
  449. {
  450. /// <summary>
  451. /// This class encodes and decodes JSON strings.
  452. /// Spec. details, see http://www.json.org/
  453. ///
  454. /// JSON uses Arrays and Objects. These correspond here to the datatypes JsonArray(IList&lt;object>) and JsonObject(IDictionary&lt;string,object>).
  455. /// All numbers are parsed to doubles.
  456. /// </summary>
  457. // [GeneratedCode("simple-json", "1.0.0")]
  458. #if SIMPLE_JSON_INTERNAL
  459. internal
  460. #else
  461. public
  462. #endif
  463. static class SimpleJson
  464. {
  465. private const int TOKEN_NONE = 0;
  466. private const int TOKEN_CURLY_OPEN = 1;
  467. private const int TOKEN_CURLY_CLOSE = 2;
  468. private const int TOKEN_SQUARED_OPEN = 3;
  469. private const int TOKEN_SQUARED_CLOSE = 4;
  470. private const int TOKEN_COLON = 5;
  471. private const int TOKEN_COMMA = 6;
  472. private const int TOKEN_STRING = 7;
  473. private const int TOKEN_NUMBER = 8;
  474. private const int TOKEN_TRUE = 9;
  475. private const int TOKEN_FALSE = 10;
  476. private const int TOKEN_NULL = 11;
  477. private const int BUILDER_CAPACITY = 2000;
  478. private static readonly char[] EscapeTable;
  479. private static readonly char[] EscapeCharacters = new char[] { '"', '\\', '\b', '\f', '\n', '\r', '\t' };
  480. private static readonly string EscapeCharactersString = new string(EscapeCharacters);
  481. static SimpleJson()
  482. {
  483. EscapeTable = new char[93];
  484. EscapeTable['"'] = '"';
  485. EscapeTable['\\'] = '\\';
  486. EscapeTable['\b'] = 'b';
  487. EscapeTable['\f'] = 'f';
  488. EscapeTable['\n'] = 'n';
  489. EscapeTable['\r'] = 'r';
  490. EscapeTable['\t'] = 't';
  491. }
  492. /// <summary>
  493. /// Parses the string json into a value
  494. /// </summary>
  495. /// <param name="json">A JSON string.</param>
  496. /// <returns>An IList&lt;object>, a IDictionary&lt;string,object>, a double, a string, null, true, or false</returns>
  497. public static object DeserializeObject(string json)
  498. {
  499. object obj;
  500. if (TryDeserializeObject(json, out obj))
  501. return obj;
  502. return "Invalid JSON string";
  503. //throw new SerializationException("Invalid JSON string");
  504. }
  505. /// <summary>
  506. /// Try parsing the json string into a value.
  507. /// </summary>
  508. /// <param name="json">
  509. /// A JSON string.
  510. /// </param>
  511. /// <param name="obj">
  512. /// The object.
  513. /// </param>
  514. /// <returns>
  515. /// Returns true if successfull otherwise false.
  516. /// </returns>
  517. [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")]
  518. public static bool TryDeserializeObject(string json, out object obj)
  519. {
  520. bool success = true;
  521. if (json != null)
  522. {
  523. char[] charArray = json.ToCharArray();
  524. int index = 0;
  525. obj = ParseValue(charArray, ref index, ref success);
  526. }
  527. else
  528. obj = null;
  529. return success;
  530. }
  531. //public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy)
  532. //{
  533. // object jsonObject = DeserializeObject(json);
  534. // return type == null || jsonObject != null && ReflectionUtils.IsAssignableFrom(jsonObject.GetType(), type)
  535. // ? jsonObject
  536. // : (jsonSerializerStrategy ?? CurrentJsonSerializerStrategy).DeserializeObject(jsonObject, type);
  537. //}
  538. //public static object DeserializeObject(string json, Type type)
  539. //{
  540. // return DeserializeObject(json, type, null);
  541. //}
  542. //public static T DeserializeObject<T>(string json, IJsonSerializerStrategy jsonSerializerStrategy)
  543. //{
  544. // return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy);
  545. //}
  546. //public static T DeserializeObject<T>(string json)
  547. //{
  548. // return (T)DeserializeObject(json, typeof(T), null);
  549. //}
  550. /// <summary>
  551. /// Converts a IDictionary&lt;string,object> / IList&lt;object> object into a JSON string
  552. /// </summary>
  553. /// <param name="json">A IDictionary&lt;string,object> / IList&lt;object></param>
  554. /// <param name="jsonSerializerStrategy">Serializer strategy to use</param>
  555. /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
  556. public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy)
  557. {
  558. StringBuilder builder = new StringBuilder(BUILDER_CAPACITY);
  559. bool success = SerializeValue(jsonSerializerStrategy, json, builder);
  560. return (success ? builder.ToString() : null);
  561. }
  562. public static string SerializeObject(object json)
  563. {
  564. return SerializeObject(json, CurrentJsonSerializerStrategy);
  565. }
  566. public static string EscapeToJavascriptString(string jsonString)
  567. {
  568. if (string.IsNullOrEmpty(jsonString))
  569. return jsonString;
  570. StringBuilder sb = new StringBuilder();
  571. char c;
  572. for (int i = 0; i < jsonString.Length; )
  573. {
  574. c = jsonString[i++];
  575. if (c == '\\')
  576. {
  577. int remainingLength = jsonString.Length - i;
  578. if (remainingLength >= 2)
  579. {
  580. char lookahead = jsonString[i];
  581. if (lookahead == '\\')
  582. {
  583. sb.Append('\\');
  584. ++i;
  585. }
  586. else if (lookahead == '"')
  587. {
  588. sb.Append("\"");
  589. ++i;
  590. }
  591. else if (lookahead == 't')
  592. {
  593. sb.Append('\t');
  594. ++i;
  595. }
  596. else if (lookahead == 'b')
  597. {
  598. sb.Append('\b');
  599. ++i;
  600. }
  601. else if (lookahead == 'n')
  602. {
  603. sb.Append('\n');
  604. ++i;
  605. }
  606. else if (lookahead == 'r')
  607. {
  608. sb.Append('\r');
  609. ++i;
  610. }
  611. }
  612. }
  613. else
  614. {
  615. sb.Append(c);
  616. }
  617. }
  618. return sb.ToString();
  619. }
  620. static IDictionary<string, object> ParseObject(char[] json, ref int index, ref bool success)
  621. {
  622. IDictionary<string, object> table = new JsonObject();
  623. int token;
  624. // {
  625. NextToken(json, ref index);
  626. bool done = false;
  627. while (!done)
  628. {
  629. token = LookAhead(json, index);
  630. if (token == TOKEN_NONE)
  631. {
  632. success = false;
  633. return null;
  634. }
  635. else if (token == TOKEN_COMMA)
  636. NextToken(json, ref index);
  637. else if (token == TOKEN_CURLY_CLOSE)
  638. {
  639. NextToken(json, ref index);
  640. return table;
  641. }
  642. else
  643. {
  644. // name
  645. string name = ParseString(json, ref index, ref success);
  646. if (!success)
  647. {
  648. success = false;
  649. return null;
  650. }
  651. // :
  652. token = NextToken(json, ref index);
  653. if (token != TOKEN_COLON)
  654. {
  655. success = false;
  656. return null;
  657. }
  658. // value
  659. object value = ParseValue(json, ref index, ref success);
  660. if (!success)
  661. {
  662. success = false;
  663. return null;
  664. }
  665. table[name] = value;
  666. }
  667. }
  668. return table;
  669. }
  670. static JsonArray ParseArray(char[] json, ref int index, ref bool success)
  671. {
  672. JsonArray array = new JsonArray();
  673. // [
  674. NextToken(json, ref index);
  675. bool done = false;
  676. while (!done)
  677. {
  678. int token = LookAhead(json, index);
  679. if (token == TOKEN_NONE)
  680. {
  681. success = false;
  682. return null;
  683. }
  684. else if (token == TOKEN_COMMA)
  685. NextToken(json, ref index);
  686. else if (token == TOKEN_SQUARED_CLOSE)
  687. {
  688. NextToken(json, ref index);
  689. break;
  690. }
  691. else
  692. {
  693. object value = ParseValue(json, ref index, ref success);
  694. if (!success)
  695. return null;
  696. array.Add(value);
  697. }
  698. }
  699. return array;
  700. }
  701. static object ParseValue(char[] json, ref int index, ref bool success)
  702. {
  703. switch (LookAhead(json, index))
  704. {
  705. case TOKEN_STRING:
  706. return ParseString(json, ref index, ref success);
  707. case TOKEN_NUMBER:
  708. return ParseNumber(json, ref index, ref success);
  709. case TOKEN_CURLY_OPEN:
  710. return ParseObject(json, ref index, ref success);
  711. case TOKEN_SQUARED_OPEN:
  712. return ParseArray(json, ref index, ref success);
  713. case TOKEN_TRUE:
  714. NextToken(json, ref index);
  715. return true;
  716. case TOKEN_FALSE:
  717. NextToken(json, ref index);
  718. return false;
  719. case TOKEN_NULL:
  720. NextToken(json, ref index);
  721. return null;
  722. case TOKEN_NONE:
  723. break;
  724. }
  725. success = false;
  726. return null;
  727. }
  728. static string ParseString(char[] json, ref int index, ref bool success)
  729. {
  730. StringBuilder s = new StringBuilder(BUILDER_CAPACITY);
  731. char c;
  732. EatWhitespace(json, ref index);
  733. // "
  734. c = json[index++];
  735. bool complete = false;
  736. while (!complete)
  737. {
  738. if (index == json.Length)
  739. break;
  740. c = json[index++];
  741. if (c == '"')
  742. {
  743. complete = true;
  744. break;
  745. }
  746. else if (c == '\\')
  747. {
  748. if (index == json.Length)
  749. break;
  750. c = json[index++];
  751. if (c == '"')
  752. s.Append('"');
  753. else if (c == '\\')
  754. s.Append('\\');
  755. else if (c == '/')
  756. s.Append('/');
  757. else if (c == 'b')
  758. s.Append('\b');
  759. else if (c == 'f')
  760. s.Append('\f');
  761. else if (c == 'n')
  762. s.Append('\n');
  763. else if (c == 'r')
  764. s.Append('\r');
  765. else if (c == 't')
  766. s.Append('\t');
  767. else if (c == 'u')
  768. {
  769. int remainingLength = json.Length - index;
  770. if (remainingLength >= 4)
  771. {
  772. // parse the 32 bit hex into an integer codepoint
  773. uint codePoint;
  774. if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint)))
  775. return "";
  776. // convert the integer codepoint to a unicode char and add to string
  777. if (0xD800 <= codePoint && codePoint <= 0xDBFF) // if high surrogate
  778. {
  779. index += 4; // skip 4 chars
  780. remainingLength = json.Length - index;
  781. if (remainingLength >= 6)
  782. {
  783. uint lowCodePoint;
  784. if (new string(json, index, 2) == "\\u" && UInt32.TryParse(new string(json, index + 2, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lowCodePoint))
  785. {
  786. if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF) // if low surrogate
  787. {
  788. s.Append((char)codePoint);
  789. s.Append((char)lowCodePoint);
  790. index += 6; // skip 6 chars
  791. continue;
  792. }
  793. }
  794. }
  795. success = false; // invalid surrogate pair
  796. return "";
  797. }
  798. s.Append(ConvertFromUtf32((int)codePoint));
  799. // skip 4 chars
  800. index += 4;
  801. }
  802. else
  803. break;
  804. }
  805. }
  806. else
  807. s.Append(c);
  808. }
  809. if (!complete)
  810. {
  811. success = false;
  812. return null;
  813. }
  814. return s.ToString();
  815. }
  816. private static string ConvertFromUtf32(int utf32)
  817. {
  818. // http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System/System/Char.cs.htm
  819. if (utf32 < 0 || utf32 > 0x10FFFF)
  820. throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF.");
  821. if (0xD800 <= utf32 && utf32 <= 0xDFFF)
  822. throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range.");
  823. if (utf32 < 0x10000)
  824. return new string((char)utf32, 1);
  825. utf32 -= 0x10000;
  826. return new string(new char[] { (char)((utf32 >> 10) + 0xD800), (char)(utf32 % 0x0400 + 0xDC00) });
  827. }
  828. static object ParseNumber(char[] json, ref int index, ref bool success)
  829. {
  830. EatWhitespace(json, ref index);
  831. int lastIndex = GetLastIndexOfNumber(json, index);
  832. int charLength = (lastIndex - index) + 1;
  833. object returnNumber;
  834. string str = new string(json, index, charLength);
  835. if (str.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || str.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1)
  836. {
  837. double number;
  838. success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
  839. returnNumber = number;
  840. }
  841. else
  842. {
  843. long number;
  844. success = long.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
  845. returnNumber = number;
  846. }
  847. index = lastIndex + 1;
  848. return returnNumber;
  849. }
  850. static int GetLastIndexOfNumber(char[] json, int index)
  851. {
  852. int lastIndex;
  853. for (lastIndex = index; lastIndex < json.Length; lastIndex++)
  854. if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) break;
  855. return lastIndex - 1;
  856. }
  857. static void EatWhitespace(char[] json, ref int index)
  858. {
  859. for (; index < json.Length; index++)
  860. if (" \t\n\r\b\f".IndexOf(json[index]) == -1) break;
  861. }
  862. static int LookAhead(char[] json, int index)
  863. {
  864. int saveIndex = index;
  865. return NextToken(json, ref saveIndex);
  866. }
  867. [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
  868. static int NextToken(char[] json, ref int index)
  869. {
  870. EatWhitespace(json, ref index);
  871. if (index == json.Length)
  872. return TOKEN_NONE;
  873. char c = json[index];
  874. index++;
  875. switch (c)
  876. {
  877. case '{':
  878. return TOKEN_CURLY_OPEN;
  879. case '}':
  880. return TOKEN_CURLY_CLOSE;
  881. case '[':
  882. return TOKEN_SQUARED_OPEN;
  883. case ']':
  884. return TOKEN_SQUARED_CLOSE;
  885. case ',':
  886. return TOKEN_COMMA;
  887. case '"':
  888. return TOKEN_STRING;
  889. case '0':
  890. case '1':
  891. case '2':
  892. case '3':
  893. case '4':
  894. case '5':
  895. case '6':
  896. case '7':
  897. case '8':
  898. case '9':
  899. case '-':
  900. return TOKEN_NUMBER;
  901. case ':':
  902. return TOKEN_COLON;
  903. }
  904. index--;
  905. int remainingLength = json.Length - index;
  906. // false
  907. if (remainingLength >= 5)
  908. {
  909. if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e')
  910. {
  911. index += 5;
  912. return TOKEN_FALSE;
  913. }
  914. }
  915. // true
  916. if (remainingLength >= 4)
  917. {
  918. if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e')
  919. {
  920. index += 4;
  921. return TOKEN_TRUE;
  922. }
  923. }
  924. // null
  925. if (remainingLength >= 4)
  926. {
  927. if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l')
  928. {
  929. index += 4;
  930. return TOKEN_NULL;
  931. }
  932. }
  933. return TOKEN_NONE;
  934. }
  935. static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, StringBuilder builder)
  936. {
  937. bool success = true;
  938. string stringValue = value as string;
  939. if (stringValue != null)
  940. success = SerializeString(stringValue, builder);
  941. else
  942. {
  943. IDictionary<string, object> dict = value as IDictionary<string, object>;
  944. if (dict != null)
  945. {
  946. success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder);
  947. }
  948. else
  949. {
  950. IDictionary<string, string> stringDictionary = value as IDictionary<string, string>;
  951. if (stringDictionary != null)
  952. {
  953. success = SerializeObject(jsonSerializerStrategy, stringDictionary.Keys, stringDictionary.Values, builder);
  954. }
  955. else
  956. {
  957. IEnumerable enumerableValue = value as IEnumerable;
  958. if (enumerableValue != null)
  959. success = SerializeArray(jsonSerializerStrategy, enumerableValue, builder);
  960. else if (IsNumeric(value))
  961. success = SerializeNumber(value, builder);
  962. else if (value is bool)
  963. builder.Append((bool)value ? "true" : "false");
  964. else if (value == null)
  965. builder.Append("null");
  966. else
  967. {
  968. object serializedObject;
  969. success = jsonSerializerStrategy.TrySerializeNonPrimitiveObject(value, out serializedObject);
  970. if (success)
  971. SerializeValue(jsonSerializerStrategy, serializedObject, builder);
  972. }
  973. }
  974. }
  975. }
  976. return success;
  977. }
  978. static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder)
  979. {
  980. builder.Append("{");
  981. IEnumerator ke = keys.GetEnumerator();
  982. IEnumerator ve = values.GetEnumerator();
  983. bool first = true;
  984. while (ke.MoveNext() && ve.MoveNext())
  985. {
  986. object key = ke.Current;
  987. object value = ve.Current;
  988. if (!first)
  989. builder.Append(",");
  990. string stringKey = key as string;
  991. if (stringKey != null)
  992. SerializeString(stringKey, builder);
  993. else
  994. if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false;
  995. builder.Append(":");
  996. if (!SerializeValue(jsonSerializerStrategy, value, builder))
  997. return false;
  998. first = false;
  999. }
  1000. builder.Append("}");
  1001. return true;
  1002. }
  1003. static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder)
  1004. {
  1005. builder.Append("[");
  1006. bool first = true;
  1007. foreach (object value in anArray)
  1008. {
  1009. if (!first)
  1010. builder.Append(",");
  1011. if (!SerializeValue(jsonSerializerStrategy, value, builder))
  1012. return false;
  1013. first = false;
  1014. }
  1015. builder.Append("]");
  1016. return true;
  1017. }
  1018. static bool SerializeString(string aString, StringBuilder builder)
  1019. {
  1020. // Happy path if there's nothing to be escaped. IndexOfAny is highly optimized (and unmanaged)
  1021. if (aString.IndexOfAny(EscapeCharacters) == -1)
  1022. {
  1023. builder.Append('"');
  1024. builder.Append(aString);
  1025. builder.Append('"');
  1026. return true;
  1027. }
  1028. builder.Append('"');
  1029. int safeCharacterCount = 0;
  1030. char[] charArray = aString.ToCharArray();
  1031. for (int i = 0; i < charArray.Length; i++)
  1032. {
  1033. char c = charArray[i];
  1034. // Non ascii characters are fine, buffer them up and send them to the builder
  1035. // in larger chunks if possible. The escape table is a 1:1 translation table
  1036. // with \0 [default(char)] denoting a safe character.
  1037. if (c >= EscapeTable.Length || EscapeTable[c] == default(char))
  1038. {
  1039. safeCharacterCount++;
  1040. }
  1041. else
  1042. {
  1043. if (safeCharacterCount > 0)
  1044. {
  1045. builder.Append(charArray, i - safeCharacterCount, safeCharacterCount);
  1046. safeCharacterCount = 0;
  1047. }
  1048. builder.Append('\\');
  1049. builder.Append(EscapeTable[c]);
  1050. }
  1051. }
  1052. if (safeCharacterCount > 0)
  1053. {
  1054. builder.Append(charArray, charArray.Length - safeCharacterCount, safeCharacterCount);
  1055. }
  1056. builder.Append('"');
  1057. return true;
  1058. }
  1059. static bool SerializeNumber(object number, StringBuilder builder)
  1060. {
  1061. if (number is long)
  1062. builder.Append(((long)number).ToString(CultureInfo.InvariantCulture));
  1063. else if (number is ulong)
  1064. builder.Append(((ulong)number).ToString(CultureInfo.InvariantCulture));
  1065. else if (number is int)
  1066. builder.Append(((int)number).ToString(CultureInfo.InvariantCulture));
  1067. else if (number is uint)
  1068. builder.Append(((uint)number).ToString(CultureInfo.InvariantCulture));
  1069. else if (number is decimal)
  1070. builder.Append(((decimal)number).ToString(CultureInfo.InvariantCulture));
  1071. else if (number is float)
  1072. builder.Append(((float)number).ToString(CultureInfo.InvariantCulture));
  1073. else
  1074. builder.Append(Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString("r", CultureInfo.InvariantCulture));
  1075. return true;
  1076. }
  1077. /// <summary>
  1078. /// Determines if a given object is numeric in any way
  1079. /// (can be integer, double, null, etc).
  1080. /// </summary>
  1081. static bool IsNumeric(object value)
  1082. {
  1083. if (value is sbyte) return true;
  1084. if (value is byte) return true;
  1085. if (value is short) return true;
  1086. if (value is ushort) return true;
  1087. if (value is int) return true;
  1088. if (value is uint) return true;
  1089. if (value is long) return true;
  1090. if (value is ulong) return true;
  1091. if (value is float) return true;
  1092. if (value is double) return true;
  1093. if (value is decimal) return true;
  1094. return false;
  1095. }
  1096. private static IJsonSerializerStrategy _currentJsonSerializerStrategy;
  1097. public static IJsonSerializerStrategy CurrentJsonSerializerStrategy
  1098. {
  1099. get
  1100. {
  1101. return _currentJsonSerializerStrategy ??
  1102. (_currentJsonSerializerStrategy =
  1103. #if SIMPLE_JSON_DATACONTRACT
  1104. DataContractJsonSerializerStrategy
  1105. #else
  1106. //PocoJsonSerializerStrategy
  1107. MorefunJsonSerializerStrategy
  1108. #endif
  1109. );
  1110. }
  1111. set
  1112. {
  1113. _currentJsonSerializerStrategy = value;
  1114. }
  1115. }
  1116. //private static PocoJsonSerializerStrategy _pocoJsonSerializerStrategy;
  1117. //[EditorBrowsable(EditorBrowsableState.Advanced)]
  1118. //public static PocoJsonSerializerStrategy PocoJsonSerializerStrategy
  1119. //{
  1120. // get
  1121. // {
  1122. // return _pocoJsonSerializerStrategy ?? (_pocoJsonSerializerStrategy = new PocoJsonSerializerStrategy());
  1123. // }
  1124. //}
  1125. private static MorefunJsonSerializerStrategy _morefunJsonSerializerStrategy;
  1126. [EditorBrowsable(EditorBrowsableState.Advanced)]
  1127. public static MorefunJsonSerializerStrategy MorefunJsonSerializerStrategy
  1128. {
  1129. get
  1130. {
  1131. return _morefunJsonSerializerStrategy ?? (_morefunJsonSerializerStrategy = new MorefunJsonSerializerStrategy());
  1132. }
  1133. }
  1134. #if SIMPLE_JSON_DATACONTRACT
  1135. private static DataContractJsonSerializerStrategy _dataContractJsonSerializerStrategy;
  1136. [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
  1137. public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrategy
  1138. {
  1139. get
  1140. {
  1141. return _dataContractJsonSerializerStrategy ?? (_dataContractJsonSerializerStrategy = new DataContractJsonSerializerStrategy());
  1142. }
  1143. }
  1144. #endif
  1145. }
  1146. // [GeneratedCode("simple-json", "1.0.0")]
  1147. #if SIMPLE_JSON_INTERNAL
  1148. internal
  1149. #else
  1150. public
  1151. #endif
  1152. interface IJsonSerializerStrategy
  1153. {
  1154. [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")]
  1155. bool TrySerializeNonPrimitiveObject(object input, out object output);
  1156. object DeserializeObject(object value, Type type);
  1157. }
  1158. public class MorefunJsonSerializerStrategy : IJsonSerializerStrategy
  1159. {
  1160. private static readonly string[] Iso8601Format = new string[]
  1161. {
  1162. @"yyyy-MM-dd\THH:mm:ss.FFFFFFF\Z",
  1163. @"yyyy-MM-dd\THH:mm:ss\Z",
  1164. @"yyyy-MM-dd\THH:mm:ssK"
  1165. };
  1166. protected virtual object SerializeEnum(Enum p)
  1167. {
  1168. return Convert.ToDouble(p, CultureInfo.InvariantCulture);
  1169. }
  1170. protected virtual string MapClrMemberNameToJsonFieldName(string clrPropertyName)
  1171. {
  1172. return clrPropertyName;
  1173. }
  1174. protected virtual bool TrySerializeUnknownTypes(object input, out object output)
  1175. {
  1176. if (input == null) throw new ArgumentNullException("input");
  1177. output = null;
  1178. Type type = input.GetType();
  1179. if (type.FullName == null)
  1180. return false;
  1181. IDictionary<string, object> obj = new JsonObject();
  1182. foreach (PropertyInfo info in type.GetProperties())
  1183. {
  1184. obj.Add(MapClrMemberNameToJsonFieldName(info.Name), info.GetGetMethod().Invoke(input, null));
  1185. // obj.Add(MapClrMemberNameToJsonFieldName(info.Name), info.GetValue(input,null));
  1186. }
  1187. output = obj;
  1188. return true;
  1189. }
  1190. protected virtual bool TrySerializeKnownTypes(object input, out object output)
  1191. {
  1192. bool returnValue = true;
  1193. if (input is DateTime)
  1194. output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);
  1195. else if (input is DateTimeOffset)
  1196. output = ((DateTimeOffset)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);
  1197. else if (input is Guid)
  1198. output = ((Guid)input).ToString("D");
  1199. else if (input is Uri)
  1200. output = input.ToString();
  1201. else
  1202. {
  1203. Enum inputEnum = input as Enum;
  1204. if (inputEnum != null)
  1205. output = SerializeEnum(inputEnum);
  1206. else
  1207. {
  1208. returnValue = false;
  1209. output = null;
  1210. }
  1211. }
  1212. return returnValue;
  1213. }
  1214. public bool TrySerializeNonPrimitiveObject(object input, out object output)
  1215. {
  1216. return TrySerializeKnownTypes(input, out output) || TrySerializeUnknownTypes(input, out output);
  1217. }
  1218. public object DeserializeObject(object value, Type type)
  1219. {
  1220. return "";
  1221. }
  1222. }
  1223. // [GeneratedCode("simple-json", "1.0.0")]
  1224. //#if SIMPLE_JSON_INTERNAL
  1225. // internal
  1226. //#else
  1227. // public
  1228. //#endif
  1229. // class PocoJsonSerializerStrategy : IJsonSerializerStrategy
  1230. // {
  1231. // internal IDictionary<Type, ReflectionUtils.ConstructorDelegate> ConstructorCache;
  1232. // internal IDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>> GetCache;
  1233. // internal IDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>> SetCache;
  1234. // internal static readonly Type[] EmptyTypes = new Type[0];
  1235. // internal static readonly Type[] ArrayConstructorParameterTypes = new Type[] { typeof(int) };
  1236. // private static readonly string[] Iso8601Format = new string[]
  1237. // {
  1238. // @"yyyy-MM-dd\THH:mm:ss.FFFFFFF\Z",
  1239. // @"yyyy-MM-dd\THH:mm:ss\Z",
  1240. // @"yyyy-MM-dd\THH:mm:ssK"
  1241. // };
  1242. // public PocoJsonSerializerStrategy()
  1243. // {
  1244. // ConstructorCache = new ReflectionUtils.ThreadSafeDictionary<Type, ReflectionUtils.ConstructorDelegate>(ContructorDelegateFactory);
  1245. // GetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>>(GetterValueFactory);
  1246. // SetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>>(SetterValueFactory);
  1247. // }
  1248. // protected virtual string MapClrMemberNameToJsonFieldName(string clrPropertyName)
  1249. // {
  1250. // return clrPropertyName;
  1251. // }
  1252. // internal virtual ReflectionUtils.ConstructorDelegate ContructorDelegateFactory(Type key)
  1253. // {
  1254. // return ReflectionUtils.GetContructor(key, key.IsArray ? ArrayConstructorParameterTypes : EmptyTypes);
  1255. // }
  1256. // internal virtual IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)
  1257. // {
  1258. // IDictionary<string, ReflectionUtils.GetDelegate> result = new Dictionary<string, ReflectionUtils.GetDelegate>();
  1259. // foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))
  1260. // {
  1261. // if (propertyInfo.CanRead)
  1262. // {
  1263. // MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo);
  1264. // if (getMethod.IsStatic || !getMethod.IsPublic)
  1265. // continue;
  1266. // result[MapClrMemberNameToJsonFieldName(propertyInfo.Name)] = ReflectionUtils.GetGetMethod(propertyInfo);
  1267. // }
  1268. // }
  1269. // foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))
  1270. // {
  1271. // if (fieldInfo.IsStatic || !fieldInfo.IsPublic)
  1272. // continue;
  1273. // result[MapClrMemberNameToJsonFieldName(fieldInfo.Name)] = ReflectionUtils.GetGetMethod(fieldInfo);
  1274. // }
  1275. // return result;
  1276. // }
  1277. // internal virtual IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type)
  1278. // {
  1279. // IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> result = new Dictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>();
  1280. // foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))
  1281. // {
  1282. // if (propertyInfo.CanWrite)
  1283. // {
  1284. // MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo);
  1285. // if (setMethod.IsStatic || !setMethod.IsPublic)
  1286. // continue;
  1287. // result[MapClrMemberNameToJsonFieldName(propertyInfo.Name)] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo));
  1288. // }
  1289. // }
  1290. // foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))
  1291. // {
  1292. // if (fieldInfo.IsInitOnly || fieldInfo.IsStatic || !fieldInfo.IsPublic)
  1293. // continue;
  1294. // result[MapClrMemberNameToJsonFieldName(fieldInfo.Name)] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo));
  1295. // }
  1296. // return result;
  1297. // }
  1298. // public virtual bool TrySerializeNonPrimitiveObject(object input, out object output)
  1299. // {
  1300. // return TrySerializeKnownTypes(input, out output) || TrySerializeUnknownTypes(input, out output);
  1301. // }
  1302. // [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
  1303. // public virtual object DeserializeObject(object value, Type type)
  1304. // {
  1305. // if (type == null) throw new ArgumentNullException("type");
  1306. // string str = value as string;
  1307. // if (type == typeof (Guid) && string.IsNullOrEmpty(str))
  1308. // return default(Guid);
  1309. // if (value == null)
  1310. // return null;
  1311. // object obj = null;
  1312. // if (str != null)
  1313. // {
  1314. // if (str.Length != 0) // We know it can't be null now.
  1315. // {
  1316. // if (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime)))
  1317. // return DateTime.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
  1318. // if (type == typeof(DateTimeOffset) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTimeOffset)))
  1319. // return DateTimeOffset.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
  1320. // if (type == typeof(Guid) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid)))
  1321. // return new Guid(str);
  1322. // if (type == typeof(Uri))
  1323. // {
  1324. // bool isValid = Uri.IsWellFormedUriString(str, UriKind.RelativeOrAbsolute);
  1325. // Uri result;
  1326. // if (isValid && Uri.TryCreate(str, UriKind.RelativeOrAbsolute, out result))
  1327. // return result;
  1328. // return null;
  1329. // }
  1330. // if (type == typeof(string))
  1331. // return str;
  1332. // return Convert.ChangeType(str, type, CultureInfo.InvariantCulture);
  1333. // }
  1334. // else
  1335. // {
  1336. // if (type == typeof(Guid))
  1337. // obj = default(Guid);
  1338. // else if (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))
  1339. // obj = null;
  1340. // else
  1341. // obj = str;
  1342. // }
  1343. // // Empty string case
  1344. // if (!ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))
  1345. // return str;
  1346. // }
  1347. // else if (value is bool)
  1348. // return value;
  1349. // bool valueIsLong = value is long;
  1350. // bool valueIsDouble = value is double;
  1351. // if ((valueIsLong && type == typeof(long)) || (valueIsDouble && type == typeof(double)))
  1352. // return value;
  1353. // if ((valueIsDouble && type != typeof(double)) || (valueIsLong && type != typeof(long)))
  1354. // {
  1355. // obj = type == typeof(int) || type == typeof(long) || type == typeof(double) || type == typeof(float) || type == typeof(bool) || type == typeof(decimal) || type == typeof(byte) || type == typeof(short)
  1356. // ? Convert.ChangeType(value, type, CultureInfo.InvariantCulture)
  1357. // : value;
  1358. // }
  1359. // else
  1360. // {
  1361. // IDictionary<string, object> objects = value as IDictionary<string, object>;
  1362. // if (objects != null)
  1363. // {
  1364. // IDictionary<string, object> jsonObject = objects;
  1365. // if (ReflectionUtils.IsTypeDictionary(type))
  1366. // {
  1367. // // if dictionary then
  1368. // Type[] types = ReflectionUtils.GetGenericTypeArguments(type);
  1369. // Type keyType = types[0];
  1370. // Type valueType = types[1];
  1371. // Type genericType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
  1372. // IDictionary dict = (IDictionary)ConstructorCache[genericType]();
  1373. // foreach (KeyValuePair<string, object> kvp in jsonObject)
  1374. // dict.Add(kvp.Key, DeserializeObject(kvp.Value, valueType));
  1375. // obj = dict;
  1376. // }
  1377. // else
  1378. // {
  1379. // if (type == typeof(object))
  1380. // obj = value;
  1381. // else
  1382. // {
  1383. // obj = ConstructorCache[type]();
  1384. // foreach (KeyValuePair<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> setter in SetCache[type])
  1385. // {
  1386. // object jsonValue;
  1387. // if (jsonObject.TryGetValue(setter.Key, out jsonValue))
  1388. // {
  1389. // jsonValue = DeserializeObject(jsonValue, setter.Value.Key);
  1390. // setter.Value.Value(obj, jsonValue);
  1391. // }
  1392. // }
  1393. // }
  1394. // }
  1395. // }
  1396. // else
  1397. // {
  1398. // IList<object> valueAsList = value as IList<object>;
  1399. // if (valueAsList != null)
  1400. // {
  1401. // IList<object> jsonObject = valueAsList;
  1402. // IList list = null;
  1403. // if (type.IsArray)
  1404. // {
  1405. // list = (IList)ConstructorCache[type](jsonObject.Count);
  1406. // int i = 0;
  1407. // foreach (object o in jsonObject)
  1408. // list[i++] = DeserializeObject(o, type.GetElementType());
  1409. // }
  1410. // else if (ReflectionUtils.IsTypeGenericeCollectionInterface(type) || ReflectionUtils.IsAssignableFrom(typeof(IList), type))
  1411. // {
  1412. // Type innerType = ReflectionUtils.GetGenericListElementType(type);
  1413. // list = (IList)(ConstructorCache[type] ?? ConstructorCache[typeof(List<>).MakeGenericType(innerType)])(jsonObject.Count);
  1414. // foreach (object o in jsonObject)
  1415. // list.Add(DeserializeObject(o, innerType));
  1416. // }
  1417. // obj = list;
  1418. // }
  1419. // }
  1420. // return obj;
  1421. // }
  1422. // if (ReflectionUtils.IsNullableType(type))
  1423. // return ReflectionUtils.ToNullableType(obj, type);
  1424. // return obj;
  1425. // }
  1426. // protected virtual object SerializeEnum(Enum p)
  1427. // {
  1428. // return Convert.ToDouble(p, CultureInfo.InvariantCulture);
  1429. // }
  1430. // [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")]
  1431. // protected virtual bool TrySerializeKnownTypes(object input, out object output)
  1432. // {
  1433. // bool returnValue = true;
  1434. // if (input is DateTime)
  1435. // output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);
  1436. // else if (input is DateTimeOffset)
  1437. // output = ((DateTimeOffset)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);
  1438. // else if (input is Guid)
  1439. // output = ((Guid)input).ToString("D");
  1440. // else if (input is Uri)
  1441. // output = input.ToString();
  1442. // else
  1443. // {
  1444. // Enum inputEnum = input as Enum;
  1445. // if (inputEnum != null)
  1446. // output = SerializeEnum(inputEnum);
  1447. // else
  1448. // {
  1449. // returnValue = false;
  1450. // output = null;
  1451. // }
  1452. // }
  1453. // return returnValue;
  1454. // }
  1455. // [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")]
  1456. // protected virtual bool TrySerializeUnknownTypes(object input, out object output)
  1457. // {
  1458. // if (input == null) throw new ArgumentNullException("input");
  1459. // output = null;
  1460. // Type type = input.GetType();
  1461. // if (type.FullName == null)
  1462. // return false;
  1463. // IDictionary<string, object> obj = new JsonObject();
  1464. // IDictionary<string, ReflectionUtils.GetDelegate> getters = GetCache[type];
  1465. // foreach (KeyValuePair<string, ReflectionUtils.GetDelegate> getter in getters)
  1466. // {
  1467. // if (getter.Value != null)
  1468. // obj.Add(MapClrMemberNameToJsonFieldName(getter.Key), getter.Value(input));
  1469. // }
  1470. // output = obj;
  1471. // return true;
  1472. // }
  1473. // }
  1474. #if SIMPLE_JSON_DATACONTRACT
  1475. [GeneratedCode("simple-json", "1.0.0")]
  1476. #if SIMPLE_JSON_INTERNAL
  1477. internal
  1478. #else
  1479. public
  1480. #endif
  1481. class DataContractJsonSerializerStrategy : PocoJsonSerializerStrategy
  1482. {
  1483. public DataContractJsonSerializerStrategy()
  1484. {
  1485. GetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>>(GetterValueFactory);
  1486. SetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>>(SetterValueFactory);
  1487. }
  1488. internal override IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)
  1489. {
  1490. bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null;
  1491. if (!hasDataContract)
  1492. return base.GetterValueFactory(type);
  1493. string jsonKey;
  1494. IDictionary<string, ReflectionUtils.GetDelegate> result = new Dictionary<string, ReflectionUtils.GetDelegate>();
  1495. foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))
  1496. {
  1497. if (propertyInfo.CanRead)
  1498. {
  1499. MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo);
  1500. if (!getMethod.IsStatic && CanAdd(propertyInfo, out jsonKey))
  1501. result[jsonKey] = ReflectionUtils.GetGetMethod(propertyInfo);
  1502. }
  1503. }
  1504. foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))
  1505. {
  1506. if (!fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey))
  1507. result[jsonKey] = ReflectionUtils.GetGetMethod(fieldInfo);
  1508. }
  1509. return result;
  1510. }
  1511. internal override IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type)
  1512. {
  1513. bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null;
  1514. if (!hasDataContract)
  1515. return base.SetterValueFactory(type);
  1516. string jsonKey;
  1517. IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> result = new Dictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>();
  1518. foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))
  1519. {
  1520. if (propertyInfo.CanWrite)
  1521. {
  1522. MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo);
  1523. if (!setMethod.IsStatic && CanAdd(propertyInfo, out jsonKey))
  1524. result[jsonKey] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo));
  1525. }
  1526. }
  1527. foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))
  1528. {
  1529. if (!fieldInfo.IsInitOnly && !fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey))
  1530. result[jsonKey] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo));
  1531. }
  1532. // todo implement sorting for DATACONTRACT.
  1533. return result;
  1534. }
  1535. private static bool CanAdd(MemberInfo info, out string jsonKey)
  1536. {
  1537. jsonKey = null;
  1538. if (ReflectionUtils.GetAttribute(info, typeof(IgnoreDataMemberAttribute)) != null)
  1539. return false;
  1540. DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)ReflectionUtils.GetAttribute(info, typeof(DataMemberAttribute));
  1541. if (dataMemberAttribute == null)
  1542. return false;
  1543. jsonKey = string.IsNullOrEmpty(dataMemberAttribute.Name) ? info.Name : dataMemberAttribute.Name;
  1544. return true;
  1545. }
  1546. }
  1547. #endif
  1548. // namespace Reflection
  1549. // {
  1550. // // This class is meant to be copied into other libraries. So we want to exclude it from Code Analysis rules
  1551. // // that might be in place in the target project.
  1552. // // [GeneratedCode("reflection-utils", "1.0.0")]
  1553. //#if SIMPLE_JSON_REFLECTION_UTILS_PUBLIC
  1554. // public
  1555. //#else
  1556. // internal
  1557. //#endif
  1558. // class ReflectionUtils
  1559. // {
  1560. // private static readonly object[] EmptyObjects = new object[] { };
  1561. // public delegate object GetDelegate(object source);
  1562. // public delegate void SetDelegate(object source, object value);
  1563. // public delegate object ConstructorDelegate(params object[] args);
  1564. // public delegate TValue ThreadSafeDictionaryValueFactory<TKey, TValue>(TKey key);
  1565. //#if SIMPLE_JSON_TYPEINFO
  1566. // public static TypeInfo GetTypeInfo(Type type)
  1567. // {
  1568. // return type.GetTypeInfo();
  1569. // }
  1570. //#else
  1571. // public static Type GetTypeInfo(Type type)
  1572. // {
  1573. // return type;
  1574. // }
  1575. //#endif
  1576. // public static Attribute GetAttribute(MemberInfo info, Type type)
  1577. // {
  1578. //#if SIMPLE_JSON_TYPEINFO
  1579. // if (info == null || type == null || !info.IsDefined(type))
  1580. // return null;
  1581. // return info.GetCustomAttribute(type);
  1582. //#else
  1583. // if (info == null || type == null || !Attribute.IsDefined(info, type))
  1584. // return null;
  1585. // return Attribute.GetCustomAttribute(info, type);
  1586. //#endif
  1587. // }
  1588. // public static Type GetGenericListElementType(Type type)
  1589. // {
  1590. // IEnumerable<Type> interfaces;
  1591. //#if SIMPLE_JSON_TYPEINFO
  1592. // interfaces = type.GetTypeInfo().ImplementedInterfaces;
  1593. //#else
  1594. // interfaces = type.GetInterfaces();
  1595. //#endif
  1596. // foreach (Type implementedInterface in interfaces)
  1597. // {
  1598. // if (IsTypeGeneric(implementedInterface) &&
  1599. // implementedInterface.GetGenericTypeDefinition() == typeof (IList<>))
  1600. // {
  1601. // return GetGenericTypeArguments(implementedInterface)[0];
  1602. // }
  1603. // }
  1604. // return GetGenericTypeArguments(type)[0];
  1605. // }
  1606. // public static Attribute GetAttribute(Type objectType, Type attributeType)
  1607. // {
  1608. //#if SIMPLE_JSON_TYPEINFO
  1609. // if (objectType == null || attributeType == null || !objectType.GetTypeInfo().IsDefined(attributeType))
  1610. // return null;
  1611. // return objectType.GetTypeInfo().GetCustomAttribute(attributeType);
  1612. //#else
  1613. // if (objectType == null || attributeType == null || !Attribute.IsDefined(objectType, attributeType))
  1614. // return null;
  1615. // return Attribute.GetCustomAttribute(objectType, attributeType);
  1616. //#endif
  1617. // }
  1618. // public static Type[] GetGenericTypeArguments(Type type)
  1619. // {
  1620. //#if SIMPLE_JSON_TYPEINFO
  1621. // return type.GetTypeInfo().GenericTypeArguments;
  1622. //#else
  1623. // return type.GetGenericArguments();
  1624. //#endif
  1625. // }
  1626. // public static bool IsTypeGeneric(Type type)
  1627. // {
  1628. // return GetTypeInfo(type).IsGenericType;
  1629. // }
  1630. // public static bool IsTypeGenericeCollectionInterface(Type type)
  1631. // {
  1632. // if (!IsTypeGeneric(type))
  1633. // return false;
  1634. // Type genericDefinition = type.GetGenericTypeDefinition();
  1635. // return (genericDefinition == typeof(IList<>)
  1636. // || genericDefinition == typeof(ICollection<>)
  1637. // || genericDefinition == typeof(IEnumerable<>)
  1638. //#if SIMPLE_JSON_READONLY_COLLECTIONS
  1639. // || genericDefinition == typeof(IReadOnlyCollection<>)
  1640. // || genericDefinition == typeof(IReadOnlyList<>)
  1641. //#endif
  1642. // );
  1643. // }
  1644. // public static bool IsAssignableFrom(Type type1, Type type2)
  1645. // {
  1646. // return GetTypeInfo(type1).IsAssignableFrom(GetTypeInfo(type2));
  1647. // }
  1648. // public static bool IsTypeDictionary(Type type)
  1649. // {
  1650. //#if SIMPLE_JSON_TYPEINFO
  1651. // if (typeof(IDictionary<,>).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
  1652. // return true;
  1653. //#else
  1654. // if (typeof(System.Collections.IDictionary).IsAssignableFrom(type))
  1655. // return true;
  1656. //#endif
  1657. // if (!GetTypeInfo(type).IsGenericType)
  1658. // return false;
  1659. // Type genericDefinition = type.GetGenericTypeDefinition();
  1660. // return genericDefinition == typeof(IDictionary<,>);
  1661. // }
  1662. // public static bool IsNullableType(Type type)
  1663. // {
  1664. // return GetTypeInfo(type).IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
  1665. // }
  1666. // public static object ToNullableType(object obj, Type nullableType)
  1667. // {
  1668. // return obj == null ? null : Convert.ChangeType(obj, Nullable.GetUnderlyingType(nullableType), CultureInfo.InvariantCulture);
  1669. // }
  1670. // public static bool IsValueType(Type type)
  1671. // {
  1672. // return GetTypeInfo(type).IsValueType;
  1673. // }
  1674. // public static IEnumerable<ConstructorInfo> GetConstructors(Type type)
  1675. // {
  1676. //#if SIMPLE_JSON_TYPEINFO
  1677. // return type.GetTypeInfo().DeclaredConstructors;
  1678. //#else
  1679. // return type.GetConstructors();
  1680. //#endif
  1681. // }
  1682. // public static ConstructorInfo GetConstructorInfo(Type type, params Type[] argsType)
  1683. // {
  1684. // IEnumerable<ConstructorInfo> constructorInfos = GetConstructors(type);
  1685. // int i;
  1686. // bool matches;
  1687. // foreach (ConstructorInfo constructorInfo in constructorInfos)
  1688. // {
  1689. // ParameterInfo[] parameters = constructorInfo.GetParameters();
  1690. // if (argsType.Length != parameters.Length)
  1691. // continue;
  1692. // i = 0;
  1693. // matches = true;
  1694. // foreach (ParameterInfo parameterInfo in constructorInfo.GetParameters())
  1695. // {
  1696. // if (parameterInfo.ParameterType != argsType[i])
  1697. // {
  1698. // matches = false;
  1699. // break;
  1700. // }
  1701. // }
  1702. // if (matches)
  1703. // return constructorInfo;
  1704. // }
  1705. // return null;
  1706. // }
  1707. // public static IEnumerable<PropertyInfo> GetProperties(Type type)
  1708. // {
  1709. //#if SIMPLE_JSON_TYPEINFO
  1710. // return type.GetRuntimeProperties();
  1711. //#else
  1712. // return type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
  1713. //#endif
  1714. // }
  1715. // public static IEnumerable<FieldInfo> GetFields(Type type)
  1716. // {
  1717. //#if SIMPLE_JSON_TYPEINFO
  1718. // return type.GetRuntimeFields();
  1719. //#else
  1720. // return type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
  1721. //#endif
  1722. // }
  1723. // public static MethodInfo GetGetterMethodInfo(PropertyInfo propertyInfo)
  1724. // {
  1725. //#if SIMPLE_JSON_TYPEINFO
  1726. // return propertyInfo.GetMethod;
  1727. //#else
  1728. // return propertyInfo.GetGetMethod(true);
  1729. //#endif
  1730. // }
  1731. // public static MethodInfo GetSetterMethodInfo(PropertyInfo propertyInfo)
  1732. // {
  1733. //#if SIMPLE_JSON_TYPEINFO
  1734. // return propertyInfo.SetMethod;
  1735. //#else
  1736. // return propertyInfo.GetSetMethod(true);
  1737. //#endif
  1738. // }
  1739. // public static ConstructorDelegate GetContructor(ConstructorInfo constructorInfo)
  1740. // {
  1741. //#if SIMPLE_JSON_NO_LINQ_EXPRESSION
  1742. // return GetConstructorByReflection(constructorInfo);
  1743. //#else
  1744. // return GetConstructorByExpression(constructorInfo);
  1745. //#endif
  1746. // }
  1747. // public static ConstructorDelegate GetContructor(Type type, params Type[] argsType)
  1748. // {
  1749. //#if SIMPLE_JSON_NO_LINQ_EXPRESSION
  1750. // return GetConstructorByReflection(type, argsType);
  1751. //#else
  1752. // return GetConstructorByExpression(type, argsType);
  1753. //#endif
  1754. // }
  1755. // public static ConstructorDelegate GetConstructorByReflection(ConstructorInfo constructorInfo)
  1756. // {
  1757. // return delegate(object[] args) { return constructorInfo.Invoke(args); };
  1758. // }
  1759. // public static ConstructorDelegate GetConstructorByReflection(Type type, params Type[] argsType)
  1760. // {
  1761. // ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType);
  1762. // return constructorInfo == null ? null : GetConstructorByReflection(constructorInfo);
  1763. // }
  1764. //#if !SIMPLE_JSON_NO_LINQ_EXPRESSION
  1765. // public static ConstructorDelegate GetConstructorByExpression(ConstructorInfo constructorInfo)
  1766. // {
  1767. // ParameterInfo[] paramsInfo = constructorInfo.GetParameters();
  1768. // ParameterExpression param = Expression.Parameter(typeof(object[]), "args");
  1769. // Expression[] argsExp = new Expression[paramsInfo.Length];
  1770. // for (int i = 0; i < paramsInfo.Length; i++)
  1771. // {
  1772. // Expression index = Expression.Constant(i);
  1773. // Type paramType = paramsInfo[i].ParameterType;
  1774. // Expression paramAccessorExp = Expression.ArrayIndex(param, index);
  1775. // Expression paramCastExp = Expression.Convert(paramAccessorExp, paramType);
  1776. // argsExp[i] = paramCastExp;
  1777. // }
  1778. // NewExpression newExp = Expression.New(constructorInfo, argsExp);
  1779. // Expression<Func<object[], object>> lambda = Expression.Lambda<Func<object[], object>>(newExp, param);
  1780. // Func<object[], object> compiledLambda = lambda.Compile();
  1781. // return delegate(object[] args) { return compiledLambda(args); };
  1782. // }
  1783. // public static ConstructorDelegate GetConstructorByExpression(Type type, params Type[] argsType)
  1784. // {
  1785. // ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType);
  1786. // return constructorInfo == null ? null : GetConstructorByExpression(constructorInfo);
  1787. // }
  1788. //#endif
  1789. // public static GetDelegate GetGetMethod(PropertyInfo propertyInfo)
  1790. // {
  1791. //#if SIMPLE_JSON_NO_LINQ_EXPRESSION
  1792. // return GetGetMethodByReflection(propertyInfo);
  1793. //#else
  1794. // return GetGetMethodByExpression(propertyInfo);
  1795. //#endif
  1796. // }
  1797. // public static GetDelegate GetGetMethod(FieldInfo fieldInfo)
  1798. // {
  1799. //#if SIMPLE_JSON_NO_LINQ_EXPRESSION
  1800. // return GetGetMethodByReflection(fieldInfo);
  1801. //#else
  1802. // return GetGetMethodByExpression(fieldInfo);
  1803. //#endif
  1804. // }
  1805. // public static GetDelegate GetGetMethodByReflection(PropertyInfo propertyInfo)
  1806. // {
  1807. // MethodInfo methodInfo = GetGetterMethodInfo(propertyInfo);
  1808. // return delegate(object source) { return methodInfo.Invoke(source, EmptyObjects); };
  1809. // }
  1810. // public static GetDelegate GetGetMethodByReflection(FieldInfo fieldInfo)
  1811. // {
  1812. // return delegate(object source) { return fieldInfo.GetValue(source); };
  1813. // }
  1814. //#if !SIMPLE_JSON_NO_LINQ_EXPRESSION
  1815. // public static GetDelegate GetGetMethodByExpression(PropertyInfo propertyInfo)
  1816. // {
  1817. // MethodInfo getMethodInfo = GetGetterMethodInfo(propertyInfo);
  1818. // ParameterExpression instance = Expression.Parameter(typeof(object), "instance");
  1819. // UnaryExpression instanceCast = (!IsValueType(propertyInfo.DeclaringType)) ? Expression.TypeAs(instance, propertyInfo.DeclaringType) : Expression.Convert(instance, propertyInfo.DeclaringType);
  1820. // Func<object, object> compiled = Expression.Lambda<Func<object, object>>(Expression.TypeAs(Expression.Call(instanceCast, getMethodInfo), typeof(object)), instance).Compile();
  1821. // return delegate(object source) { return compiled(source); };
  1822. // }
  1823. // public static GetDelegate GetGetMethodByExpression(FieldInfo fieldInfo)
  1824. // {
  1825. // ParameterExpression instance = Expression.Parameter(typeof(object), "instance");
  1826. // MemberExpression member = Expression.Field(Expression.Convert(instance, fieldInfo.DeclaringType), fieldInfo);
  1827. // GetDelegate compiled = Expression.Lambda<GetDelegate>(Expression.Convert(member, typeof(object)), instance).Compile();
  1828. // return delegate(object source) { return compiled(source); };
  1829. // }
  1830. //#endif
  1831. // public static SetDelegate GetSetMethod(PropertyInfo propertyInfo)
  1832. // {
  1833. //#if SIMPLE_JSON_NO_LINQ_EXPRESSION
  1834. // return GetSetMethodByReflection(propertyInfo);
  1835. //#else
  1836. // return GetSetMethodByExpression(propertyInfo);
  1837. //#endif
  1838. // }
  1839. // public static SetDelegate GetSetMethod(FieldInfo fieldInfo)
  1840. // {
  1841. //#if SIMPLE_JSON_NO_LINQ_EXPRESSION
  1842. // return GetSetMethodByReflection(fieldInfo);
  1843. //#else
  1844. // return GetSetMethodByExpression(fieldInfo);
  1845. //#endif
  1846. // }
  1847. // public static SetDelegate GetSetMethodByReflection(PropertyInfo propertyInfo)
  1848. // {
  1849. // MethodInfo methodInfo = GetSetterMethodInfo(propertyInfo);
  1850. // return delegate(object source, object value) { methodInfo.Invoke(source, new object[] { value }); };
  1851. // }
  1852. // public static SetDelegate GetSetMethodByReflection(FieldInfo fieldInfo)
  1853. // {
  1854. // return delegate(object source, object value) { fieldInfo.SetValue(source, value); };
  1855. // }
  1856. //#if !SIMPLE_JSON_NO_LINQ_EXPRESSION
  1857. // public static SetDelegate GetSetMethodByExpression(PropertyInfo propertyInfo)
  1858. // {
  1859. // MethodInfo setMethodInfo = GetSetterMethodInfo(propertyInfo);
  1860. // ParameterExpression instance = Expression.Parameter(typeof(object), "instance");
  1861. // ParameterExpression value = Expression.Parameter(typeof(object), "value");
  1862. // UnaryExpression instanceCast = (!IsValueType(propertyInfo.DeclaringType)) ? Expression.TypeAs(instance, propertyInfo.DeclaringType) : Expression.Convert(instance, propertyInfo.DeclaringType);
  1863. // UnaryExpression valueCast = (!IsValueType(propertyInfo.PropertyType)) ? Expression.TypeAs(value, propertyInfo.PropertyType) : Expression.Convert(value, propertyInfo.PropertyType);
  1864. // Action<object, object> compiled = Expression.Lambda<Action<object, object>>(Expression.Call(instanceCast, setMethodInfo, valueCast), new ParameterExpression[] { instance, value }).Compile();
  1865. // return delegate(object source, object val) { compiled(source, val); };
  1866. // }
  1867. // public static SetDelegate GetSetMethodByExpression(FieldInfo fieldInfo)
  1868. // {
  1869. // ParameterExpression instance = Expression.Parameter(typeof(object), "instance");
  1870. // ParameterExpression value = Expression.Parameter(typeof(object), "value");
  1871. // Action<object, object> compiled = Expression.Lambda<Action<object, object>>(
  1872. // Assign(Expression.Field(Expression.Convert(instance, fieldInfo.DeclaringType), fieldInfo), Expression.Convert(value, fieldInfo.FieldType)), instance, value).Compile();
  1873. // return delegate(object source, object val) { compiled(source, val); };
  1874. // }
  1875. // public static BinaryExpression Assign(Expression left, Expression right)
  1876. // {
  1877. //#if SIMPLE_JSON_TYPEINFO
  1878. // return Expression.Assign(left, right);
  1879. //#else
  1880. // MethodInfo assign = typeof(Assigner<>).MakeGenericType(left.Type).GetMethod("Assign");
  1881. // BinaryExpression assignExpr = Expression.Add(left, right, assign);
  1882. // return assignExpr;
  1883. //#endif
  1884. // }
  1885. // private static class Assigner<T>
  1886. // {
  1887. // public static T Assign(ref T left, T right)
  1888. // {
  1889. // return (left = right);
  1890. // }
  1891. // }
  1892. //#endif
  1893. // public sealed class ThreadSafeDictionary<TKey, TValue> : IDictionary<TKey, TValue>
  1894. // {
  1895. // private readonly object _lock = new object();
  1896. // private readonly ThreadSafeDictionaryValueFactory<TKey, TValue> _valueFactory;
  1897. // private Dictionary<TKey, TValue> _dictionary;
  1898. // public ThreadSafeDictionary(ThreadSafeDictionaryValueFactory<TKey, TValue> valueFactory)
  1899. // {
  1900. // _valueFactory = valueFactory;
  1901. // }
  1902. // private TValue Get(TKey key)
  1903. // {
  1904. // if (_dictionary == null)
  1905. // return AddValue(key);
  1906. // TValue value;
  1907. // if (!_dictionary.TryGetValue(key, out value))
  1908. // return AddValue(key);
  1909. // return value;
  1910. // }
  1911. // private TValue AddValue(TKey key)
  1912. // {
  1913. // TValue value = _valueFactory(key);
  1914. // lock (_lock)
  1915. // {
  1916. // if (_dictionary == null)
  1917. // {
  1918. // _dictionary = new Dictionary<TKey, TValue>();
  1919. // _dictionary[key] = value;
  1920. // }
  1921. // else
  1922. // {
  1923. // TValue val;
  1924. // if (_dictionary.TryGetValue(key, out val))
  1925. // return val;
  1926. // Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>(_dictionary);
  1927. // dict[key] = value;
  1928. // _dictionary = dict;
  1929. // }
  1930. // }
  1931. // return value;
  1932. // }
  1933. // public void Add(TKey key, TValue value)
  1934. // {
  1935. // throw new NotImplementedException();
  1936. // }
  1937. // public bool ContainsKey(TKey key)
  1938. // {
  1939. // return _dictionary.ContainsKey(key);
  1940. // }
  1941. // public ICollection<TKey> Keys
  1942. // {
  1943. // get { return _dictionary.Keys; }
  1944. // }
  1945. // public bool Remove(TKey key)
  1946. // {
  1947. // throw new NotImplementedException();
  1948. // }
  1949. // public bool TryGetValue(TKey key, out TValue value)
  1950. // {
  1951. // value = this[key];
  1952. // return true;
  1953. // }
  1954. // public ICollection<TValue> Values
  1955. // {
  1956. // get { return _dictionary.Values; }
  1957. // }
  1958. // public TValue this[TKey key]
  1959. // {
  1960. // get { return Get(key); }
  1961. // set { throw new NotImplementedException(); }
  1962. // }
  1963. // public void Add(KeyValuePair<TKey, TValue> item)
  1964. // {
  1965. // throw new NotImplementedException();
  1966. // }
  1967. // public void Clear()
  1968. // {
  1969. // throw new NotImplementedException();
  1970. // }
  1971. // public bool Contains(KeyValuePair<TKey, TValue> item)
  1972. // {
  1973. // throw new NotImplementedException();
  1974. // }
  1975. // public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
  1976. // {
  1977. // throw new NotImplementedException();
  1978. // }
  1979. // public int Count
  1980. // {
  1981. // get { return _dictionary.Count; }
  1982. // }
  1983. // public bool IsReadOnly
  1984. // {
  1985. // get { throw new NotImplementedException(); }
  1986. // }
  1987. // public bool Remove(KeyValuePair<TKey, TValue> item)
  1988. // {
  1989. // throw new NotImplementedException();
  1990. // }
  1991. // public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
  1992. // {
  1993. // return _dictionary.GetEnumerator();
  1994. // }
  1995. // System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  1996. // {
  1997. // return _dictionary.GetEnumerator();
  1998. // }
  1999. // }
  2000. // }
  2001. // }
  2002. }
  2003. // ReSharper restore LoopCanBeConvertedToQuery
  2004. // ReSharper restore RedundantExplicitArrayCreation
  2005. // ReSharper restore SuggestUseVarKeywordEvident