PageRenderTime 63ms CodeModel.GetById 24ms 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

Large files files are truncated, but you can click here to view the full file

  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<Array

Large files files are truncated, but you can click here to view the full file