PageRenderTime 62ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/src/GitHub.Exports/SimpleJson.cs

https://gitlab.com/github-cloud-corporation/VisualStudio
C# | 1264 lines | 949 code | 77 blank | 238 comment | 149 complexity | 1ae3d20c765a60151bcc3b8171fcb557 MD5 | raw file
  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: 0.38.0
  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 GitHub.Reflection;
  58. // ReSharper disable LoopCanBeConvertedToQuery
  59. // ReSharper disable RedundantExplicitArrayCreation
  60. // ReSharper disable SuggestUseVarKeywordEvident
  61. namespace GitHub
  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. return _members.TryGetValue(key, out value);
  195. }
  196. /// <summary>
  197. /// Gets the values.
  198. /// </summary>
  199. /// <value>The values.</value>
  200. public ICollection<object> Values
  201. {
  202. get { return _members.Values; }
  203. }
  204. /// <summary>
  205. /// Gets or sets the <see cref="System.Object"/> with the specified key.
  206. /// </summary>
  207. /// <value></value>
  208. public object this[string key]
  209. {
  210. get { return _members[key]; }
  211. set { _members[key] = value; }
  212. }
  213. /// <summary>
  214. /// Adds the specified item.
  215. /// </summary>
  216. /// <param name="item">The item.</param>
  217. public void Add(KeyValuePair<string, object> item)
  218. {
  219. _members.Add(item.Key, item.Value);
  220. }
  221. /// <summary>
  222. /// Clears this instance.
  223. /// </summary>
  224. public void Clear()
  225. {
  226. _members.Clear();
  227. }
  228. /// <summary>
  229. /// Determines whether [contains] [the specified item].
  230. /// </summary>
  231. /// <param name="item">The item.</param>
  232. /// <returns>
  233. /// <c>true</c> if [contains] [the specified item]; otherwise, <c>false</c>.
  234. /// </returns>
  235. public bool Contains(KeyValuePair<string, object> item)
  236. {
  237. return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value;
  238. }
  239. /// <summary>
  240. /// Copies to.
  241. /// </summary>
  242. /// <param name="array">The array.</param>
  243. /// <param name="arrayIndex">Index of the array.</param>
  244. public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
  245. {
  246. if (array == null) throw new ArgumentNullException("array");
  247. int num = Count;
  248. foreach (KeyValuePair<string, object> kvp in this)
  249. {
  250. array[arrayIndex++] = kvp;
  251. if (--num <= 0)
  252. return;
  253. }
  254. }
  255. /// <summary>
  256. /// Gets the count.
  257. /// </summary>
  258. /// <value>The count.</value>
  259. public int Count
  260. {
  261. get { return _members.Count; }
  262. }
  263. /// <summary>
  264. /// Gets a value indicating whether this instance is read only.
  265. /// </summary>
  266. /// <value>
  267. /// <c>true</c> if this instance is read only; otherwise, <c>false</c>.
  268. /// </value>
  269. public bool IsReadOnly
  270. {
  271. get { return false; }
  272. }
  273. /// <summary>
  274. /// Removes the specified item.
  275. /// </summary>
  276. /// <param name="item">The item.</param>
  277. /// <returns></returns>
  278. public bool Remove(KeyValuePair<string, object> item)
  279. {
  280. return _members.Remove(item.Key);
  281. }
  282. /// <summary>
  283. /// Gets the enumerator.
  284. /// </summary>
  285. /// <returns></returns>
  286. public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
  287. {
  288. return _members.GetEnumerator();
  289. }
  290. /// <summary>
  291. /// Returns an enumerator that iterates through a collection.
  292. /// </summary>
  293. /// <returns>
  294. /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
  295. /// </returns>
  296. IEnumerator IEnumerable.GetEnumerator()
  297. {
  298. return _members.GetEnumerator();
  299. }
  300. /// <summary>
  301. /// Returns a json <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
  302. /// </summary>
  303. /// <returns>
  304. /// A json <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
  305. /// </returns>
  306. public override string ToString()
  307. {
  308. return SimpleJson.SerializeObject(this);
  309. }
  310. #if SIMPLE_JSON_DYNAMIC
  311. /// <summary>
  312. /// 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.
  313. /// </summary>
  314. /// <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>
  315. /// <param name="result">The result of the type conversion operation.</param>
  316. /// <returns>
  317. /// Alwasy returns true.
  318. /// </returns>
  319. public override bool TryConvert(ConvertBinder binder, out object result)
  320. {
  321. // <pex>
  322. if (binder == null)
  323. throw new ArgumentNullException("binder");
  324. // </pex>
  325. Type targetType = binder.Type;
  326. if ((targetType == typeof(IEnumerable)) ||
  327. (targetType == typeof(IEnumerable<KeyValuePair<string, object>>)) ||
  328. (targetType == typeof(IDictionary<string, object>)) ||
  329. (targetType == typeof(IDictionary)))
  330. {
  331. result = this;
  332. return true;
  333. }
  334. return base.TryConvert(binder, out result);
  335. }
  336. /// <summary>
  337. /// Provides the implementation for operations that delete an object member. This method is not intended for use in C# or Visual Basic.
  338. /// </summary>
  339. /// <param name="binder">Provides information about the deletion.</param>
  340. /// <returns>
  341. /// Alwasy returns true.
  342. /// </returns>
  343. public override bool TryDeleteMember(DeleteMemberBinder binder)
  344. {
  345. // <pex>
  346. if (binder == null)
  347. throw new ArgumentNullException("binder");
  348. // </pex>
  349. return _members.Remove(binder.Name);
  350. }
  351. /// <summary>
  352. /// 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.
  353. /// </summary>
  354. /// <param name="binder">Provides information about the operation.</param>
  355. /// <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>
  356. /// <param name="result">The result of the index operation.</param>
  357. /// <returns>
  358. /// Alwasy returns true.
  359. /// </returns>
  360. public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
  361. {
  362. if (indexes == null) throw new ArgumentNullException("indexes");
  363. if (indexes.Length == 1)
  364. {
  365. result = ((IDictionary<string, object>)this)[(string)indexes[0]];
  366. return true;
  367. }
  368. result = null;
  369. return true;
  370. }
  371. /// <summary>
  372. /// 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.
  373. /// </summary>
  374. /// <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>
  375. /// <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>
  376. /// <returns>
  377. /// Alwasy returns true.
  378. /// </returns>
  379. public override bool TryGetMember(GetMemberBinder binder, out object result)
  380. {
  381. object value;
  382. if (_members.TryGetValue(binder.Name, out value))
  383. {
  384. result = value;
  385. return true;
  386. }
  387. result = null;
  388. return true;
  389. }
  390. /// <summary>
  391. /// 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.
  392. /// </summary>
  393. /// <param name="binder">Provides information about the operation.</param>
  394. /// <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>
  395. /// <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>
  396. /// <returns>
  397. /// 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.
  398. /// </returns>
  399. public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
  400. {
  401. if (indexes == null) throw new ArgumentNullException("indexes");
  402. if (indexes.Length == 1)
  403. {
  404. ((IDictionary<string, object>)this)[(string)indexes[0]] = value;
  405. return true;
  406. }
  407. return base.TrySetIndex(binder, indexes, value);
  408. }
  409. /// <summary>
  410. /// 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.
  411. /// </summary>
  412. /// <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>
  413. /// <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>
  414. /// <returns>
  415. /// 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.)
  416. /// </returns>
  417. public override bool TrySetMember(SetMemberBinder binder, object value)
  418. {
  419. // <pex>
  420. if (binder == null)
  421. throw new ArgumentNullException("binder");
  422. // </pex>
  423. _members[binder.Name] = value;
  424. return true;
  425. }
  426. /// <summary>
  427. /// Returns the enumeration of all dynamic member names.
  428. /// </summary>
  429. /// <returns>
  430. /// A sequence that contains dynamic member names.
  431. /// </returns>
  432. public override IEnumerable<string> GetDynamicMemberNames()
  433. {
  434. foreach (var key in Keys)
  435. yield return key;
  436. }
  437. #endif
  438. }
  439. }
  440. namespace GitHub
  441. {
  442. /// <summary>
  443. /// This class encodes and decodes JSON strings.
  444. /// Spec. details, see http://www.json.org/
  445. ///
  446. /// JSON uses Arrays and Objects. These correspond here to the datatypes JsonArray(IList&lt;object>) and JsonObject(IDictionary&lt;string,object>).
  447. /// All numbers are parsed to doubles.
  448. /// </summary>
  449. [GeneratedCode("simple-json", "1.0.0")]
  450. #if SIMPLE_JSON_INTERNAL
  451. internal
  452. #else
  453. public
  454. #endif
  455. static class SimpleJson
  456. {
  457. private const int TOKEN_NONE = 0;
  458. private const int TOKEN_CURLY_OPEN = 1;
  459. private const int TOKEN_CURLY_CLOSE = 2;
  460. private const int TOKEN_SQUARED_OPEN = 3;
  461. private const int TOKEN_SQUARED_CLOSE = 4;
  462. private const int TOKEN_COLON = 5;
  463. private const int TOKEN_COMMA = 6;
  464. private const int TOKEN_STRING = 7;
  465. private const int TOKEN_NUMBER = 8;
  466. private const int TOKEN_TRUE = 9;
  467. private const int TOKEN_FALSE = 10;
  468. private const int TOKEN_NULL = 11;
  469. private const int BUILDER_CAPACITY = 2000;
  470. private static readonly char[] EscapeTable;
  471. private static readonly char[] EscapeCharacters = new char[] { '"', '\\', '\b', '\f', '\n', '\r', '\t' };
  472. private static readonly string EscapeCharactersString = new string(EscapeCharacters);
  473. static SimpleJson()
  474. {
  475. EscapeTable = new char[93];
  476. EscapeTable['"'] = '"';
  477. EscapeTable['\\'] = '\\';
  478. EscapeTable['\b'] = 'b';
  479. EscapeTable['\f'] = 'f';
  480. EscapeTable['\n'] = 'n';
  481. EscapeTable['\r'] = 'r';
  482. EscapeTable['\t'] = 't';
  483. }
  484. /// <summary>
  485. /// Parses the string json into a value
  486. /// </summary>
  487. /// <param name="json">A JSON string.</param>
  488. /// <returns>An IList&lt;object>, a IDictionary&lt;string,object>, a double, a string, null, true, or false</returns>
  489. public static object DeserializeObject(string json)
  490. {
  491. object obj;
  492. if (TryDeserializeObject(json, out obj))
  493. return obj;
  494. throw new SerializationException("Invalid JSON string");
  495. }
  496. /// <summary>
  497. /// Try parsing the json string into a value.
  498. /// </summary>
  499. /// <param name="json">
  500. /// A JSON string.
  501. /// </param>
  502. /// <param name="obj">
  503. /// The object.
  504. /// </param>
  505. /// <returns>
  506. /// Returns true if successfull otherwise false.
  507. /// </returns>
  508. [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")]
  509. public static bool TryDeserializeObject(string json, out object obj)
  510. {
  511. bool success = true;
  512. if (json != null)
  513. {
  514. char[] charArray = json.ToCharArray();
  515. int index = 0;
  516. obj = ParseValue(charArray, ref index, ref success);
  517. }
  518. else
  519. obj = null;
  520. return success;
  521. }
  522. public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy)
  523. {
  524. object jsonObject = DeserializeObject(json);
  525. return type == null || jsonObject != null && ReflectionUtils.IsAssignableFrom(jsonObject.GetType(), type)
  526. ? jsonObject
  527. : (jsonSerializerStrategy ?? CurrentJsonSerializerStrategy).DeserializeObject(jsonObject, type);
  528. }
  529. public static object DeserializeObject(string json, Type type)
  530. {
  531. return DeserializeObject(json, type, null);
  532. }
  533. public static T DeserializeObject<T>(string json, IJsonSerializerStrategy jsonSerializerStrategy)
  534. {
  535. return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy);
  536. }
  537. public static T DeserializeObject<T>(string json)
  538. {
  539. return (T)DeserializeObject(json, typeof(T), null);
  540. }
  541. /// <summary>
  542. /// Converts a IDictionary&lt;string,object> / IList&lt;object> object into a JSON string
  543. /// </summary>
  544. /// <param name="json">A IDictionary&lt;string,object> / IList&lt;object></param>
  545. /// <param name="jsonSerializerStrategy">Serializer strategy to use</param>
  546. /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
  547. public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy)
  548. {
  549. StringBuilder builder = new StringBuilder(BUILDER_CAPACITY);
  550. bool success = SerializeValue(jsonSerializerStrategy, json, builder);
  551. return (success ? builder.ToString() : null);
  552. }
  553. public static string SerializeObject(object json)
  554. {
  555. return SerializeObject(json, CurrentJsonSerializerStrategy);
  556. }
  557. public static string EscapeToJavascriptString(string jsonString)
  558. {
  559. if (string.IsNullOrEmpty(jsonString))
  560. return jsonString;
  561. StringBuilder sb = new StringBuilder();
  562. char c;
  563. for (int i = 0; i < jsonString.Length; )
  564. {
  565. c = jsonString[i++];
  566. if (c == '\\')
  567. {
  568. int remainingLength = jsonString.Length - i;
  569. if (remainingLength >= 2)
  570. {
  571. char lookahead = jsonString[i];
  572. if (lookahead == '\\')
  573. {
  574. sb.Append('\\');
  575. ++i;
  576. }
  577. else if (lookahead == '"')
  578. {
  579. sb.Append("\"");
  580. ++i;
  581. }
  582. else if (lookahead == 't')
  583. {
  584. sb.Append('\t');
  585. ++i;
  586. }
  587. else if (lookahead == 'b')
  588. {
  589. sb.Append('\b');
  590. ++i;
  591. }
  592. else if (lookahead == 'n')
  593. {
  594. sb.Append('\n');
  595. ++i;
  596. }
  597. else if (lookahead == 'r')
  598. {
  599. sb.Append('\r');
  600. ++i;
  601. }
  602. }
  603. }
  604. else
  605. {
  606. sb.Append(c);
  607. }
  608. }
  609. return sb.ToString();
  610. }
  611. static IDictionary<string, object> ParseObject(char[] json, ref int index, ref bool success)
  612. {
  613. IDictionary<string, object> table = new JsonObject();
  614. int token;
  615. // {
  616. NextToken(json, ref index);
  617. bool done = false;
  618. while (!done)
  619. {
  620. token = LookAhead(json, index);
  621. if (token == TOKEN_NONE)
  622. {
  623. success = false;
  624. return null;
  625. }
  626. else if (token == TOKEN_COMMA)
  627. NextToken(json, ref index);
  628. else if (token == TOKEN_CURLY_CLOSE)
  629. {
  630. NextToken(json, ref index);
  631. return table;
  632. }
  633. else
  634. {
  635. // name
  636. string name = ParseString(json, ref index, ref success);
  637. if (!success)
  638. {
  639. success = false;
  640. return null;
  641. }
  642. // :
  643. token = NextToken(json, ref index);
  644. if (token != TOKEN_COLON)
  645. {
  646. success = false;
  647. return null;
  648. }
  649. // value
  650. object value = ParseValue(json, ref index, ref success);
  651. if (!success)
  652. {
  653. success = false;
  654. return null;
  655. }
  656. table[name] = value;
  657. }
  658. }
  659. return table;
  660. }
  661. static JsonArray ParseArray(char[] json, ref int index, ref bool success)
  662. {
  663. JsonArray array = new JsonArray();
  664. // [
  665. NextToken(json, ref index);
  666. bool done = false;
  667. while (!done)
  668. {
  669. int token = LookAhead(json, index);
  670. if (token == TOKEN_NONE)
  671. {
  672. success = false;
  673. return null;
  674. }
  675. else if (token == TOKEN_COMMA)
  676. NextToken(json, ref index);
  677. else if (token == TOKEN_SQUARED_CLOSE)
  678. {
  679. NextToken(json, ref index);
  680. break;
  681. }
  682. else
  683. {
  684. object value = ParseValue(json, ref index, ref success);
  685. if (!success)
  686. return null;
  687. array.Add(value);
  688. }
  689. }
  690. return array;
  691. }
  692. static object ParseValue(char[] json, ref int index, ref bool success)
  693. {
  694. switch (LookAhead(json, index))
  695. {
  696. case TOKEN_STRING:
  697. return ParseString(json, ref index, ref success);
  698. case TOKEN_NUMBER:
  699. return ParseNumber(json, ref index, ref success);
  700. case TOKEN_CURLY_OPEN:
  701. return ParseObject(json, ref index, ref success);
  702. case TOKEN_SQUARED_OPEN:
  703. return ParseArray(json, ref index, ref success);
  704. case TOKEN_TRUE:
  705. NextToken(json, ref index);
  706. return true;
  707. case TOKEN_FALSE:
  708. NextToken(json, ref index);
  709. return false;
  710. case TOKEN_NULL:
  711. NextToken(json, ref index);
  712. return null;
  713. case TOKEN_NONE:
  714. break;
  715. }
  716. success = false;
  717. return null;
  718. }
  719. static string ParseString(char[] json, ref int index, ref bool success)
  720. {
  721. StringBuilder s = new StringBuilder(BUILDER_CAPACITY);
  722. char c;
  723. EatWhitespace(json, ref index);
  724. // "
  725. c = json[index++];
  726. bool complete = false;
  727. while (!complete)
  728. {
  729. if (index == json.Length)
  730. break;
  731. c = json[index++];
  732. if (c == '"')
  733. {
  734. complete = true;
  735. break;
  736. }
  737. else if (c == '\\')
  738. {
  739. if (index == json.Length)
  740. break;
  741. c = json[index++];
  742. if (c == '"')
  743. s.Append('"');
  744. else if (c == '\\')
  745. s.Append('\\');
  746. else if (c == '/')
  747. s.Append('/');
  748. else if (c == 'b')
  749. s.Append('\b');
  750. else if (c == 'f')
  751. s.Append('\f');
  752. else if (c == 'n')
  753. s.Append('\n');
  754. else if (c == 'r')
  755. s.Append('\r');
  756. else if (c == 't')
  757. s.Append('\t');
  758. else if (c == 'u')
  759. {
  760. int remainingLength = json.Length - index;
  761. if (remainingLength >= 4)
  762. {
  763. // parse the 32 bit hex into an integer codepoint
  764. uint codePoint;
  765. if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint)))
  766. return "";
  767. // convert the integer codepoint to a unicode char and add to string
  768. if (0xD800 <= codePoint && codePoint <= 0xDBFF) // if high surrogate
  769. {
  770. index += 4; // skip 4 chars
  771. remainingLength = json.Length - index;
  772. if (remainingLength >= 6)
  773. {
  774. uint lowCodePoint;
  775. if (new string(json, index, 2) == "\\u" && UInt32.TryParse(new string(json, index + 2, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lowCodePoint))
  776. {
  777. if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF) // if low surrogate
  778. {
  779. s.Append((char)codePoint);
  780. s.Append((char)lowCodePoint);
  781. index += 6; // skip 6 chars
  782. continue;
  783. }
  784. }
  785. }
  786. success = false; // invalid surrogate pair
  787. return "";
  788. }
  789. s.Append(ConvertFromUtf32((int)codePoint));
  790. // skip 4 chars
  791. index += 4;
  792. }
  793. else
  794. break;
  795. }
  796. }
  797. else
  798. s.Append(c);
  799. }
  800. if (!complete)
  801. {
  802. success = false;
  803. return null;
  804. }
  805. return s.ToString();
  806. }
  807. private static string ConvertFromUtf32(int utf32)
  808. {
  809. // http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System/System/Char.cs.htm
  810. if (utf32 < 0 || utf32 > 0x10FFFF)
  811. throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF.");
  812. if (0xD800 <= utf32 && utf32 <= 0xDFFF)
  813. throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range.");
  814. if (utf32 < 0x10000)
  815. return new string((char)utf32, 1);
  816. utf32 -= 0x10000;
  817. return new string(new char[] { (char)((utf32 >> 10) + 0xD800), (char)(utf32 % 0x0400 + 0xDC00) });
  818. }
  819. static object ParseNumber(char[] json, ref int index, ref bool success)
  820. {
  821. EatWhitespace(json, ref index);
  822. int lastIndex = GetLastIndexOfNumber(json, index);
  823. int charLength = (lastIndex - index) + 1;
  824. object returnNumber;
  825. string str = new string(json, index, charLength);
  826. if (str.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || str.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1)
  827. {
  828. double number;
  829. success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
  830. returnNumber = number;
  831. }
  832. else
  833. {
  834. long number;
  835. success = long.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
  836. returnNumber = number;
  837. }
  838. index = lastIndex + 1;
  839. return returnNumber;
  840. }
  841. static int GetLastIndexOfNumber(char[] json, int index)
  842. {
  843. int lastIndex;
  844. for (lastIndex = index; lastIndex < json.Length; lastIndex++)
  845. if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) break;
  846. return lastIndex - 1;
  847. }
  848. static void EatWhitespace(char[] json, ref int index)
  849. {
  850. for (; index < json.Length; index++)
  851. if (" \t\n\r\b\f".IndexOf(json[index]) == -1) break;
  852. }
  853. static int LookAhead(char[] json, int index)
  854. {
  855. int saveIndex = index;
  856. return NextToken(json, ref saveIndex);
  857. }
  858. [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
  859. static int NextToken(char[] json, ref int index)
  860. {
  861. EatWhitespace(json, ref index);
  862. if (index == json.Length)
  863. return TOKEN_NONE;
  864. char c = json[index];
  865. index++;
  866. switch (c)
  867. {
  868. case '{':
  869. return TOKEN_CURLY_OPEN;
  870. case '}':
  871. return TOKEN_CURLY_CLOSE;
  872. case '[':
  873. return TOKEN_SQUARED_OPEN;
  874. case ']':
  875. return TOKEN_SQUARED_CLOSE;
  876. case ',':
  877. return TOKEN_COMMA;
  878. case '"':
  879. return TOKEN_STRING;
  880. case '0':
  881. case '1':
  882. case '2':
  883. case '3':
  884. case '4':
  885. case '5':
  886. case '6':
  887. case '7':
  888. case '8':
  889. case '9':
  890. case '-':
  891. return TOKEN_NUMBER;
  892. case ':':
  893. return TOKEN_COLON;
  894. }
  895. index--;
  896. int remainingLength = json.Length - index;
  897. // false
  898. if (remainingLength >= 5)
  899. {
  900. if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e')
  901. {
  902. index += 5;
  903. return TOKEN_FALSE;
  904. }
  905. }
  906. // true
  907. if (remainingLength >= 4)
  908. {
  909. if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e')
  910. {
  911. index += 4;
  912. return TOKEN_TRUE;
  913. }
  914. }
  915. // null
  916. if (remainingLength >= 4)
  917. {
  918. if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l')
  919. {
  920. index += 4;
  921. return TOKEN_NULL;
  922. }
  923. }
  924. return TOKEN_NONE;
  925. }
  926. static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, StringBuilder builder)
  927. {
  928. bool success = true;
  929. string stringValue = value as string;
  930. if (stringValue != null)
  931. success = SerializeString(stringValue, builder);
  932. else
  933. {
  934. IDictionary<string, object> dict = value as IDictionary<string, object>;
  935. if (dict != null)
  936. {
  937. success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder);
  938. }
  939. else
  940. {
  941. IDictionary<string, string> stringDictionary = value as IDictionary<string, string>;
  942. if (stringDictionary != null)
  943. {
  944. success = SerializeObject(jsonSerializerStrategy, stringDictionary.Keys, stringDictionary.Values, builder);
  945. }
  946. else
  947. {
  948. IEnumerable enumerableValue = value as IEnumerable;
  949. if (enumerableValue != null)
  950. success = SerializeArray(jsonSerializerStrategy, enumerableValue, builder);
  951. else if (IsNumeric(value))
  952. success = SerializeNumber(value, builder);
  953. else if (value is bool)
  954. builder.Append((bool)value ? "true" : "false");
  955. else if (value == null)
  956. builder.Append("null");
  957. else
  958. {
  959. object serializedObject;
  960. success = jsonSerializerStrategy.TrySerializeNonPrimitiveObject(value, out serializedObject);
  961. if (success)
  962. SerializeValue(jsonSerializerStrategy, serializedObject, builder);
  963. }
  964. }
  965. }
  966. }
  967. return success;
  968. }
  969. static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder)
  970. {
  971. builder.Append("{");
  972. IEnumerator ke = keys.GetEnumerator();
  973. IEnumerator ve = values.GetEnumerator();
  974. bool first = true;
  975. while (ke.MoveNext() && ve.MoveNext())
  976. {
  977. object key = ke.Current;
  978. object value = ve.Current;
  979. if (!first)
  980. builder.Append(",");
  981. string stringKey = key as string;
  982. if (stringKey != null)
  983. SerializeString(stringKey, builder);
  984. else
  985. if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false;
  986. builder.Append(":");
  987. if (!SerializeValue(jsonSerializerStrategy, value, builder))
  988. return false;
  989. first = false;
  990. }
  991. builder.Append("}");
  992. return true;
  993. }
  994. static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder)
  995. {
  996. builder.Append("[");
  997. bool first = true;
  998. foreach (object value in anArray)
  999. {
  1000. if (!first)
  1001. builder.Append(",");
  1002. if (!SerializeValue(jsonSerializerStrategy, value, builder))
  1003. return false;
  1004. first = false;
  1005. }
  1006. builder.Append("]");
  1007. return true;
  1008. }
  1009. static bool SerializeString(string aString, StringBuilder builder)
  1010. {
  1011. // Happy path if there's nothing to be escaped. IndexOfAny is highly optimized (and unmanaged)
  1012. if (aString.IndexOfAny(EscapeCharacters) == -1)
  1013. {
  1014. builder.Append('"');
  1015. builder.Append(aString);
  1016. builder.Append('"');
  1017. return true;
  1018. }
  1019. builder.Append('"');
  1020. int safeCharacterCount = 0;
  1021. char[] charArray = aString.ToCharArray();
  1022. for (int i = 0; i < charArray.Length; i++)
  1023. {
  1024. char c = charArray[i];
  1025. // Non ascii characters are fine, buffer them up and send them to the builder
  1026. // in larger chunks if possible. The escape table is a 1:1 translation table
  1027. // with \0 [default(char)] denoting a safe character.
  1028. if (c >= EscapeTable.Length || EscapeTable[c] == default(char))
  1029. {
  1030. safeCharacterCount++;
  1031. }
  1032. else
  1033. {
  1034. if (safeCharacterCount > 0)
  1035. {
  1036. builder.Append(charArray, i - safeCharacterCount, safeCharacterCount);
  1037. safeCharacterCount = 0;
  1038. }
  1039. builder.Append('\\');
  1040. builder.Append(EscapeTable[c]);
  1041. }
  1042. }
  1043. if (safeCharacterCount > 0)
  1044. {
  1045. builder.Append(charArray, charArray.Length - safeCharacterCount, safeCharacterCount);
  1046. }
  1047. builder.Append('"');
  1048. return true;
  1049. }
  1050. static bool SerializeNumber(object number, StringBuilder builder)
  1051. {
  1052. if (number is long)
  1053. builder.Append(((long)number).ToString(CultureInfo.InvariantCulture));
  1054. else if (number is ulong)
  1055. builder.Append(((ulong)number).ToString(CultureInfo.InvariantCulture));
  1056. else if (number is int)
  1057. builder.Append(((int)number).ToString(CultureInfo.InvariantCulture));
  1058. else if (number is uint)
  1059. builder.Append(((uint)number).ToString(CultureInfo.InvariantCulture));
  1060. else if (number is decimal)
  1061. builder.Append(((decimal)number).ToString(CultureInfo.InvariantCulture));
  1062. else if (number is float)
  1063. builder.Append(((float)number).ToString(CultureInfo.InvariantCulture));
  1064. else
  1065. builder.Append(Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString("r", CultureInfo.InvariantCulture));
  1066. return true;
  1067. }
  1068. /// <summary>
  1069. /// Determines if a given object is numeric in any way
  1070. /// (can be integer, double, null, etc).
  1071. /// </summary>
  1072. static bool IsNumeric(object value)
  1073. {
  1074. if (value is sbyte) return true;
  1075. if (value is byte) return true;
  1076. if (value is short) return true;
  1077. if (value is ushort) return true;
  1078. if (value is int) return true;
  1079. if (value is uint) return true;
  1080. if (value is long) return true;
  1081. if (value is ulong) return true;
  1082. if (value is float) return true;
  1083. if (value is double) return true;
  1084. if (value is decimal) return true;
  1085. return false;
  1086. }
  1087. private static IJsonSerializerStrategy _currentJsonSerializerStrategy;
  1088. public static IJsonSerializerStrategy CurrentJsonSerializerStrategy
  1089. {
  1090. get
  1091. {
  1092. return _currentJsonSerializerStrategy ??
  1093. (_currentJsonSerializerStrategy =
  1094. #if SIMPLE_JSON_DATACONTRACT
  1095. DataContractJsonSerializerStrategy
  1096. #else
  1097. PocoJsonSerializerStrategy
  1098. #endif
  1099. );
  1100. }
  1101. set
  1102. {
  1103. _currentJsonSerializerStrategy = value;
  1104. }
  1105. }
  1106. private static PocoJsonSerializerStrategy _pocoJsonSerializerStrategy;
  1107. [EditorBrowsable(EditorBrowsableState.Advanced)]
  1108. public static PocoJsonSerializerStrategy PocoJsonSerializerStrategy
  1109. {
  1110. get
  1111. {
  1112. return _pocoJsonSerializerStrategy ?? (_pocoJsonSerializerStrategy = new PocoJsonSerializerStrategy());
  1113. }
  1114. }
  1115. #if SIMPLE_JSON_DATACONTRACT
  1116. private static DataContractJsonSerializerStrategy _dataContractJsonSerializerStrategy;
  1117. [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
  1118. public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrategy
  1119. {
  1120. get
  1121. {
  1122. return _dataContractJsonSerializerStrategy ?? (_dataContractJsonSerializerStrategy = new DataContractJsonSerializerStrategy());
  1123. }
  1124. }
  1125. #endif
  1126. }
  1127. [GeneratedCode("simple-json", "1.0.0")]
  1128. #if SIMPLE_JSON_INTERNAL
  1129. internal
  1130. #else
  1131. public
  1132. #endif
  1133. interface IJsonSerializerStrategy
  1134. {
  1135. [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")]
  1136. bool TrySerializeNonPrimitiveObject(object input, out object output);
  1137. object DeserializeObject(object value, Type type);
  1138. }
  1139. [GeneratedCode("simple-json", "1.0.0")]
  1140. #if SIMPLE_JSON_INTERNAL
  1141. internal
  1142. #else
  1143. public
  1144. #endif
  1145. class PocoJsonSerializerStrategy : IJsonSerializerStrategy
  1146. {
  1147. internal IDictionary<Type, ReflectionUtils.ConstructorDelegate> ConstructorCache;
  1148. internal IDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>> GetCache;
  1149. internal IDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>> SetCache;
  1150. internal static readonly Type[] EmptyTypes = new Type[0];
  1151. internal static readonly Type[] ArrayConstructorParameterTypes = new Type[] { typeof(int) };
  1152. private static readonly string[] Iso8601Format = new string[]
  1153. {
  1154. @"yyyy-MM-dd\THH:mm:ss.FFFFFFF\Z",
  1155. @"yyyy-MM-dd\THH:mm:ss\Z",
  1156. @"yyyy-MM-dd\THH:mm:ssK"
  1157. };
  1158. public PocoJsonSerializerStrategy()
  1159. {
  1160. ConstructorCache = new ReflectionUtils.ThreadSafeDictionary<Type, ReflectionUtils.ConstructorDelegate>(ContructorDelegateFactory);
  1161. GetCache = new Reflect