PageRenderTime 71ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/desktop_clients/Visual Studio/Crear beneficiarios/Json100r3/Source/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs

https://bitbucket.org/wfpcoslv/maps-examples
C# | 2583 lines | 2244 code | 243 blank | 96 comment | 42 complexity | 8db323d978316227d17d73cd5f69840c MD5 | raw file
Possible License(s): GPL-2.0
  1. #region License
  2. // Copyright (c) 2007 James Newton-King
  3. //
  4. // Permission is hereby granted, free of charge, to any person
  5. // obtaining a copy of this software and associated documentation
  6. // files (the "Software"), to deal in the Software without
  7. // restriction, including without limitation the rights to use,
  8. // copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the
  10. // Software is furnished to do so, subject to the following
  11. // conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  18. // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  20. // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21. // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23. // OTHER DEALINGS IN THE SOFTWARE.
  24. #endregion
  25. using System;
  26. using System.Collections;
  27. using System.Collections.Concurrent;
  28. using System.Collections.Specialized;
  29. using System.Runtime.Serialization;
  30. using System.Collections.Generic;
  31. using System.Collections.ObjectModel;
  32. using System.Globalization;
  33. using System.IO;
  34. #if NET20
  35. using Newtonsoft.Json.Utilities.LinqBridge;
  36. #else
  37. using System.Linq;
  38. #endif
  39. using System.Text;
  40. using System.Xml;
  41. using Newtonsoft.Json.Linq;
  42. using Newtonsoft.Json.Serialization;
  43. using Newtonsoft.Json.Tests.TestObjects;
  44. using Newtonsoft.Json.Tests.TestObjects.Events;
  45. using Newtonsoft.Json.Tests.TestObjects.Organization;
  46. using Newtonsoft.Json.Utilities;
  47. #if DNXCORE50
  48. using Xunit;
  49. using Test = Xunit.FactAttribute;
  50. using Assert = Newtonsoft.Json.Tests.XUnitAssert;
  51. #else
  52. using NUnit.Framework;
  53. #endif
  54. #if !NET20 && !PORTABLE40
  55. using System.Xml.Linq;
  56. #endif
  57. namespace Newtonsoft.Json.Tests.Serialization
  58. {
  59. [TestFixture]
  60. public class JsonSerializerCollectionsTests : TestFixtureBase
  61. {
  62. #if !(NET20 || NET35)
  63. [Test]
  64. public void SerializeConcurrentQueue()
  65. {
  66. ConcurrentQueue<int> queue1 = new ConcurrentQueue<int>();
  67. queue1.Enqueue(1);
  68. string output = JsonConvert.SerializeObject(queue1);
  69. Assert.AreEqual(@"[1]", output);
  70. ConcurrentQueue<int> queue2 = JsonConvert.DeserializeObject<ConcurrentQueue<int>>(output);
  71. int i;
  72. Assert.IsTrue(queue2.TryDequeue(out i));
  73. Assert.AreEqual(1, i);
  74. }
  75. [Test]
  76. public void SerializeConcurrentBag()
  77. {
  78. ConcurrentBag<int> bag1 = new ConcurrentBag<int>();
  79. bag1.Add(1);
  80. string output = JsonConvert.SerializeObject(bag1);
  81. Assert.AreEqual(@"[1]", output);
  82. ConcurrentBag<int> bag2 = JsonConvert.DeserializeObject<ConcurrentBag<int>>(output);
  83. int i;
  84. Assert.IsTrue(bag2.TryTake(out i));
  85. Assert.AreEqual(1, i);
  86. }
  87. [Test]
  88. public void SerializeConcurrentStack()
  89. {
  90. ConcurrentStack<int> stack1 = new ConcurrentStack<int>();
  91. stack1.Push(1);
  92. string output = JsonConvert.SerializeObject(stack1);
  93. Assert.AreEqual(@"[1]", output);
  94. ConcurrentStack<int> stack2 = JsonConvert.DeserializeObject<ConcurrentStack<int>>(output);
  95. int i;
  96. Assert.IsTrue(stack2.TryPop(out i));
  97. Assert.AreEqual(1, i);
  98. }
  99. #endif
  100. [Test]
  101. public void DoubleKey_WholeValue()
  102. {
  103. Dictionary<double, int> dictionary = new Dictionary<double, int> { { 1d, 1 } };
  104. string output = JsonConvert.SerializeObject(dictionary);
  105. Assert.AreEqual(@"{""1"":1}", output);
  106. Dictionary<double, int> deserializedValue = JsonConvert.DeserializeObject<Dictionary<double, int>>(output);
  107. Assert.AreEqual(1d, deserializedValue.First().Key);
  108. }
  109. [Test]
  110. public void DoubleKey_MaxValue()
  111. {
  112. Dictionary<double, int> dictionary = new Dictionary<double, int> { { double.MaxValue, 1 } };
  113. string output = JsonConvert.SerializeObject(dictionary);
  114. Assert.AreEqual(@"{""1.7976931348623157E+308"":1}", output);
  115. Dictionary<double, int> deserializedValue = JsonConvert.DeserializeObject<Dictionary<double, int>>(output);
  116. Assert.AreEqual(double.MaxValue, deserializedValue.First().Key);
  117. }
  118. [Test]
  119. public void FloatKey_MaxValue()
  120. {
  121. Dictionary<float, int> dictionary = new Dictionary<float, int> { { float.MaxValue, 1 } };
  122. string output = JsonConvert.SerializeObject(dictionary);
  123. Assert.AreEqual(@"{""3.40282347E+38"":1}", output);
  124. Dictionary<float, int> deserializedValue = JsonConvert.DeserializeObject<Dictionary<float, int>>(output);
  125. Assert.AreEqual(float.MaxValue, deserializedValue.First().Key);
  126. }
  127. public class TestCollectionPrivateParameterized : IEnumerable<int>
  128. {
  129. private readonly List<int> _bars;
  130. public TestCollectionPrivateParameterized()
  131. {
  132. _bars = new List<int>();
  133. }
  134. [JsonConstructor]
  135. private TestCollectionPrivateParameterized(IEnumerable<int> bars)
  136. {
  137. _bars = new List<int>(bars);
  138. }
  139. public void Add(int bar)
  140. {
  141. _bars.Add(bar);
  142. }
  143. public IEnumerator<int> GetEnumerator() => _bars.GetEnumerator();
  144. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  145. }
  146. [Test]
  147. public void CollectionJsonConstructorPrivateParameterized()
  148. {
  149. TestCollectionPrivateParameterized c1 = new TestCollectionPrivateParameterized();
  150. c1.Add(0);
  151. c1.Add(1);
  152. c1.Add(2);
  153. string json = JsonConvert.SerializeObject(c1);
  154. TestCollectionPrivateParameterized c2 = JsonConvert.DeserializeObject<TestCollectionPrivateParameterized>(json);
  155. List<int> values = c2.ToList();
  156. Assert.AreEqual(3, values.Count);
  157. Assert.AreEqual(0, values[0]);
  158. Assert.AreEqual(1, values[1]);
  159. Assert.AreEqual(2, values[2]);
  160. }
  161. public class TestCollectionPrivate : List<int>
  162. {
  163. [JsonConstructor]
  164. private TestCollectionPrivate()
  165. {
  166. }
  167. public static TestCollectionPrivate Create()
  168. {
  169. return new TestCollectionPrivate();
  170. }
  171. }
  172. [Test]
  173. public void CollectionJsonConstructorPrivate()
  174. {
  175. TestCollectionPrivate c1 = TestCollectionPrivate.Create();
  176. c1.Add(0);
  177. c1.Add(1);
  178. c1.Add(2);
  179. string json = JsonConvert.SerializeObject(c1);
  180. TestCollectionPrivate c2 = JsonConvert.DeserializeObject<TestCollectionPrivate>(json);
  181. List<int> values = c2.ToList();
  182. Assert.AreEqual(3, values.Count);
  183. Assert.AreEqual(0, values[0]);
  184. Assert.AreEqual(1, values[1]);
  185. Assert.AreEqual(2, values[2]);
  186. }
  187. public class TestCollectionMultipleParameters : List<int>
  188. {
  189. [JsonConstructor]
  190. public TestCollectionMultipleParameters(string s1, string s2)
  191. {
  192. }
  193. }
  194. [Test]
  195. public void CollectionJsonConstructorMultipleParameters()
  196. {
  197. ExceptionAssert.Throws<JsonException>(
  198. () => JsonConvert.SerializeObject(new TestCollectionMultipleParameters(null, null)),
  199. "Constructor for 'Newtonsoft.Json.Tests.Serialization.JsonSerializerCollectionsTests+TestCollectionMultipleParameters' must have no parameters or a single parameter that implements 'System.Collections.Generic.IEnumerable`1[System.Int32]'.");
  200. }
  201. public class TestCollectionBadIEnumerableParameter : List<int>
  202. {
  203. [JsonConstructor]
  204. public TestCollectionBadIEnumerableParameter(List<string> l)
  205. {
  206. }
  207. }
  208. [Test]
  209. public void CollectionJsonConstructorBadIEnumerableParameter()
  210. {
  211. ExceptionAssert.Throws<JsonException>(
  212. () => JsonConvert.SerializeObject(new TestCollectionBadIEnumerableParameter(null)),
  213. "Constructor for 'Newtonsoft.Json.Tests.Serialization.JsonSerializerCollectionsTests+TestCollectionBadIEnumerableParameter' must have no parameters or a single parameter that implements 'System.Collections.Generic.IEnumerable`1[System.Int32]'.");
  214. }
  215. #if !(DNXCORE50 || PORTABLE)
  216. public class TestCollectionNonGeneric : ArrayList
  217. {
  218. [JsonConstructor]
  219. public TestCollectionNonGeneric(IEnumerable l)
  220. : base(l.Cast<object>().ToList())
  221. {
  222. }
  223. }
  224. [Test]
  225. public void CollectionJsonConstructorNonGeneric()
  226. {
  227. string json = @"[1,2,3]";
  228. TestCollectionNonGeneric l = JsonConvert.DeserializeObject<TestCollectionNonGeneric>(json);
  229. Assert.AreEqual(3, l.Count);
  230. Assert.AreEqual(1, l[0]);
  231. Assert.AreEqual(2, l[1]);
  232. Assert.AreEqual(3, l[2]);
  233. }
  234. #endif
  235. public class TestDictionaryPrivateParameterized : Dictionary<string, int>
  236. {
  237. public TestDictionaryPrivateParameterized()
  238. {
  239. }
  240. [JsonConstructor]
  241. private TestDictionaryPrivateParameterized(IEnumerable<KeyValuePair<string, int>> bars)
  242. : base(bars.ToDictionary(k => k.Key, k => k.Value))
  243. {
  244. }
  245. }
  246. [Test]
  247. public void DictionaryJsonConstructorPrivateParameterized()
  248. {
  249. TestDictionaryPrivateParameterized c1 = new TestDictionaryPrivateParameterized();
  250. c1.Add("zero", 0);
  251. c1.Add("one", 1);
  252. c1.Add("two", 2);
  253. string json = JsonConvert.SerializeObject(c1);
  254. TestDictionaryPrivateParameterized c2 = JsonConvert.DeserializeObject<TestDictionaryPrivateParameterized>(json);
  255. Assert.AreEqual(3, c2.Count);
  256. Assert.AreEqual(0, c2["zero"]);
  257. Assert.AreEqual(1, c2["one"]);
  258. Assert.AreEqual(2, c2["two"]);
  259. }
  260. public class TestDictionaryPrivate : Dictionary<string, int>
  261. {
  262. [JsonConstructor]
  263. private TestDictionaryPrivate()
  264. {
  265. }
  266. public static TestDictionaryPrivate Create()
  267. {
  268. return new TestDictionaryPrivate();
  269. }
  270. }
  271. [Test]
  272. public void DictionaryJsonConstructorPrivate()
  273. {
  274. TestDictionaryPrivate c1 = TestDictionaryPrivate.Create();
  275. c1.Add("zero", 0);
  276. c1.Add("one", 1);
  277. c1.Add("two", 2);
  278. string json = JsonConvert.SerializeObject(c1);
  279. TestDictionaryPrivate c2 = JsonConvert.DeserializeObject<TestDictionaryPrivate>(json);
  280. Assert.AreEqual(3, c2.Count);
  281. Assert.AreEqual(0, c2["zero"]);
  282. Assert.AreEqual(1, c2["one"]);
  283. Assert.AreEqual(2, c2["two"]);
  284. }
  285. public class TestDictionaryMultipleParameters : Dictionary<string, int>
  286. {
  287. [JsonConstructor]
  288. public TestDictionaryMultipleParameters(string s1, string s2)
  289. {
  290. }
  291. }
  292. [Test]
  293. public void DictionaryJsonConstructorMultipleParameters()
  294. {
  295. ExceptionAssert.Throws<JsonException>(
  296. () => JsonConvert.SerializeObject(new TestDictionaryMultipleParameters(null, null)),
  297. "Constructor for 'Newtonsoft.Json.Tests.Serialization.JsonSerializerCollectionsTests+TestDictionaryMultipleParameters' must have no parameters or a single parameter that implements 'System.Collections.Generic.IEnumerable`1[System.Collections.Generic.KeyValuePair`2[System.String,System.Int32]]'.");
  298. }
  299. public class TestDictionaryBadIEnumerableParameter : Dictionary<string, int>
  300. {
  301. [JsonConstructor]
  302. public TestDictionaryBadIEnumerableParameter(Dictionary<string, string> l)
  303. {
  304. }
  305. }
  306. [Test]
  307. public void DictionaryJsonConstructorBadIEnumerableParameter()
  308. {
  309. ExceptionAssert.Throws<JsonException>(
  310. () => JsonConvert.SerializeObject(new TestDictionaryBadIEnumerableParameter(null)),
  311. "Constructor for 'Newtonsoft.Json.Tests.Serialization.JsonSerializerCollectionsTests+TestDictionaryBadIEnumerableParameter' must have no parameters or a single parameter that implements 'System.Collections.Generic.IEnumerable`1[System.Collections.Generic.KeyValuePair`2[System.String,System.Int32]]'.");
  312. }
  313. #if !(DNXCORE50 || PORTABLE)
  314. public class TestDictionaryNonGeneric : Hashtable
  315. {
  316. [JsonConstructor]
  317. public TestDictionaryNonGeneric(IDictionary d)
  318. : base(d)
  319. {
  320. }
  321. }
  322. [Test]
  323. public void DictionaryJsonConstructorNonGeneric()
  324. {
  325. string json = @"{'zero':0,'one':1,'two':2}";
  326. TestDictionaryNonGeneric d = JsonConvert.DeserializeObject<TestDictionaryNonGeneric>(json);
  327. Assert.AreEqual(3, d.Count);
  328. Assert.AreEqual(0, d["zero"]);
  329. Assert.AreEqual(1, d["one"]);
  330. Assert.AreEqual(2, d["two"]);
  331. }
  332. #endif
  333. #if !(DNXCORE50)
  334. public class NameValueCollectionTestClass
  335. {
  336. public NameValueCollection Collection { get; set; }
  337. }
  338. [Test]
  339. public void DeserializeNameValueCollection()
  340. {
  341. ExceptionAssert.Throws<JsonSerializationException>(
  342. () => JsonConvert.DeserializeObject<NameValueCollectionTestClass>("{Collection:[]}"),
  343. "Cannot create and populate list type System.Collections.Specialized.NameValueCollection. Path 'Collection', line 1, position 13.");
  344. }
  345. #endif
  346. #if !(NET35 || NET20 || PORTABLE || PORTABLE40)
  347. public class SomeObject
  348. {
  349. public string Text1 { get; set; }
  350. }
  351. public class CustomConcurrentDictionary : ConcurrentDictionary<string, List<SomeObject>>
  352. {
  353. [OnDeserialized]
  354. internal void OnDeserializedMethod(StreamingContext context)
  355. {
  356. ((IDictionary)this).Add("key2", new List<SomeObject>
  357. {
  358. new SomeObject
  359. {
  360. Text1 = "value2"
  361. }
  362. });
  363. }
  364. }
  365. [Test]
  366. public void SerializeCustomConcurrentDictionary()
  367. {
  368. IDictionary d = new CustomConcurrentDictionary();
  369. d.Add("key", new List<SomeObject>
  370. {
  371. new SomeObject
  372. {
  373. Text1 = "value1"
  374. }
  375. });
  376. string json = JsonConvert.SerializeObject(d, Formatting.Indented);
  377. Assert.AreEqual(@"{
  378. ""key"": [
  379. {
  380. ""Text1"": ""value1""
  381. }
  382. ]
  383. }", json);
  384. CustomConcurrentDictionary d2 = JsonConvert.DeserializeObject<CustomConcurrentDictionary>(json);
  385. Assert.AreEqual(2, d2.Count);
  386. Assert.AreEqual("value1", d2["key"][0].Text1);
  387. Assert.AreEqual("value2", d2["key2"][0].Text1);
  388. }
  389. #endif
  390. [Test]
  391. public void NonZeroBasedArray()
  392. {
  393. var onebasedArray = Array.CreateInstance(typeof(string), new[] { 3 }, new[] { 2 });
  394. for (var i = onebasedArray.GetLowerBound(0); i <= onebasedArray.GetUpperBound(0); i++)
  395. {
  396. onebasedArray.SetValue(i.ToString(CultureInfo.InvariantCulture), new[] { i, });
  397. }
  398. string output = JsonConvert.SerializeObject(onebasedArray, Formatting.Indented);
  399. StringAssert.AreEqual(@"[
  400. ""2"",
  401. ""3"",
  402. ""4""
  403. ]", output);
  404. }
  405. [Test]
  406. public void NonZeroBasedMultiArray()
  407. {
  408. // lets create a two dimensional array, each rank is 1-based of with a capacity of 4.
  409. var onebasedArray = Array.CreateInstance(typeof(string), new[] { 3, 3 }, new[] { 1, 2 });
  410. // Iterate of the array elements and assign a random double
  411. for (var i = onebasedArray.GetLowerBound(0); i <= onebasedArray.GetUpperBound(0); i++)
  412. {
  413. for (var j = onebasedArray.GetLowerBound(1); j <= onebasedArray.GetUpperBound(1); j++)
  414. {
  415. onebasedArray.SetValue(i + "_" + j, new[] { i, j });
  416. }
  417. }
  418. // Now lets try and serialize the Array
  419. string output = JsonConvert.SerializeObject(onebasedArray, Formatting.Indented);
  420. StringAssert.AreEqual(@"[
  421. [
  422. ""1_2"",
  423. ""1_3"",
  424. ""1_4""
  425. ],
  426. [
  427. ""2_2"",
  428. ""2_3"",
  429. ""2_4""
  430. ],
  431. [
  432. ""3_2"",
  433. ""3_3"",
  434. ""3_4""
  435. ]
  436. ]", output);
  437. }
  438. [Test]
  439. public void MultiDObjectArray()
  440. {
  441. object[,] myOtherArray =
  442. {
  443. { new KeyValuePair<string, double>("my value", 0.8), "foobar" },
  444. { true, 0.4d },
  445. { 0.05f, 6 }
  446. };
  447. string myOtherArrayAsString = JsonConvert.SerializeObject(myOtherArray, Formatting.Indented);
  448. StringAssert.AreEqual(@"[
  449. [
  450. {
  451. ""Key"": ""my value"",
  452. ""Value"": 0.8
  453. },
  454. ""foobar""
  455. ],
  456. [
  457. true,
  458. 0.4
  459. ],
  460. [
  461. 0.05,
  462. 6
  463. ]
  464. ]", myOtherArrayAsString);
  465. JObject o = JObject.Parse(@"{
  466. ""Key"": ""my value"",
  467. ""Value"": 0.8
  468. }");
  469. object[,] myOtherResult = JsonConvert.DeserializeObject<object[,]>(myOtherArrayAsString);
  470. Assert.IsTrue(JToken.DeepEquals(o, (JToken)myOtherResult[0, 0]));
  471. Assert.AreEqual("foobar", myOtherResult[0, 1]);
  472. Assert.AreEqual(true, myOtherResult[1, 0]);
  473. Assert.AreEqual(0.4, myOtherResult[1, 1]);
  474. Assert.AreEqual(0.05, myOtherResult[2, 0]);
  475. Assert.AreEqual(6L, myOtherResult[2, 1]);
  476. }
  477. public class EnumerableClass<T> : IEnumerable<T>
  478. {
  479. private readonly IList<T> _values;
  480. public EnumerableClass(IEnumerable<T> values)
  481. {
  482. _values = new List<T>(values);
  483. }
  484. public IEnumerator<T> GetEnumerator()
  485. {
  486. return _values.GetEnumerator();
  487. }
  488. IEnumerator IEnumerable.GetEnumerator()
  489. {
  490. return GetEnumerator();
  491. }
  492. }
  493. [Test]
  494. public void DeserializeIEnumerableFromConstructor()
  495. {
  496. string json = @"[
  497. 1,
  498. 2,
  499. null
  500. ]";
  501. var result = JsonConvert.DeserializeObject<EnumerableClass<int?>>(json);
  502. Assert.AreEqual(3, result.Count());
  503. Assert.AreEqual(1, result.ElementAt(0));
  504. Assert.AreEqual(2, result.ElementAt(1));
  505. Assert.AreEqual(null, result.ElementAt(2));
  506. }
  507. public class EnumerableClassFailure<T> : IEnumerable<T>
  508. {
  509. private readonly IList<T> _values;
  510. public EnumerableClassFailure()
  511. {
  512. _values = new List<T>();
  513. }
  514. public IEnumerator<T> GetEnumerator()
  515. {
  516. return _values.GetEnumerator();
  517. }
  518. IEnumerator IEnumerable.GetEnumerator()
  519. {
  520. return GetEnumerator();
  521. }
  522. }
  523. [Test]
  524. public void DeserializeIEnumerableFromConstructor_Failure()
  525. {
  526. string json = @"[
  527. ""One"",
  528. ""II"",
  529. ""3""
  530. ]";
  531. ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<EnumerableClassFailure<string>>(json), "Cannot create and populate list type Newtonsoft.Json.Tests.Serialization.JsonSerializerCollectionsTests+EnumerableClassFailure`1[System.String]. Path '', line 1, position 1.");
  532. }
  533. public class PrivateDefaultCtorList<T> : List<T>
  534. {
  535. private PrivateDefaultCtorList()
  536. {
  537. }
  538. }
  539. [Test]
  540. public void DeserializePrivateListCtor()
  541. {
  542. ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<PrivateDefaultCtorList<int>>("[1,2]"), "Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerCollectionsTests+PrivateDefaultCtorList`1[System.Int32]. Path '', line 1, position 1.");
  543. var list = JsonConvert.DeserializeObject<PrivateDefaultCtorList<int>>("[1,2]", new JsonSerializerSettings
  544. {
  545. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
  546. });
  547. Assert.AreEqual(2, list.Count);
  548. }
  549. public class PrivateDefaultCtorWithIEnumerableCtorList<T> : List<T>
  550. {
  551. private PrivateDefaultCtorWithIEnumerableCtorList()
  552. {
  553. }
  554. public PrivateDefaultCtorWithIEnumerableCtorList(IEnumerable<T> values)
  555. : base(values)
  556. {
  557. Add(default(T));
  558. }
  559. }
  560. [Test]
  561. public void DeserializePrivateListConstructor()
  562. {
  563. var list = JsonConvert.DeserializeObject<PrivateDefaultCtorWithIEnumerableCtorList<int>>("[1,2]");
  564. Assert.AreEqual(3, list.Count);
  565. Assert.AreEqual(1, list[0]);
  566. Assert.AreEqual(2, list[1]);
  567. Assert.AreEqual(0, list[2]);
  568. }
  569. [Test]
  570. public void DeserializeNonIsoDateDictionaryKey()
  571. {
  572. Dictionary<DateTime, string> d = JsonConvert.DeserializeObject<Dictionary<DateTime, string>>(@"{""04/28/2013 00:00:00"":""test""}");
  573. Assert.AreEqual(1, d.Count);
  574. DateTime key = DateTime.Parse("04/28/2013 00:00:00", CultureInfo.InvariantCulture);
  575. Assert.AreEqual("test", d[key]);
  576. }
  577. [Test]
  578. public void DeserializeNonGenericList()
  579. {
  580. IList l = JsonConvert.DeserializeObject<IList>("['string!']");
  581. Assert.AreEqual(typeof(List<object>), l.GetType());
  582. Assert.AreEqual(1, l.Count);
  583. Assert.AreEqual("string!", l[0]);
  584. }
  585. #if !(NET40 || NET35 || NET20 || PORTABLE40)
  586. [Test]
  587. public void DeserializeReadOnlyListInterface()
  588. {
  589. IReadOnlyList<int> list = JsonConvert.DeserializeObject<IReadOnlyList<int>>("[1,2,3]");
  590. Assert.AreEqual(3, list.Count);
  591. Assert.AreEqual(1, list[0]);
  592. Assert.AreEqual(2, list[1]);
  593. Assert.AreEqual(3, list[2]);
  594. }
  595. [Test]
  596. public void DeserializeReadOnlyCollectionInterface()
  597. {
  598. IReadOnlyCollection<int> list = JsonConvert.DeserializeObject<IReadOnlyCollection<int>>("[1,2,3]");
  599. Assert.AreEqual(3, list.Count);
  600. Assert.AreEqual(1, list.ElementAt(0));
  601. Assert.AreEqual(2, list.ElementAt(1));
  602. Assert.AreEqual(3, list.ElementAt(2));
  603. }
  604. [Test]
  605. public void DeserializeReadOnlyCollection()
  606. {
  607. ReadOnlyCollection<int> list = JsonConvert.DeserializeObject<ReadOnlyCollection<int>>("[1,2,3]");
  608. Assert.AreEqual(3, list.Count);
  609. Assert.AreEqual(1, list[0]);
  610. Assert.AreEqual(2, list[1]);
  611. Assert.AreEqual(3, list[2]);
  612. }
  613. [Test]
  614. public void DeserializeReadOnlyDictionaryInterface()
  615. {
  616. IReadOnlyDictionary<string, int> dic = JsonConvert.DeserializeObject<IReadOnlyDictionary<string, int>>("{'one':1,'two':2}");
  617. Assert.AreEqual(2, dic.Count);
  618. Assert.AreEqual(1, dic["one"]);
  619. Assert.AreEqual(2, dic["two"]);
  620. CustomAssert.IsInstanceOfType(typeof(ReadOnlyDictionary<string, int>), dic);
  621. }
  622. [Test]
  623. public void DeserializeReadOnlyDictionary()
  624. {
  625. ReadOnlyDictionary<string, int> dic = JsonConvert.DeserializeObject<ReadOnlyDictionary<string, int>>("{'one':1,'two':2}");
  626. Assert.AreEqual(2, dic.Count);
  627. Assert.AreEqual(1, dic["one"]);
  628. Assert.AreEqual(2, dic["two"]);
  629. }
  630. public class CustomReadOnlyDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue>
  631. {
  632. private readonly IDictionary<TKey, TValue> _dictionary;
  633. public CustomReadOnlyDictionary(IDictionary<TKey, TValue> dictionary)
  634. {
  635. _dictionary = dictionary;
  636. }
  637. public bool ContainsKey(TKey key)
  638. {
  639. return _dictionary.ContainsKey(key);
  640. }
  641. public IEnumerable<TKey> Keys
  642. {
  643. get { return _dictionary.Keys; }
  644. }
  645. public bool TryGetValue(TKey key, out TValue value)
  646. {
  647. return _dictionary.TryGetValue(key, out value);
  648. }
  649. public IEnumerable<TValue> Values
  650. {
  651. get { return _dictionary.Values; }
  652. }
  653. public TValue this[TKey key]
  654. {
  655. get { return _dictionary[key]; }
  656. }
  657. public int Count
  658. {
  659. get { return _dictionary.Count; }
  660. }
  661. public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
  662. {
  663. return _dictionary.GetEnumerator();
  664. }
  665. IEnumerator IEnumerable.GetEnumerator()
  666. {
  667. return _dictionary.GetEnumerator();
  668. }
  669. }
  670. [Test]
  671. public void SerializeCustomReadOnlyDictionary()
  672. {
  673. IDictionary<string, int> d = new Dictionary<string, int>
  674. {
  675. { "one", 1 },
  676. { "two", 2 }
  677. };
  678. CustomReadOnlyDictionary<string, int> dic = new CustomReadOnlyDictionary<string, int>(d);
  679. string json = JsonConvert.SerializeObject(dic, Formatting.Indented);
  680. StringAssert.AreEqual(@"{
  681. ""one"": 1,
  682. ""two"": 2
  683. }", json);
  684. }
  685. public class CustomReadOnlyCollection<T> : IReadOnlyCollection<T>
  686. {
  687. private readonly IList<T> _values;
  688. public CustomReadOnlyCollection(IList<T> values)
  689. {
  690. _values = values;
  691. }
  692. public int Count
  693. {
  694. get { return _values.Count; }
  695. }
  696. public IEnumerator<T> GetEnumerator()
  697. {
  698. return _values.GetEnumerator();
  699. }
  700. IEnumerator IEnumerable.GetEnumerator()
  701. {
  702. return _values.GetEnumerator();
  703. }
  704. }
  705. [Test]
  706. public void SerializeCustomReadOnlyCollection()
  707. {
  708. IList<int> l = new List<int>
  709. {
  710. 1,
  711. 2,
  712. 3
  713. };
  714. CustomReadOnlyCollection<int> list = new CustomReadOnlyCollection<int>(l);
  715. string json = JsonConvert.SerializeObject(list, Formatting.Indented);
  716. StringAssert.AreEqual(@"[
  717. 1,
  718. 2,
  719. 3
  720. ]", json);
  721. }
  722. #endif
  723. [Test]
  724. public void TestEscapeDictionaryStrings()
  725. {
  726. const string s = @"host\user";
  727. string serialized = JsonConvert.SerializeObject(s);
  728. Assert.AreEqual(@"""host\\user""", serialized);
  729. Dictionary<int, object> d1 = new Dictionary<int, object>();
  730. d1.Add(5, s);
  731. Assert.AreEqual(@"{""5"":""host\\user""}", JsonConvert.SerializeObject(d1));
  732. Dictionary<string, object> d2 = new Dictionary<string, object>();
  733. d2.Add(s, 5);
  734. Assert.AreEqual(@"{""host\\user"":5}", JsonConvert.SerializeObject(d2));
  735. }
  736. public class GenericListTestClass
  737. {
  738. public List<string> GenericList { get; set; }
  739. public GenericListTestClass()
  740. {
  741. GenericList = new List<string>();
  742. }
  743. }
  744. [Test]
  745. public void DeserializeExistingGenericList()
  746. {
  747. GenericListTestClass c = new GenericListTestClass();
  748. c.GenericList.Add("1");
  749. c.GenericList.Add("2");
  750. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  751. GenericListTestClass newValue = JsonConvert.DeserializeObject<GenericListTestClass>(json);
  752. Assert.AreEqual(2, newValue.GenericList.Count);
  753. Assert.AreEqual(typeof(List<string>), newValue.GenericList.GetType());
  754. }
  755. [Test]
  756. public void DeserializeSimpleKeyValuePair()
  757. {
  758. List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
  759. list.Add(new KeyValuePair<string, string>("key1", "value1"));
  760. list.Add(new KeyValuePair<string, string>("key2", "value2"));
  761. string json = JsonConvert.SerializeObject(list);
  762. Assert.AreEqual(@"[{""Key"":""key1"",""Value"":""value1""},{""Key"":""key2"",""Value"":""value2""}]", json);
  763. List<KeyValuePair<string, string>> result = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(json);
  764. Assert.AreEqual(2, result.Count);
  765. Assert.AreEqual("key1", result[0].Key);
  766. Assert.AreEqual("value1", result[0].Value);
  767. Assert.AreEqual("key2", result[1].Key);
  768. Assert.AreEqual("value2", result[1].Value);
  769. }
  770. [Test]
  771. public void DeserializeComplexKeyValuePair()
  772. {
  773. DateTime dateTime = new DateTime(2000, 12, 1, 23, 1, 1, DateTimeKind.Utc);
  774. List<KeyValuePair<string, WagePerson>> list = new List<KeyValuePair<string, WagePerson>>();
  775. list.Add(new KeyValuePair<string, WagePerson>("key1", new WagePerson
  776. {
  777. BirthDate = dateTime,
  778. Department = "Department1",
  779. LastModified = dateTime,
  780. HourlyWage = 1
  781. }));
  782. list.Add(new KeyValuePair<string, WagePerson>("key2", new WagePerson
  783. {
  784. BirthDate = dateTime,
  785. Department = "Department2",
  786. LastModified = dateTime,
  787. HourlyWage = 2
  788. }));
  789. string json = JsonConvert.SerializeObject(list, Formatting.Indented);
  790. StringAssert.AreEqual(@"[
  791. {
  792. ""Key"": ""key1"",
  793. ""Value"": {
  794. ""HourlyWage"": 1.0,
  795. ""Name"": null,
  796. ""BirthDate"": ""2000-12-01T23:01:01Z"",
  797. ""LastModified"": ""2000-12-01T23:01:01Z""
  798. }
  799. },
  800. {
  801. ""Key"": ""key2"",
  802. ""Value"": {
  803. ""HourlyWage"": 2.0,
  804. ""Name"": null,
  805. ""BirthDate"": ""2000-12-01T23:01:01Z"",
  806. ""LastModified"": ""2000-12-01T23:01:01Z""
  807. }
  808. }
  809. ]", json);
  810. List<KeyValuePair<string, WagePerson>> result = JsonConvert.DeserializeObject<List<KeyValuePair<string, WagePerson>>>(json);
  811. Assert.AreEqual(2, result.Count);
  812. Assert.AreEqual("key1", result[0].Key);
  813. Assert.AreEqual(1, result[0].Value.HourlyWage);
  814. Assert.AreEqual("key2", result[1].Key);
  815. Assert.AreEqual(2, result[1].Value.HourlyWage);
  816. }
  817. [Test]
  818. public void StringListAppenderConverterTest()
  819. {
  820. Movie p = new Movie();
  821. p.ReleaseCountries = new List<string> { "Existing" };
  822. JsonConvert.PopulateObject("{'ReleaseCountries':['Appended']}", p, new JsonSerializerSettings
  823. {
  824. Converters = new List<JsonConverter> { new StringListAppenderConverter() }
  825. });
  826. Assert.AreEqual(2, p.ReleaseCountries.Count);
  827. Assert.AreEqual("Existing", p.ReleaseCountries[0]);
  828. Assert.AreEqual("Appended", p.ReleaseCountries[1]);
  829. }
  830. [Test]
  831. public void StringAppenderConverterTest()
  832. {
  833. Movie p = new Movie();
  834. p.Name = "Existing,";
  835. JsonConvert.PopulateObject("{'Name':'Appended'}", p, new JsonSerializerSettings
  836. {
  837. Converters = new List<JsonConverter> { new StringAppenderConverter() }
  838. });
  839. Assert.AreEqual("Existing,Appended", p.Name);
  840. }
  841. [Test]
  842. public void DeserializeIDictionary()
  843. {
  844. IDictionary dictionary = JsonConvert.DeserializeObject<IDictionary>("{'name':'value!'}");
  845. Assert.AreEqual(1, dictionary.Count);
  846. Assert.AreEqual("value!", dictionary["name"]);
  847. }
  848. [Test]
  849. public void DeserializeIList()
  850. {
  851. IList list = JsonConvert.DeserializeObject<IList>("['1', 'two', 'III']");
  852. Assert.AreEqual(3, list.Count);
  853. }
  854. [Test]
  855. public void NullableValueGenericDictionary()
  856. {
  857. IDictionary<string, int?> v1 = new Dictionary<string, int?>
  858. {
  859. { "First", 1 },
  860. { "Second", null },
  861. { "Third", 3 }
  862. };
  863. string json = JsonConvert.SerializeObject(v1, Formatting.Indented);
  864. StringAssert.AreEqual(@"{
  865. ""First"": 1,
  866. ""Second"": null,
  867. ""Third"": 3
  868. }", json);
  869. IDictionary<string, int?> v2 = JsonConvert.DeserializeObject<IDictionary<string, int?>>(json);
  870. Assert.AreEqual(3, v2.Count);
  871. Assert.AreEqual(1, v2["First"]);
  872. Assert.AreEqual(null, v2["Second"]);
  873. Assert.AreEqual(3, v2["Third"]);
  874. }
  875. #if !(NET35 || NET20 || PORTABLE || PORTABLE40)
  876. [Test]
  877. public void DeserializeConcurrentDictionary()
  878. {
  879. IDictionary<string, TestObjects.Component> components = new Dictionary<string, TestObjects.Component>
  880. {
  881. { "Key!", new TestObjects.Component() }
  882. };
  883. GameObject go = new GameObject
  884. {
  885. Components = new ConcurrentDictionary<string, TestObjects.Component>(components),
  886. Id = "Id!",
  887. Name = "Name!"
  888. };
  889. string originalJson = JsonConvert.SerializeObject(go, Formatting.Indented);
  890. StringAssert.AreEqual(@"{
  891. ""Components"": {
  892. ""Key!"": {}
  893. },
  894. ""Id"": ""Id!"",
  895. ""Name"": ""Name!""
  896. }", originalJson);
  897. GameObject newObject = JsonConvert.DeserializeObject<GameObject>(originalJson);
  898. Assert.AreEqual(1, newObject.Components.Count);
  899. Assert.AreEqual("Id!", newObject.Id);
  900. Assert.AreEqual("Name!", newObject.Name);
  901. }
  902. #endif
  903. [Test]
  904. public void DeserializeKeyValuePairArray()
  905. {
  906. string json = @"[ { ""Value"": [ ""1"", ""2"" ], ""Key"": ""aaa"", ""BadContent"": [ 0 ] }, { ""Value"": [ ""3"", ""4"" ], ""Key"": ""bbb"" } ]";
  907. IList<KeyValuePair<string, IList<string>>> values = JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json);
  908. Assert.AreEqual(2, values.Count);
  909. Assert.AreEqual("aaa", values[0].Key);
  910. Assert.AreEqual(2, values[0].Value.Count);
  911. Assert.AreEqual("1", values[0].Value[0]);
  912. Assert.AreEqual("2", values[0].Value[1]);
  913. Assert.AreEqual("bbb", values[1].Key);
  914. Assert.AreEqual(2, values[1].Value.Count);
  915. Assert.AreEqual("3", values[1].Value[0]);
  916. Assert.AreEqual("4", values[1].Value[1]);
  917. }
  918. [Test]
  919. public void DeserializeNullableKeyValuePairArray()
  920. {
  921. string json = @"[ { ""Value"": [ ""1"", ""2"" ], ""Key"": ""aaa"", ""BadContent"": [ 0 ] }, null, { ""Value"": [ ""3"", ""4"" ], ""Key"": ""bbb"" } ]";
  922. IList<KeyValuePair<string, IList<string>>?> values = JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>?>>(json);
  923. Assert.AreEqual(3, values.Count);
  924. Assert.AreEqual("aaa", values[0].Value.Key);
  925. Assert.AreEqual(2, values[0].Value.Value.Count);
  926. Assert.AreEqual("1", values[0].Value.Value[0]);
  927. Assert.AreEqual("2", values[0].Value.Value[1]);
  928. Assert.AreEqual(null, values[1]);
  929. Assert.AreEqual("bbb", values[2].Value.Key);
  930. Assert.AreEqual(2, values[2].Value.Value.Count);
  931. Assert.AreEqual("3", values[2].Value.Value[0]);
  932. Assert.AreEqual("4", values[2].Value.Value[1]);
  933. }
  934. [Test]
  935. public void DeserializeNullToNonNullableKeyValuePairArray()
  936. {
  937. string json = @"[ null ]";
  938. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json); }, "Cannot convert null value to KeyValuePair. Path '[0]', line 1, position 6.");
  939. }
  940. #if !(NET40 || NET35 || NET20 || PORTABLE40)
  941. public class PopulateReadOnlyTestClass
  942. {
  943. public IList<int> NonReadOnlyList { get; set; }
  944. public IDictionary<string, int> NonReadOnlyDictionary { get; set; }
  945. public IList<int> Array { get; set; }
  946. public IList<int> List { get; set; }
  947. public IDictionary<string, int> Dictionary { get; set; }
  948. public IReadOnlyCollection<int> IReadOnlyCollection { get; set; }
  949. public ReadOnlyCollection<int> ReadOnlyCollection { get; set; }
  950. public IReadOnlyList<int> IReadOnlyList { get; set; }
  951. public IReadOnlyDictionary<string, int> IReadOnlyDictionary { get; set; }
  952. public ReadOnlyDictionary<string, int> ReadOnlyDictionary { get; set; }
  953. public PopulateReadOnlyTestClass()
  954. {
  955. NonReadOnlyList = new List<int> { 1 };
  956. NonReadOnlyDictionary = new Dictionary<string, int> { { "first", 2 } };
  957. Array = new[] { 3 };
  958. List = new ReadOnlyCollection<int>(new[] { 4 });
  959. Dictionary = new ReadOnlyDictionary<string, int>(new Dictionary<string, int> { { "first", 5 } });
  960. IReadOnlyCollection = new ReadOnlyCollection<int>(new[] { 6 });
  961. ReadOnlyCollection = new ReadOnlyCollection<int>(new[] { 7 });
  962. IReadOnlyList = new ReadOnlyCollection<int>(new[] { 8 });
  963. IReadOnlyDictionary = new ReadOnlyDictionary<string, int>(new Dictionary<string, int> { { "first", 9 } });
  964. ReadOnlyDictionary = new ReadOnlyDictionary<string, int>(new Dictionary<string, int> { { "first", 10 } });
  965. }
  966. }
  967. [Test]
  968. public void SerializeReadOnlyCollections()
  969. {
  970. PopulateReadOnlyTestClass c1 = new PopulateReadOnlyTestClass();
  971. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  972. StringAssert.AreEqual(@"{
  973. ""NonReadOnlyList"": [
  974. 1
  975. ],
  976. ""NonReadOnlyDictionary"": {
  977. ""first"": 2
  978. },
  979. ""Array"": [
  980. 3
  981. ],
  982. ""List"": [
  983. 4
  984. ],
  985. ""Dictionary"": {
  986. ""first"": 5
  987. },
  988. ""IReadOnlyCollection"": [
  989. 6
  990. ],
  991. ""ReadOnlyCollection"": [
  992. 7
  993. ],
  994. ""IReadOnlyList"": [
  995. 8
  996. ],
  997. ""IReadOnlyDictionary"": {
  998. ""first"": 9
  999. },
  1000. ""ReadOnlyDictionary"": {
  1001. ""first"": 10
  1002. }
  1003. }", json);
  1004. }
  1005. [Test]
  1006. public void PopulateReadOnlyCollections()
  1007. {
  1008. string json = @"{
  1009. ""NonReadOnlyList"": [
  1010. 11
  1011. ],
  1012. ""NonReadOnlyDictionary"": {
  1013. ""first"": 12
  1014. },
  1015. ""Array"": [
  1016. 13
  1017. ],
  1018. ""List"": [
  1019. 14
  1020. ],
  1021. ""Dictionary"": {
  1022. ""first"": 15
  1023. },
  1024. ""IReadOnlyCollection"": [
  1025. 16
  1026. ],
  1027. ""ReadOnlyCollection"": [
  1028. 17
  1029. ],
  1030. ""IReadOnlyList"": [
  1031. 18
  1032. ],
  1033. ""IReadOnlyDictionary"": {
  1034. ""first"": 19
  1035. },
  1036. ""ReadOnlyDictionary"": {
  1037. ""first"": 20
  1038. }
  1039. }";
  1040. var c2 = JsonConvert.DeserializeObject<PopulateReadOnlyTestClass>(json);
  1041. Assert.AreEqual(1, c2.NonReadOnlyDictionary.Count);
  1042. Assert.AreEqual(12, c2.NonReadOnlyDictionary["first"]);
  1043. Assert.AreEqual(2, c2.NonReadOnlyList.Count);
  1044. Assert.AreEqual(1, c2.NonReadOnlyList[0]);
  1045. Assert.AreEqual(11, c2.NonReadOnlyList[1]);
  1046. Assert.AreEqual(1, c2.Array.Count);
  1047. Assert.AreEqual(13, c2.Array[0]);
  1048. }
  1049. #endif
  1050. [Test]
  1051. public void SerializeArray2D()
  1052. {
  1053. Array2D aa = new Array2D();
  1054. aa.Before = "Before!";
  1055. aa.After = "After!";
  1056. aa.Coordinates = new[,] { { 1, 1 }, { 1, 2 }, { 2, 1 }, { 2, 2 } };
  1057. string json = JsonConvert.SerializeObject(aa);
  1058. Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}", json);
  1059. }
  1060. [Test]
  1061. public void SerializeArray3D()
  1062. {
  1063. Array3D aa = new Array3D();
  1064. aa.Before = "Before!";
  1065. aa.After = "After!";
  1066. aa.Coordinates = new[,,] { { { 1, 1, 1 }, { 1, 1, 2 } }, { { 1, 2, 1 }, { 1, 2, 2 } }, { { 2, 1, 1 }, { 2, 1, 2 } }, { { 2, 2, 1 }, { 2, 2, 2 } } };
  1067. string json = JsonConvert.SerializeObject(aa);
  1068. Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1,2]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],[2,2,2]]],""After"":""After!""}", json);
  1069. }
  1070. [Test]
  1071. public void SerializeArray3DWithConverter()
  1072. {
  1073. Array3DWithConverter aa = new Array3DWithConverter();
  1074. aa.Before = "Before!";
  1075. aa.After = "After!";
  1076. aa.Coordinates = new[,,] { { { 1, 1, 1 }, { 1, 1, 2 } }, { { 1, 2, 1 }, { 1, 2, 2 } }, { { 2, 1, 1 }, { 2, 1, 2 } }, { { 2, 2, 1 }, { 2, 2, 2 } } };
  1077. string json = JsonConvert.SerializeObject(aa, Formatting.Indented);
  1078. StringAssert.AreEqual(@"{
  1079. ""Before"": ""Before!"",
  1080. ""Coordinates"": [
  1081. [
  1082. [
  1083. 1.0,
  1084. 1.0,
  1085. 1.0
  1086. ],
  1087. [
  1088. 1.0,
  1089. 1.0,
  1090. 2.0
  1091. ]
  1092. ],
  1093. [
  1094. [
  1095. 1.0,
  1096. 2.0,
  1097. 1.0
  1098. ],
  1099. [
  1100. 1.0,
  1101. 2.0,
  1102. 2.0
  1103. ]
  1104. ],
  1105. [
  1106. [
  1107. 2.0,
  1108. 1.0,
  1109. 1.0
  1110. ],
  1111. [
  1112. 2.0,
  1113. 1.0,
  1114. 2.0
  1115. ]
  1116. ],
  1117. [
  1118. [
  1119. 2.0,
  1120. 2.0,
  1121. 1.0
  1122. ],
  1123. [
  1124. 2.0,
  1125. 2.0,
  1126. 2.0
  1127. ]
  1128. ]
  1129. ],
  1130. ""After"": ""After!""
  1131. }", json);
  1132. }
  1133. [Test]
  1134. public void DeserializeArray3DWithConverter()
  1135. {
  1136. string json = @"{
  1137. ""Before"": ""Before!"",
  1138. ""Coordinates"": [
  1139. [
  1140. [
  1141. 1.0,
  1142. 1.0,
  1143. 1.0
  1144. ],
  1145. [
  1146. 1.0,
  1147. 1.0,
  1148. 2.0
  1149. ]
  1150. ],
  1151. [
  1152. [
  1153. 1.0,
  1154. 2.0,
  1155. 1.0
  1156. ],
  1157. [
  1158. 1.0,
  1159. 2.0,
  1160. 2.0
  1161. ]
  1162. ],
  1163. [
  1164. [
  1165. 2.0,
  1166. 1.0,
  1167. 1.0
  1168. ],
  1169. [
  1170. 2.0,
  1171. 1.0,
  1172. 2.0
  1173. ]
  1174. ],
  1175. [
  1176. [
  1177. 2.0,
  1178. 2.0,
  1179. 1.0
  1180. ],
  1181. [
  1182. 2.0,
  1183. 2.0,
  1184. 2.0
  1185. ]
  1186. ]
  1187. ],
  1188. ""After"": ""After!""
  1189. }";
  1190. Array3DWithConverter aa = JsonConvert.DeserializeObject<Array3DWithConverter>(json);
  1191. Assert.AreEqual("Before!", aa.Before);
  1192. Assert.AreEqual("After!", aa.After);
  1193. Assert.AreEqual(4, aa.Coordinates.GetLength(0));
  1194. Assert.AreEqual(2, aa.Coordinates.GetLength(1));
  1195. Assert.AreEqual(3, aa.Coordinates.GetLength(2));
  1196. Assert.AreEqual(1, aa.Coordinates[0, 0, 0]);
  1197. Assert.AreEqual(2, aa.Coordinates[1, 1, 1]);
  1198. }
  1199. [Test]
  1200. public void DeserializeArray2D()
  1201. {
  1202. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}";
  1203. Array2D aa = JsonConvert.DeserializeObject<Array2D>(json);
  1204. Assert.AreEqual("Before!", aa.Before);
  1205. Assert.AreEqual("After!", aa.After);
  1206. Assert.AreEqual(4, aa.Coordinates.GetLength(0));
  1207. Assert.AreEqual(2, aa.Coordinates.GetLength(1));
  1208. Assert.AreEqual(1, aa.Coordinates[0, 0]);
  1209. Assert.AreEqual(2, aa.Coordinates[1, 1]);
  1210. string after = JsonConvert.SerializeObject(aa);
  1211. Assert.AreEqual(json, after);
  1212. }
  1213. [Test]
  1214. public void DeserializeArray2D_WithTooManyItems()
  1215. {
  1216. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2,3],[2,1],[2,2]],""After"":""After!""}";
  1217. ExceptionAssert.Throws<Exception>(() => JsonConvert.DeserializeObject<Array2D>(json), "Cannot deserialize non-cubical array as multidimensional array.");
  1218. }
  1219. [Test]
  1220. public void DeserializeArray2D_WithTooFewItems()
  1221. {
  1222. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1],[2,1],[2,2]],""After"":""After!""}";
  1223. ExceptionAssert.Throws<Exception>(() => JsonConvert.DeserializeObject<Array2D>(json), "Cannot deserialize non-cubical array as multidimensional array.");
  1224. }
  1225. [Test]
  1226. public void DeserializeArray3D()
  1227. {
  1228. string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1,2]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],[2,2,2]]],""After"":""After!""}";
  1229. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  1230. Assert.AreEqual("Before!", aa.Before);
  1231. Assert.AreEqual("After!", aa.After);
  1232. Assert.AreEqual(4, aa.Coordinates.GetLength(0));
  1233. Assert.AreEqual(2, aa.Coordinates.GetLength(1));
  1234. Assert.AreEqual(3, aa.Coordinates.GetLength(2));
  1235. Assert.AreEqual(1, aa.Coordinates[0, 0, 0]);
  1236. Assert.AreEqual(2, aa.Coordinates[1, 1, 1]);
  1237. string after = JsonConvert.SerializeObject(aa);
  1238. Assert.AreEqual(json, after);
  1239. }
  1240. [Test]
  1241. public void DeserializeArray3D_WithTooManyItems()
  1242. {
  1243. string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1,2,1]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],[2,2,2]]],""After"":""After!""}";
  1244. ExceptionAssert.Throws<Exception>(() => JsonConvert.DeserializeObject<Array3D>(json), "Cannot deserialize non-cubical array as multidimensional array.");
  1245. }
  1246. [Test]
  1247. public void DeserializeArray3D_WithBadItems()
  1248. {
  1249. string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1,2]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],{}]],""After"":""After!""}";
  1250. ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<Array3D>(json), "Unexpected token when deserializing multidimensional array: StartObject. Path 'Coordinates[3][1]', line 1, position 99.");
  1251. }
  1252. [Test]
  1253. public void DeserializeArray3D_WithTooFewItems()
  1254. {
  1255. string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],[2,2,2]]],""After"":""After!""}";
  1256. ExceptionAssert.Throws<Exception>(() => JsonConvert.DeserializeObject<Array3D>(json), "Cannot deserialize non-cubical array as multidimensional array.");
  1257. }
  1258. [Test]
  1259. public void SerializeEmpty3DArray()
  1260. {
  1261. Array3D aa = new Array3D();
  1262. aa.Before = "Before!";
  1263. aa.After = "After!";
  1264. aa.Coordinates = new int[0, 0, 0];
  1265. string json = JsonConvert.SerializeObject(aa);
  1266. Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[],""After"":""After!""}", json);
  1267. }
  1268. [Test]
  1269. public void DeserializeEmpty3DArray()
  1270. {
  1271. string json = @"{""Before"":""Before!"",""Coordinates"":[],""After"":""After!""}";
  1272. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  1273. Assert.AreEqual("Before!", aa.Before);
  1274. Assert.AreEqual("After!", aa.After);
  1275. Assert.AreEqual(0, aa.Coordinates.GetLength(0));
  1276. Assert.AreEqual(0, aa.Coordinates.GetLength(1));
  1277. Assert.AreEqual(0, aa.Coordinates.GetLength(2));
  1278. string after = JsonConvert.SerializeObject(aa);
  1279. Assert.AreEqual(json, after);
  1280. }
  1281. [Test]
  1282. public void DeserializeIncomplete3DArray()
  1283. {
  1284. string json = @"{""Before"":""Before!"",""Coordinates"":[/*hi*/[/*hi*/[1/*hi*/,/*hi*/1/*hi*/,1]/*hi*/,/*hi*/[1,1";
  1285. ExceptionAssert.Throws<JsonException>(() => JsonConvert.DeserializeObject<Array3D>(json));
  1286. }
  1287. [Test]
  1288. public void DeserializeIncompleteNotTopLevel3DArray()
  1289. {
  1290. string json = @"{""Before"":""Before!"",""Coordinates"":[/*hi*/[/*hi*/";
  1291. ExceptionAssert.Throws<JsonException>(() => JsonConvert.DeserializeObject<Array3D>(json));
  1292. }
  1293. [Test]
  1294. public void DeserializeNull3DArray()
  1295. {
  1296. string json = @"{""Before"":""Before!"",""Coordinates"":null,""After"":""After!""}";
  1297. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  1298. Assert.AreEqual("Before!", aa.Before);
  1299. Assert.AreEqual("After!", aa.After);
  1300. Assert.AreEqual(null, aa.Coordinates);
  1301. string after = JsonConvert.SerializeObject(aa);
  1302. Assert.AreEqual(json, after);
  1303. }
  1304. [Test]
  1305. public void DeserializeSemiEmpty3DArray()
  1306. {
  1307. string json = @"{""Before"":""Before!"",""Coordinates"":[[]],""After"":""After!""}";
  1308. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  1309. Assert.AreEqual("Before!", aa.Before);
  1310. Assert.AreEqual("After!", aa.After);
  1311. Assert.AreEqual(1, aa.Coordinates.GetLength(0));
  1312. Assert.AreEqual(0, aa.Coordinates.GetLength(1));
  1313. Assert.AreEqual(0, aa.Coordinates.GetLength(2));
  1314. string after = JsonConvert.SerializeObject(aa);
  1315. Assert.AreEqual(json, after);
  1316. }
  1317. [Test]
  1318. public void SerializeReferenceTracked3DArray()
  1319. {
  1320. Event1 e1 = new Event1
  1321. {
  1322. EventName = "EventName!"
  1323. };
  1324. Event1[,] array1 = new[,] { { e1, e1 }, { e1, e1 } };
  1325. IList<Event1[,]> values1 = new List<Event1[,]>
  1326. {
  1327. array1,
  1328. array1
  1329. };
  1330. string json = JsonConvert.SerializeObject(values1, new JsonSerializerSettings
  1331. {
  1332. PreserveReferencesHandling = PreserveReferencesHandling.All,
  1333. Formatting = Formatting.Indented
  1334. });
  1335. StringAssert.AreEqual(@"{
  1336. ""$id"": ""1"",
  1337. ""$values"": [
  1338. {
  1339. ""$id"": ""2"",
  1340. ""$values"": [
  1341. [
  1342. {
  1343. ""$id"": ""3"",
  1344. ""EventName"": ""EventName!"",
  1345. ""Venue"": null,
  1346. ""Performances"": null
  1347. },
  1348. {
  1349. ""$ref"": ""3""
  1350. }
  1351. ],
  1352. [
  1353. {
  1354. ""$ref"": ""3""
  1355. },
  1356. {
  1357. ""$ref"": ""3""
  1358. }
  1359. ]
  1360. ]
  1361. },
  1362. {
  1363. ""$ref"": ""2""
  1364. }
  1365. ]
  1366. }", json);
  1367. }
  1368. [Test]
  1369. public void SerializeTypeName3DArray()
  1370. {
  1371. Event1 e1 = new Event1
  1372. {
  1373. EventName = "EventName!"
  1374. };
  1375. Event1[,] array1 = new[,] { { e1, e1 }, { e1, e1 } };
  1376. IList<Event1[,]> values1 = new List<Event1[,]>
  1377. {
  1378. array1,
  1379. array1
  1380. };
  1381. string json = JsonConvert.SerializeObject(values1, new JsonSerializerSettings
  1382. {
  1383. TypeNameHandling = TypeNameHandling.All,
  1384. Formatting = Formatting.Indented
  1385. });
  1386. StringAssert.AreEqual(@"{
  1387. ""$type"": """ + ReflectionUtils.GetTypeName(typeof(List<Event1[,]>), 0, DefaultSerializationBinder.Instance) + @""",
  1388. ""$values"": [
  1389. {
  1390. ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Events.Event1[,], Newtonsoft.Json.Tests"",
  1391. ""$values"": [
  1392. [
  1393. {
  1394. ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Events.Event1, Newtonsoft.Json.Tests"",
  1395. ""EventName"": ""EventName!"",
  1396. ""Venue"": null,
  1397. ""Performances"": null
  1398. },
  1399. {
  1400. ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Events.Event1, Newtonsoft.Json.Tests"",
  1401. ""EventName"": ""EventName!"",
  1402. ""Venue"": null,
  1403. ""Performances"": null
  1404. }
  1405. ],
  1406. [
  1407. {
  1408. ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Events.Event1, Newtonsoft.Json.Tests"",
  1409. ""EventName"": ""EventName!"",
  1410. ""Venue"": null,
  1411. ""Performances"": null
  1412. },
  1413. {
  1414. ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Events.Event1, Newtonsoft.Json.Tests"",
  1415. ""EventName"": ""EventName!"",
  1416. ""Venue"": null,
  1417. ""Performances"": null
  1418. }
  1419. ]
  1420. ]
  1421. },
  1422. {
  1423. ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Events.Event1[,], Newtonsoft.Json.Tests"",
  1424. ""$values"": [
  1425. [
  1426. {
  1427. ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Events.Event1, Newtonsoft.Json.Tests"",
  1428. ""EventName"": ""EventName!"",
  1429. ""Venue"": null,
  1430. ""Performances"": null
  1431. },
  1432. {
  1433. ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Events.Event1, Newtonsoft.Json.Tests"",
  1434. ""EventName"": ""EventName!"",
  1435. ""Venue"": null,
  1436. ""Performances"": null
  1437. }
  1438. ],
  1439. [
  1440. {
  1441. ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Events.Event1, Newtonsoft.Json.Tests"",
  1442. ""EventName"": ""EventName!"",
  1443. ""Venue"": null,
  1444. ""Performances"": null
  1445. },
  1446. {
  1447. ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Events.Event1, Newtonsoft.Json.Tests"",
  1448. ""EventName"": ""EventName!"",
  1449. ""Venue"": null,
  1450. ""Performances"": null
  1451. }
  1452. ]
  1453. ]
  1454. }
  1455. ]
  1456. }", json);
  1457. IList<Event1[,]> values2 = (IList<Event1[,]>)JsonConvert.DeserializeObject(json, new JsonSerializerSettings
  1458. {
  1459. TypeNameHandling = TypeNameHandling.All
  1460. });
  1461. Assert.AreEqual(2, values2.Count);
  1462. Assert.AreEqual("EventName!", values2[0][0, 0].EventName);
  1463. }
  1464. [Test]
  1465. public void PrimitiveValuesInObjectArray()
  1466. {
  1467. string json = @"{""action"":""Router"",""method"":""Navigate"",""data"":[""dashboard"",null],""type"":""rpc"",""tid"":2}";
  1468. ObjectArrayPropertyTest o = JsonConvert.DeserializeObject<ObjectArrayPropertyTest>(json);
  1469. Assert.AreEqual("Router", o.Action);
  1470. Assert.AreEqual("Navigate", o.Method);
  1471. Assert.AreEqual(2, o.Data.Length);
  1472. Assert.AreEqual("dashboard", o.Data[0]);
  1473. Assert.AreEqual(null, o.Data[1]);
  1474. }
  1475. [Test]
  1476. public void ComplexValuesInObjectArray()
  1477. {
  1478. string json = @"{""action"":""Router"",""method"":""Navigate"",""data"":[""dashboard"",[""id"", 1, ""teststring"", ""test""],{""one"":1}],""type"":""rpc"",""tid"":2}";
  1479. ObjectArrayPropertyTest o = JsonConvert.DeserializeObject<ObjectArrayPropertyTest>(json);
  1480. Assert.AreEqual("Router", o.Action);
  1481. Assert.AreEqual("Navigate", o.Method);
  1482. Assert.AreEqual(3, o.Data.Length);
  1483. Assert.AreEqual("dashboard", o.Data[0]);
  1484. CustomAssert.IsInstanceOfType(typeof(JArray), o.Data[1]);
  1485. Assert.AreEqual(4, ((JArray)o.Data[1]).Count);
  1486. CustomAssert.IsInstanceOfType(typeof(JObject), o.Data[2]);
  1487. Assert.AreEqual(1, ((JObject)o.Data[2]).Count);
  1488. Assert.AreEqual(1, (int)((JObject)o.Data[2])["one"]);
  1489. }
  1490. #if !(DNXCORE50)
  1491. [Test]
  1492. public void SerializeArrayAsArrayList()
  1493. {
  1494. string jsonText = @"[3, ""somestring"",[1,2,3],{}]";
  1495. ArrayList o = JsonConvert.DeserializeObject<ArrayList>(jsonText);
  1496. Assert.AreEqual(4, o.Count);
  1497. Assert.AreEqual(3, ((JArray)o[2]).Count);
  1498. Assert.AreEqual(0, ((JObject)o[3]).Count);
  1499. }
  1500. #endif
  1501. [Test]
  1502. public void SerializeMemberGenericList()
  1503. {
  1504. Name name = new Name("The Idiot in Next To Me");
  1505. PhoneNumber p1 = new PhoneNumber("555-1212");
  1506. PhoneNumber p2 = new PhoneNumber("444-1212");
  1507. name.pNumbers.Add(p1);
  1508. name.pNumbers.Add(p2);
  1509. string json = JsonConvert.SerializeObject(name, Formatting.Indented);
  1510. StringAssert.AreEqual(@"{
  1511. ""personsName"": ""The Idiot in Next To Me"",
  1512. ""pNumbers"": [
  1513. {
  1514. ""phoneNumber"": ""555-1212""
  1515. },
  1516. {
  1517. ""phoneNumber"": ""444-1212""
  1518. }
  1519. ]
  1520. }", json);
  1521. Name newName = JsonConvert.DeserializeObject<Name>(json);
  1522. Assert.AreEqual("The Idiot in Next To Me", newName.personsName);
  1523. // not passed in as part of the constructor but assigned to pNumbers property
  1524. Assert.AreEqual(2, newName.pNumbers.Count);
  1525. Assert.AreEqual("555-1212", newName.pNumbers[0].phoneNumber);
  1526. Assert.AreEqual("444-1212", newName.pNumbers[1].phoneNumber);
  1527. }
  1528. [Test]
  1529. public void CustomCollectionSerialization()
  1530. {
  1531. ProductCollection collection = new ProductCollection()
  1532. {
  1533. new Product() { Name = "Test1" },
  1534. new Product() { Name = "Test2" },
  1535. new Product() { Name = "Test3" }
  1536. };
  1537. JsonSerializer jsonSerializer = new JsonSerializer();
  1538. jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  1539. StringWriter sw = new StringWriter();
  1540. jsonSerializer.Serialize(sw, collection);
  1541. Assert.AreEqual(@"[{""Name"":""Test1"",""ExpiryDate"":""2000-01-01T00:00:00Z"",""Price"":0.0,""Sizes"":null},{""Name"":""Test2"",""ExpiryDate"":""2000-01-01T00:00:00Z"",""Price"":0.0,""Sizes"":null},{""Name"":""Test3"",""ExpiryDate"":""2000-01-01T00:00:00Z"",""Price"":0.0,""Sizes"":null}]",
  1542. sw.GetStringBuilder().ToString());
  1543. ProductCollection collectionNew = (ProductCollection)jsonSerializer.Deserialize(new JsonTextReader(new StringReader(sw.GetStringBuilder().ToString())), typeof(ProductCollection));
  1544. CollectionAssert.AreEqual(collection, collectionNew);
  1545. }
  1546. [Test]
  1547. public void GenericCollectionInheritance()
  1548. {
  1549. string json;
  1550. GenericClass<GenericItem<string>, string> foo1 = new GenericClass<GenericItem<string>, string>();
  1551. foo1.Items.Add(new GenericItem<string> { Value = "Hello" });
  1552. json = JsonConvert.SerializeObject(new { selectList = foo1 });
  1553. Assert.AreEqual(@"{""selectList"":[{""Value"":""Hello""}]}", json);
  1554. GenericClass<NonGenericItem, string> foo2 = new GenericClass<NonGenericItem, string>();
  1555. foo2.Items.Add(new NonGenericItem { Value = "Hello" });
  1556. json = JsonConvert.SerializeObject(new { selectList = foo2 });
  1557. Assert.AreEqual(@"{""selectList"":[{""Value"":""Hello""}]}", json);
  1558. NonGenericClass foo3 = new NonGenericClass();
  1559. foo3.Items.Add(new NonGenericItem { Value = "Hello" });
  1560. json = JsonConvert.SerializeObject(new { selectList = foo3 });
  1561. Assert.AreEqual(@"{""selectList"":[{""Value"":""Hello""}]}", json);
  1562. }
  1563. [Test]
  1564. public void InheritedListSerialize()
  1565. {
  1566. Article a1 = new Article("a1");
  1567. Article a2 = new Article("a2");
  1568. ArticleCollection articles1 = new ArticleCollection();
  1569. articles1.Add(a1);
  1570. articles1.Add(a2);
  1571. string jsonText = JsonConvert.SerializeObject(articles1);
  1572. ArticleCollection articles2 = JsonConvert.DeserializeObject<ArticleCollection>(jsonText);
  1573. Assert.AreEqual(articles1.Count, articles2.Count);
  1574. Assert.AreEqual(articles1[0].Name, articles2[0].Name);
  1575. }
  1576. [Test]
  1577. public void ReadOnlyCollectionSerialize()
  1578. {
  1579. ReadOnlyCollection<int> r1 = new ReadOnlyCollection<int>(new int[] { 0, 1, 2, 3, 4 });
  1580. string jsonText = JsonConvert.SerializeObject(r1);
  1581. Assert.AreEqual("[0,1,2,3,4]", jsonText);
  1582. ReadOnlyCollection<int> r2 = JsonConvert.DeserializeObject<ReadOnlyCollection<int>>(jsonText);
  1583. CollectionAssert.AreEqual(r1, r2);
  1584. }
  1585. [Test]
  1586. public void SerializeGenericList()
  1587. {
  1588. Product p1 = new Product
  1589. {
  1590. Name = "Product 1",
  1591. Price = 99.95m,
  1592. ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
  1593. };
  1594. Product p2 = new Product
  1595. {
  1596. Name = "Product 2",
  1597. Price = 12.50m,
  1598. ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
  1599. };
  1600. List<Product> products = new List<Product>();
  1601. products.Add(p1);
  1602. products.Add(p2);
  1603. string json = JsonConvert.SerializeObject(products, Formatting.Indented);
  1604. //[
  1605. // {
  1606. // "Name": "Product 1",
  1607. // "ExpiryDate": "\/Date(978048000000)\/",
  1608. // "Price": 99.95,
  1609. // "Sizes": null
  1610. // },
  1611. // {
  1612. // "Name": "Product 2",
  1613. // "ExpiryDate": "\/Date(1248998400000)\/",
  1614. // "Price": 12.50,
  1615. // "Sizes": null
  1616. // }
  1617. //]
  1618. StringAssert.AreEqual(@"[
  1619. {
  1620. ""Name"": ""Product 1"",
  1621. ""ExpiryDate"": ""2000-12-29T00:00:00Z"",
  1622. ""Price"": 99.95,
  1623. ""Sizes"": null
  1624. },
  1625. {
  1626. ""Name"": ""Product 2"",
  1627. ""ExpiryDate"": ""2009-07-31T00:00:00Z"",
  1628. ""Price"": 12.50,
  1629. ""Sizes"": null
  1630. }
  1631. ]", json);
  1632. }
  1633. [Test]
  1634. public void DeserializeGenericList()
  1635. {
  1636. string json = @"[
  1637. {
  1638. ""Name"": ""Product 1"",
  1639. ""ExpiryDate"": ""\/Date(978048000000)\/"",
  1640. ""Price"": 99.95,
  1641. ""Sizes"": null
  1642. },
  1643. {
  1644. ""Name"": ""Product 2"",
  1645. ""ExpiryDate"": ""\/Date(1248998400000)\/"",
  1646. ""Price"": 12.50,
  1647. ""Sizes"": null
  1648. }
  1649. ]";
  1650. List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);
  1651. Product p1 = products[0];
  1652. Assert.AreEqual(2, products.Count);
  1653. Assert.AreEqual("Product 1", p1.Name);
  1654. }
  1655. #if !(NET40 || NET35 || NET20 || PORTABLE40)
  1656. [Test]
  1657. public void ReadOnlyIntegerList()
  1658. {
  1659. ReadOnlyIntegerList l = new ReadOnlyIntegerList(new List<int>
  1660. {
  1661. 1,
  1662. 2,
  1663. 3,
  1664. int.MaxValue
  1665. });
  1666. string json = JsonConvert.SerializeObject(l, Formatting.Indented);
  1667. StringAssert.AreEqual(@"[
  1668. 1,
  1669. 2,
  1670. 3,
  1671. 2147483647
  1672. ]", json);
  1673. }
  1674. #endif
  1675. #if !DNXCORE50
  1676. [Test]
  1677. public void EmptyStringInHashtableIsDeserialized()
  1678. {
  1679. string externalJson = @"{""$type"":""System.Collections.Hashtable, mscorlib"",""testkey"":""""}";
  1680. JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
  1681. JsonConvert.SerializeObject(new Hashtable { { "testkey", "" } }, settings);
  1682. Hashtable deserializeTest2 = JsonConvert.DeserializeObject<Hashtable>(externalJson, settings);
  1683. Assert.AreEqual(deserializeTest2["testkey"], "");
  1684. }
  1685. #endif
  1686. [Test]
  1687. public void DeserializeCollectionWithConstructorArrayArgument()
  1688. {
  1689. var v = new ReadOnlyCollectionWithArrayArgument<double>(new[] { -0.014147478859765236, -0.011419606805541858, -0.010038461483676238 });
  1690. var json = JsonConvert.SerializeObject(v);
  1691. ExceptionAssert.Throws<JsonSerializationException>(() =>
  1692. {
  1693. JsonConvert.DeserializeObject<ReadOnlyCollectionWithArrayArgument<double>>(json);
  1694. }, "Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.ReadOnlyCollectionWithArrayArgument`1[System.Double]. Path '', line 1, position 1.");
  1695. }
  1696. #if !NET20 && !PORTABLE40
  1697. [Test]
  1698. public void NonDefaultConstructor_DuplicateKeyInDictionary_Replace()
  1699. {
  1700. string json = @"{ ""user"":""bpan"", ""Person"":{ ""groups"":""replaced!"", ""domain"":""adm"", ""mail"":""bpan@sdu.dk"", ""sn"":""Pan"", ""gn"":""Benzhi"", ""cn"":""Benzhi Pan"", ""eo"":""BQHLJaVTMr0eWsi1jaIut4Ls/pSuMeNEmsWfWsfKo="", ""guid"":""9A38CE8E5B288942A8DA415CF5E687"", ""employeenumber"":""2674"", ""omk1"":""930"", ""language"":""da"" }, ""XMLResponce"":""<?xml version='1.0' encoding='iso-8859-1' ?>\n<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>\n\t<cas:authenticationSuccess>\n\t\t<cas:user>bpan</cas:user>\n\t\t<norEduPerson>\n\t\t\t<groups>FNC-PRI-APP-SUNDB-EDOR-A,FNC-RI-APP-SUB-EDITOR-B</groups>\n\t\t\t<domain>adm</domain>\n\t\t\t<mail>bpan@sdu.dk</mail>\n\t\t\t<sn>Pan</sn>\n\t\t\t<gn>Benzhi</gn>\n\t\t\t<cn>Benzhi Pan</cn>\n\t\t\t<eo>BQHLJaVTMr0eWsi1jaIut4Lsfr/pSuMeNEmsWfWsfKo=</eo>\n\t\t\t<guid>9A38CE8E5B288942A8DA415C2C687</guid>\n\t\t\t<employeenumber>274</employeenumber>\n\t\t\t<omk1>930</omk1>\n\t\t\t<language>da</language>\n\t\t</norEduPerson>\n\t</cas:authenticationSuccess>\n</cas:serviceResponse>\n"", ""Language"":1, ""Groups"":[ ""FNC-PRI-APP-SNDB-EDOR-A"", ""FNC-PI-APP-SUNDB-EDOR-B"" ], ""Domain"":""adm"", ""Mail"":""bpan@sdu.dk"", ""Surname"":""Pan"", ""Givenname"":""Benzhi"", ""CommonName"":""Benzhi Pan"", ""OrganizationName"":null }";
  1701. var result = JsonConvert.DeserializeObject<CASResponce>(json);
  1702. Assert.AreEqual("replaced!", result.Person["groups"]);
  1703. }
  1704. #endif
  1705. [Test]
  1706. public void GenericIListAndOverrideConstructor()
  1707. {
  1708. MyClass deserialized = JsonConvert.DeserializeObject<MyClass>(@"[""apple"", ""monkey"", ""goose""]");
  1709. Assert.AreEqual("apple", deserialized[0]);
  1710. Assert.AreEqual("monkey", deserialized[1]);
  1711. Assert.AreEqual("goose", deserialized[2]);
  1712. }
  1713. public class MyClass : IList<string>
  1714. {
  1715. private List<string> _storage;
  1716. [JsonConstructor]
  1717. private MyClass()
  1718. {
  1719. _storage = new List<string>();
  1720. }
  1721. public MyClass(IEnumerable<string> source)
  1722. {
  1723. _storage = new List<string>(source);
  1724. }
  1725. //Below is generated by VS to implement IList<string>
  1726. public string this[int index]
  1727. {
  1728. get
  1729. {
  1730. return ((IList<string>)_storage)[index];
  1731. }
  1732. set
  1733. {
  1734. ((IList<string>)_storage)[index] = value;
  1735. }
  1736. }
  1737. public int Count
  1738. {
  1739. get
  1740. {
  1741. return ((IList<string>)_storage).Count;
  1742. }
  1743. }
  1744. public bool IsReadOnly
  1745. {
  1746. get
  1747. {
  1748. return ((IList<string>)_storage).IsReadOnly;
  1749. }
  1750. }
  1751. public void Add(string item)
  1752. {
  1753. ((IList<string>)_storage).Add(item);
  1754. }
  1755. public void Clear()
  1756. {
  1757. ((IList<string>)_storage).Clear();
  1758. }
  1759. public bool Contains(string item)
  1760. {
  1761. return ((IList<string>)_storage).Contains(item);
  1762. }
  1763. public void CopyTo(string[] array, int arrayIndex)
  1764. {
  1765. ((IList<string>)_storage).CopyTo(array, arrayIndex);
  1766. }
  1767. public IEnumerator<string> GetEnumerator()
  1768. {
  1769. return ((IList<string>)_storage).GetEnumerator();
  1770. }
  1771. public int IndexOf(string item)
  1772. {
  1773. return ((IList<string>)_storage).IndexOf(item);
  1774. }
  1775. public void Insert(int index, string item)
  1776. {
  1777. ((IList<string>)_storage).Insert(index, item);
  1778. }
  1779. public bool Remove(string item)
  1780. {
  1781. return ((IList<string>)_storage).Remove(item);
  1782. }
  1783. public void RemoveAt(int index)
  1784. {
  1785. ((IList<string>)_storage).RemoveAt(index);
  1786. }
  1787. IEnumerator IEnumerable.GetEnumerator()
  1788. {
  1789. return ((IList<string>)_storage).GetEnumerator();
  1790. }
  1791. }
  1792. }
  1793. #if !NET20 && !PORTABLE40
  1794. public class CASResponce
  1795. {
  1796. //<?xml version='1.0' encoding='iso-8859-1' ?>
  1797. //<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
  1798. // <cas:authenticationSuccess>
  1799. // <cas:user>and</cas:user>
  1800. // <norEduPerson>
  1801. // <groups>IT-service-OD,USR-IT-service,IT-service-udvikling</groups>
  1802. // <domain>adm</domain>
  1803. // <mail>and@sdu.dk</mail>
  1804. // <sn>And</sn>
  1805. // <gn>Anders</gn>
  1806. // <cn>Anders And</cn>
  1807. // <eo>QQT3tKSKjCxQSGsDiR8HTP9L5VsojBvOYyjOu8pwLMA=</eo>
  1808. // <guid>DE423352CC763649B8F2ECF1DA304750</guid>
  1809. // <language>da</language>
  1810. // </norEduPerson>
  1811. // </cas:authenticationSuccess>
  1812. //</cas:serviceResponse>
  1813. // NemID
  1814. //<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
  1815. // <cas:authenticationSuccess>
  1816. // <cas:user>
  1817. // 2903851921
  1818. // </cas:user>
  1819. // </cas:authenticationSuccess>
  1820. //</cas:serviceResponse>
  1821. //WAYF
  1822. //<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
  1823. // <cas:authenticationSuccess>
  1824. // <cas:user>
  1825. // jj@testidp.wayf.dk
  1826. // </cas:user>
  1827. // <norEduPerson>
  1828. // <sn>Jensen</sn>
  1829. // <gn>Jens</gn>
  1830. // <cn>Jens farmer</cn>
  1831. // <eduPersonPrincipalName>jj @testidp.wayf.dk</eduPersonPrincipalName>
  1832. // <mail>jens.jensen @institution.dk</mail>
  1833. // <organizationName>Institution</organizationName>
  1834. // <eduPersonAssurance>2</eduPersonAssurance>
  1835. // <schacPersonalUniqueID>urn:mace:terena.org:schac:personalUniqueID:dk:CPR:0708741234</schacPersonalUniqueID>
  1836. // <eduPersonScopedAffiliation>student @course1.testidp.wayf.dk</eduPersonScopedAffiliation>
  1837. // <eduPersonScopedAffiliation>staff @course1.testidp.wayf.dk</eduPersonScopedAffiliation>
  1838. // <eduPersonScopedAffiliation>staff @course1.testidp.wsayf.dk</eduPersonScopedAffiliation>
  1839. // <preferredLanguage>en</preferredLanguage>
  1840. // <eduPersonEntitlement>test</eduPersonEntitlement>
  1841. // <eduPersonPrimaryAffiliation>student</eduPersonPrimaryAffiliation>
  1842. // <schacCountryOfCitizenship>DK</schacCountryOfCitizenship>
  1843. // <eduPersonTargetedID>WAYF-DK-7a86d1c3b69a9639d7650b64f2eb773bd21a8c6d</eduPersonTargetedID>
  1844. // <schacHomeOrganization>testidp.wayf.dk</schacHomeOrganization>
  1845. // <givenName>Jens</givenName>
  1846. // <o>Institution</o>
  1847. // <idp>https://testbridge.wayf.dk</idp>
  1848. // </norEduPerson>
  1849. // </cas:authenticationSuccess>
  1850. //</cas:serviceResponse>
  1851. public enum ssoLanguage
  1852. {
  1853. Unknown,
  1854. Danish,
  1855. English
  1856. }
  1857. public CASResponce(string xmlResponce)
  1858. {
  1859. this.Domain = "";
  1860. this.Mail = "";
  1861. this.Surname = "";
  1862. this.Givenname = "";
  1863. this.CommonName = "";
  1864. ParseReplyXML(xmlResponce);
  1865. ExtractGroups();
  1866. ExtractLanguage();
  1867. }
  1868. private void ExtractGroups()
  1869. {
  1870. this.Groups = new List<string>();
  1871. if (this.Person.ContainsKey("groups"))
  1872. {
  1873. string groupsString = this.Person["groups"];
  1874. string[] stringList = groupsString.Split(',');
  1875. foreach (string group in stringList)
  1876. {
  1877. this.Groups.Add(group);
  1878. }
  1879. }
  1880. }
  1881. private void ExtractLanguage()
  1882. {
  1883. if (Person.ContainsKey("language"))
  1884. {
  1885. switch (Person["language"].Trim())
  1886. {
  1887. case "da":
  1888. this.Language = ssoLanguage.Danish;
  1889. break;
  1890. case "en":
  1891. this.Language = ssoLanguage.English;
  1892. break;
  1893. default:
  1894. this.Language = ssoLanguage.Unknown;
  1895. break;
  1896. }
  1897. }
  1898. else
  1899. {
  1900. this.Language = ssoLanguage.Unknown;
  1901. }
  1902. }
  1903. private void ParseReplyXML(string xmlString)
  1904. {
  1905. try
  1906. {
  1907. System.Xml.Linq.XDocument xDoc = XDocument.Parse(xmlString);
  1908. var root = xDoc.Root;
  1909. string ns = "http://www.yale.edu/tp/cas";
  1910. XElement auth = root.Element(XName.Get("authenticationSuccess", ns));
  1911. if (auth == null)
  1912. auth = root.Element(XName.Get("authenticationFailure", ns));
  1913. XElement xNodeUser = auth.Element(XName.Get("user", ns));
  1914. XElement eduPers = auth.Element(XName.Get("norEduPerson", ""));
  1915. string casUser = "";
  1916. Dictionary<string, string> eduPerson = new Dictionary<string, string>();
  1917. if (xNodeUser != null)
  1918. {
  1919. casUser = xNodeUser.Value;
  1920. if (eduPers != null)
  1921. {
  1922. foreach (XElement xPersonValue in eduPers.Elements())
  1923. {
  1924. if (!eduPerson.ContainsKey(xPersonValue.Name.LocalName))
  1925. {
  1926. eduPerson.Add(xPersonValue.Name.LocalName, xPersonValue.Value);
  1927. }
  1928. else
  1929. {
  1930. eduPerson[xPersonValue.Name.LocalName] = eduPerson[xPersonValue.Name.LocalName] + ";" + xPersonValue.Value;
  1931. }
  1932. }
  1933. }
  1934. }
  1935. if (casUser.Trim() != "")
  1936. {
  1937. this.user = casUser;
  1938. }
  1939. if (eduPerson.ContainsKey("domain"))
  1940. this.Domain = eduPerson["domain"];
  1941. if (eduPerson.ContainsKey("organizationName"))
  1942. this.OrganizationName = eduPerson["organizationName"];
  1943. if (eduPerson.ContainsKey("mail"))
  1944. this.Mail = eduPerson["mail"];
  1945. if (eduPerson.ContainsKey("sn"))
  1946. this.Surname = eduPerson["sn"];
  1947. if (eduPerson.ContainsKey("gn"))
  1948. this.Givenname = eduPerson["gn"];
  1949. if (eduPerson.ContainsKey("cn"))
  1950. this.CommonName = eduPerson["cn"];
  1951. this.Person = eduPerson;
  1952. this.XMLResponce = xmlString;
  1953. }
  1954. catch
  1955. {
  1956. this.user = "";
  1957. }
  1958. }
  1959. /// <summary>
  1960. /// Fast felt der altid findes.
  1961. /// </summary>
  1962. public string user { get; private set; }
  1963. /// <summary>
  1964. /// Person type som dictionary indeholdende de ekstra informationer returneret ved login.
  1965. /// </summary>
  1966. public Dictionary<string, string> Person { get; private set; }
  1967. /// <summary>
  1968. /// Den oprindelige xml returneret fra CAS.
  1969. /// </summary>
  1970. public string XMLResponce { get; private set; }
  1971. /// <summary>
  1972. /// Det sprog der benyttes i SSO. Muligheder er da eller en.
  1973. /// </summary>
  1974. public ssoLanguage Language { get; private set; }
  1975. /// <summary>
  1976. /// Liste af grupper som man er medlem af. Kun udvalgt iblandt dem der blev puttet ind i systemet.
  1977. /// </summary>
  1978. public List<string> Groups { get; private set; }
  1979. public string Domain { get; private set; }
  1980. public string Mail { get; private set; }
  1981. public string Surname { get; private set; }
  1982. public string Givenname { get; private set; }
  1983. public string CommonName { get; private set; }
  1984. public string OrganizationName { get; private set; }
  1985. }
  1986. #endif
  1987. public class ReadOnlyCollectionWithArrayArgument<T> : IList<T>
  1988. {
  1989. private readonly IList<T> _values;
  1990. public ReadOnlyCollectionWithArrayArgument(T[] args)
  1991. {
  1992. _values = args ?? (IList<T>)new List<T>();
  1993. }
  1994. public IEnumerator<T> GetEnumerator()
  1995. {
  1996. return _values.GetEnumerator();
  1997. }
  1998. IEnumerator IEnumerable.GetEnumerator()
  1999. {
  2000. return _values.GetEnumerator();
  2001. }
  2002. public void Add(T item)
  2003. {
  2004. throw new NotImplementedException();
  2005. }
  2006. public void Clear()
  2007. {
  2008. throw new NotImplementedException();
  2009. }
  2010. public bool Contains(T item)
  2011. {
  2012. throw new NotImplementedException();
  2013. }
  2014. public void CopyTo(T[] array, int arrayIndex)
  2015. {
  2016. throw new NotImplementedException();
  2017. }
  2018. public bool Remove(T item)
  2019. {
  2020. throw new NotImplementedException();
  2021. }
  2022. public int Count { get; }
  2023. public bool IsReadOnly { get; }
  2024. public int IndexOf(T item)
  2025. {
  2026. throw new NotImplementedException();
  2027. }
  2028. public void Insert(int index, T item)
  2029. {
  2030. throw new NotImplementedException();
  2031. }
  2032. public void RemoveAt(int index)
  2033. {
  2034. throw new NotImplementedException();
  2035. }
  2036. public T this[int index]
  2037. {
  2038. get { throw new NotImplementedException(); }
  2039. set { throw new NotImplementedException(); }
  2040. }
  2041. }
  2042. #if !(NET40 || NET35 || NET20 || PORTABLE40)
  2043. public class ReadOnlyIntegerList : IReadOnlyCollection<int>
  2044. {
  2045. private readonly List<int> _list;
  2046. public ReadOnlyIntegerList(List<int> l)
  2047. {
  2048. _list = l;
  2049. }
  2050. public int Count
  2051. {
  2052. get { return _list.Count; }
  2053. }
  2054. public IEnumerator<int> GetEnumerator()
  2055. {
  2056. return _list.GetEnumerator();
  2057. }
  2058. IEnumerator IEnumerable.GetEnumerator()
  2059. {
  2060. return GetEnumerator();
  2061. }
  2062. }
  2063. #endif
  2064. public class Array2D
  2065. {
  2066. public string Before { get; set; }
  2067. public int[,] Coordinates { get; set; }
  2068. public string After { get; set; }
  2069. }
  2070. public class Array3D
  2071. {
  2072. public string Before { get; set; }
  2073. public int[,,] Coordinates { get; set; }
  2074. public string After { get; set; }
  2075. }
  2076. public class Array3DWithConverter
  2077. {
  2078. public string Before { get; set; }
  2079. [JsonProperty(ItemConverterType = typeof(IntToFloatConverter))]
  2080. public int[,,] Coordinates { get; set; }
  2081. public string After { get; set; }
  2082. }
  2083. public class GenericItem<T>
  2084. {
  2085. public T Value { get; set; }
  2086. }
  2087. public class NonGenericItem : GenericItem<string>
  2088. {
  2089. }
  2090. public class GenericClass<T, TValue> : IEnumerable<T>
  2091. where T : GenericItem<TValue>, new()
  2092. {
  2093. public IList<T> Items { get; set; }
  2094. public GenericClass()
  2095. {
  2096. Items = new List<T>();
  2097. }
  2098. public IEnumerator<T> GetEnumerator()
  2099. {
  2100. if (Items != null)
  2101. {
  2102. foreach (T item in Items)
  2103. {
  2104. yield return item;
  2105. }
  2106. }
  2107. else
  2108. {
  2109. yield break;
  2110. }
  2111. }
  2112. IEnumerator IEnumerable.GetEnumerator()
  2113. {
  2114. return GetEnumerator();
  2115. }
  2116. }
  2117. public class NonGenericClass : GenericClass<GenericItem<string>, string>
  2118. {
  2119. }
  2120. public class StringListAppenderConverter : JsonConverter
  2121. {
  2122. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  2123. {
  2124. writer.WriteValue(value);
  2125. }
  2126. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  2127. {
  2128. List<string> existingStrings = (List<string>)existingValue;
  2129. List<string> newStrings = new List<string>(existingStrings);
  2130. reader.Read();
  2131. while (reader.TokenType != JsonToken.EndArray)
  2132. {
  2133. string s = (string)reader.Value;
  2134. newStrings.Add(s);
  2135. reader.Read();
  2136. }
  2137. return newStrings;
  2138. }
  2139. public override bool CanConvert(Type objectType)
  2140. {
  2141. return (objectType == typeof(List<string>));
  2142. }
  2143. }
  2144. public class StringAppenderConverter : JsonConverter
  2145. {
  2146. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  2147. {
  2148. writer.WriteValue(value);
  2149. }
  2150. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  2151. {
  2152. string existingString = (string)existingValue;
  2153. string newString = existingString + (string)reader.Value;
  2154. return newString;
  2155. }
  2156. public override bool CanConvert(Type objectType)
  2157. {
  2158. return (objectType == typeof(string));
  2159. }
  2160. }
  2161. }