PageRenderTime 128ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 1ms

/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs

https://bitbucket.org/Ecarestia/newtonsoft.json
C# | 10337 lines | 9699 code | 589 blank | 49 comment | 57 complexity | ed917c878c953a32550256444c83dfaa MD5 | raw 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.ComponentModel;
  27. #if !(NET35 || NET20)
  28. using System.Collections.Concurrent;
  29. #endif
  30. using System.Collections.Generic;
  31. #if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
  32. using System.Numerics;
  33. #endif
  34. #if !(NET20 || DNXCORE50)
  35. using System.ComponentModel.DataAnnotations;
  36. using System.Configuration;
  37. using System.Runtime.CompilerServices;
  38. using System.Runtime.Serialization.Formatters;
  39. using System.Threading;
  40. using System.Web.Script.Serialization;
  41. #endif
  42. using System.Text;
  43. using System.Text.RegularExpressions;
  44. #if DNXCORE50
  45. using Xunit;
  46. using Test = Xunit.FactAttribute;
  47. using Assert = Newtonsoft.Json.Tests.XUnitAssert;
  48. #else
  49. using NUnit.Framework;
  50. #endif
  51. using Newtonsoft.Json;
  52. using System.IO;
  53. using System.Collections;
  54. using System.Xml;
  55. using System.Xml.Serialization;
  56. using System.Collections.ObjectModel;
  57. using System.Diagnostics;
  58. using Newtonsoft.Json.Bson;
  59. using Newtonsoft.Json.Linq;
  60. using Newtonsoft.Json.Converters;
  61. #if !(NET20 || NET35)
  62. using System.Runtime.Serialization.Json;
  63. #endif
  64. using Newtonsoft.Json.Serialization;
  65. using Newtonsoft.Json.Tests.Linq;
  66. using Newtonsoft.Json.Tests.TestObjects;
  67. using Newtonsoft.Json.Tests.TestObjects.Events;
  68. using Newtonsoft.Json.Tests.TestObjects.GeoCoding;
  69. using Newtonsoft.Json.Tests.TestObjects.Organization;
  70. using System.Runtime.Serialization;
  71. using System.Globalization;
  72. using Newtonsoft.Json.Utilities;
  73. using System.Reflection;
  74. #if !NET20
  75. using System.Xml.Linq;
  76. using System.Collections.Specialized;
  77. using System.Linq.Expressions;
  78. #endif
  79. #if !(NET35 || NET20)
  80. using System.Dynamic;
  81. #endif
  82. #if NET20
  83. using Newtonsoft.Json.Utilities.LinqBridge;
  84. using Action = Newtonsoft.Json.Serialization.Action;
  85. #else
  86. using System.Linq;
  87. #endif
  88. #if !(DNXCORE50)
  89. using System.Drawing;
  90. #endif
  91. namespace Newtonsoft.Json.Tests.Serialization
  92. {
  93. [TestFixture]
  94. public class JsonSerializerTest : TestFixtureBase
  95. {
  96. public struct ImmutableStruct
  97. {
  98. public ImmutableStruct(string value)
  99. {
  100. Value = value;
  101. Value2 = 0;
  102. }
  103. public string Value { get; }
  104. public int Value2 { get; set; }
  105. }
  106. [Test]
  107. public void DeserializeImmutableStruct()
  108. {
  109. var result = JsonConvert.DeserializeObject<ImmutableStruct>("{ \"Value\": \"working\", \"Value2\": 2 }");
  110. Assert.AreEqual("working", result.Value);
  111. Assert.AreEqual(2, result.Value2);
  112. }
  113. public struct AlmostImmutableStruct
  114. {
  115. public AlmostImmutableStruct(string value, int value2)
  116. {
  117. Value = value;
  118. Value2 = value2;
  119. }
  120. public string Value { get; }
  121. public int Value2 { get; set; }
  122. }
  123. [Test]
  124. public void DeserializeAlmostImmutableStruct()
  125. {
  126. var result = JsonConvert.DeserializeObject<AlmostImmutableStruct>("{ \"Value\": \"working\", \"Value2\": 2 }");
  127. Assert.AreEqual(null, result.Value);
  128. Assert.AreEqual(2, result.Value2);
  129. }
  130. public class ErroringClass
  131. {
  132. public DateTime Tags { get; set; }
  133. }
  134. [Test]
  135. public void DontCloseInputOnDeserializeError()
  136. {
  137. using (var s = System.IO.File.OpenRead("large.json"))
  138. {
  139. try
  140. {
  141. using (JsonTextReader reader = new JsonTextReader(new StreamReader(s)))
  142. {
  143. reader.SupportMultipleContent = true;
  144. reader.CloseInput = false;
  145. // read into array
  146. reader.Read();
  147. var ser = new JsonSerializer();
  148. ser.CheckAdditionalContent = false;
  149. ser.Deserialize<IList<ErroringClass>>(reader);
  150. }
  151. Assert.Fail();
  152. }
  153. catch (Exception)
  154. {
  155. Assert.IsTrue(s.Position > 0);
  156. s.Seek(0, SeekOrigin.Begin);
  157. Assert.AreEqual(0, s.Position);
  158. }
  159. }
  160. }
  161. public interface ISubclassBase
  162. {
  163. int ID { get; set; }
  164. string Name { get; set; }
  165. bool P1 { get; }
  166. }
  167. public interface ISubclass : ISubclassBase
  168. {
  169. new bool P1 { get; set; }
  170. int P2 { get; set; }
  171. }
  172. public interface IMainClass
  173. {
  174. int ID { get; set; }
  175. string Name { get; set; }
  176. ISubclass Subclass { get; set; }
  177. }
  178. public class Subclass : ISubclass
  179. {
  180. public int ID { get; set; }
  181. public string Name { get; set; }
  182. public bool P1 { get; set; }
  183. public int P2 { get; set; }
  184. }
  185. public class MainClass : IMainClass
  186. {
  187. public int ID { get; set; }
  188. public string Name { get; set; }
  189. public ISubclass Subclass { get; set; }
  190. }
  191. public class MyFactory
  192. {
  193. public static ISubclass InstantiateSubclass()
  194. {
  195. return new Subclass
  196. {
  197. ID = 123,
  198. Name = "ABC",
  199. P1 = true,
  200. P2 = 44
  201. };
  202. }
  203. public static IMainClass InstantiateManiClass()
  204. {
  205. return new MainClass
  206. {
  207. ID = 567,
  208. Name = "XYZ",
  209. Subclass = InstantiateSubclass()
  210. };
  211. }
  212. }
  213. [Test]
  214. public void SerializeInterfaceWithHiddenProperties()
  215. {
  216. var mySubclass = MyFactory.InstantiateSubclass();
  217. var myMainClass = MyFactory.InstantiateManiClass();
  218. //Class implementing interface with hidden members - flat object.
  219. var strJsonSubclass = JsonConvert.SerializeObject(mySubclass, Formatting.Indented);
  220. StringAssert.AreEqual(@"{
  221. ""ID"": 123,
  222. ""Name"": ""ABC"",
  223. ""P1"": true,
  224. ""P2"": 44
  225. }", strJsonSubclass);
  226. //Class implementing interface with hidden members - member of another class.
  227. var strJsonMainClass = JsonConvert.SerializeObject(myMainClass, Formatting.Indented);
  228. StringAssert.AreEqual(@"{
  229. ""ID"": 567,
  230. ""Name"": ""XYZ"",
  231. ""Subclass"": {
  232. ""ID"": 123,
  233. ""Name"": ""ABC"",
  234. ""P1"": true,
  235. ""P2"": 44
  236. }
  237. }", strJsonMainClass);
  238. }
  239. [Test]
  240. public void DeserializeGenericIEnumerableWithImplicitConversion()
  241. {
  242. string deserialized = @"{
  243. ""Enumerable"": [ ""abc"", ""def"" ]
  244. }";
  245. var enumerableClass = JsonConvert.DeserializeObject<GenericIEnumerableWithImplicitConversion>(deserialized);
  246. var enumerableObject = enumerableClass.Enumerable.ToArray();
  247. Assert.AreEqual(2, enumerableObject.Length);
  248. Assert.AreEqual("abc", enumerableObject[0].Value);
  249. Assert.AreEqual("def", enumerableObject[1].Value);
  250. }
  251. public class GenericIEnumerableWithImplicitConversion
  252. {
  253. public IEnumerable<ClassWithImplicitOperator> Enumerable { get; set; }
  254. }
  255. public class ClassWithImplicitOperator
  256. {
  257. public string Value { get; set; }
  258. public static implicit operator ClassWithImplicitOperator(string value)
  259. {
  260. return new ClassWithImplicitOperator() { Value = value };
  261. }
  262. }
  263. #if !(PORTABLE || PORTABLE40 || NET20 || NET35)
  264. [Test]
  265. public void LargeIntegerAsString()
  266. {
  267. var largeBrokenNumber = JsonConvert.DeserializeObject<Foo64>("{\"Blah\": 43443333222211111117 }");
  268. Assert.AreEqual("43443333222211111117", largeBrokenNumber.Blah);
  269. var largeOddWorkingNumber = JsonConvert.DeserializeObject<Foo64>("{\"Blah\": 53443333222211111117 }");
  270. Assert.AreEqual("53443333222211111117", largeOddWorkingNumber.Blah);
  271. }
  272. public class Foo64
  273. {
  274. public string Blah { get; set; }
  275. }
  276. #endif
  277. #if !NET20
  278. [Test]
  279. public void DeserializeMSDateTimeOffset()
  280. {
  281. DateTimeOffset d = JsonConvert.DeserializeObject<DateTimeOffset>(@"""/Date(1418924498000+0800)/""");
  282. long initialTicks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(d.DateTime, d.Offset);
  283. Assert.AreEqual(1418924498000, initialTicks);
  284. Assert.AreEqual(8, d.Offset.Hours);
  285. }
  286. #endif
  287. [Test]
  288. public void DeserializeBoolean_Null()
  289. {
  290. ExceptionAssert.Throws<JsonSerializationException>(
  291. () => JsonConvert.DeserializeObject<IList<bool>>(@"[null]"),
  292. "Error converting value {null} to type 'System.Boolean'. Path '[0]', line 1, position 5.");
  293. }
  294. [Test]
  295. public void DeserializeBoolean_DateTime()
  296. {
  297. ExceptionAssert.Throws<JsonReaderException>(
  298. () => JsonConvert.DeserializeObject<IList<bool>>(@"['2000-12-20T10:55:55Z']"),
  299. "Could not convert string to boolean: 2000-12-20T10:55:55Z. Path '[0]', line 1, position 23.");
  300. }
  301. [Test]
  302. public void DeserializeBoolean_BadString()
  303. {
  304. ExceptionAssert.Throws<JsonReaderException>(
  305. () => JsonConvert.DeserializeObject<IList<bool>>(@"['pie']"),
  306. @"Could not convert string to boolean: pie. Path '[0]', line 1, position 6.");
  307. }
  308. [Test]
  309. public void DeserializeBoolean_EmptyString()
  310. {
  311. ExceptionAssert.Throws<JsonSerializationException>(
  312. () => JsonConvert.DeserializeObject<IList<bool>>(@"['']"),
  313. @"Error converting value {null} to type 'System.Boolean'. Path '[0]', line 1, position 3.");
  314. }
  315. #if !(PORTABLE || PORTABLE40 || NET35 || NET20)
  316. [Test]
  317. public void DeserializeBooleans()
  318. {
  319. IList<bool> l = JsonConvert.DeserializeObject<IList<bool>>(@"[
  320. 1,
  321. 0,
  322. 1.1,
  323. 0.0,
  324. 0.000000000001,
  325. 9999999999,
  326. -9999999999,
  327. 9999999999999999999999999999999999999999999999999999999999999999999999,
  328. -9999999999999999999999999999999999999999999999999999999999999999999999,
  329. 'true',
  330. 'TRUE',
  331. 'false',
  332. 'FALSE'
  333. ]");
  334. int i = 0;
  335. Assert.AreEqual(true, l[i++]);
  336. Assert.AreEqual(false, l[i++]);
  337. Assert.AreEqual(true, l[i++]);
  338. Assert.AreEqual(false, l[i++]);
  339. Assert.AreEqual(true, l[i++]);
  340. Assert.AreEqual(true, l[i++]);
  341. Assert.AreEqual(true, l[i++]);
  342. Assert.AreEqual(true, l[i++]);
  343. Assert.AreEqual(true, l[i++]);
  344. Assert.AreEqual(true, l[i++]);
  345. Assert.AreEqual(true, l[i++]);
  346. Assert.AreEqual(false, l[i++]);
  347. Assert.AreEqual(false, l[i++]);
  348. }
  349. [Test]
  350. public void DeserializeNullableBooleans()
  351. {
  352. IList<bool?> l = JsonConvert.DeserializeObject<IList<bool?>>(@"[
  353. 1,
  354. 0,
  355. 1.1,
  356. 0.0,
  357. 0.000000000001,
  358. 9999999999,
  359. -9999999999,
  360. 9999999999999999999999999999999999999999999999999999999999999999999999,
  361. -9999999999999999999999999999999999999999999999999999999999999999999999,
  362. 'true',
  363. 'TRUE',
  364. 'false',
  365. 'FALSE',
  366. '',
  367. null
  368. ]");
  369. int i = 0;
  370. Assert.AreEqual(true, l[i++]);
  371. Assert.AreEqual(false, l[i++]);
  372. Assert.AreEqual(true, l[i++]);
  373. Assert.AreEqual(false, l[i++]);
  374. Assert.AreEqual(true, l[i++]);
  375. Assert.AreEqual(true, l[i++]);
  376. Assert.AreEqual(true, l[i++]);
  377. Assert.AreEqual(true, l[i++]);
  378. Assert.AreEqual(true, l[i++]);
  379. Assert.AreEqual(true, l[i++]);
  380. Assert.AreEqual(true, l[i++]);
  381. Assert.AreEqual(false, l[i++]);
  382. Assert.AreEqual(false, l[i++]);
  383. Assert.AreEqual(null, l[i++]);
  384. Assert.AreEqual(null, l[i++]);
  385. }
  386. #endif
  387. [Test]
  388. public void CaseInsensitiveRequiredPropertyConstructorCreation()
  389. {
  390. FooRequired foo1 = new FooRequired(new[] { "A", "B", "C" });
  391. string json = JsonConvert.SerializeObject(foo1);
  392. StringAssert.AreEqual(@"{""Bars"":[""A"",""B"",""C""]}", json);
  393. FooRequired foo2 = JsonConvert.DeserializeObject<FooRequired>(json);
  394. Assert.AreEqual(foo1.Bars.Count, foo2.Bars.Count);
  395. Assert.AreEqual(foo1.Bars[0], foo2.Bars[0]);
  396. Assert.AreEqual(foo1.Bars[1], foo2.Bars[1]);
  397. Assert.AreEqual(foo1.Bars[2], foo2.Bars[2]);
  398. }
  399. public class FooRequired
  400. {
  401. [JsonProperty(Required = Required.Always)]
  402. public List<string> Bars { get; private set; }
  403. public FooRequired(IEnumerable<string> bars)
  404. {
  405. Bars = new List<string>();
  406. if (bars != null)
  407. {
  408. Bars.AddRange(bars);
  409. }
  410. }
  411. }
  412. [Test]
  413. public void CoercedEmptyStringWithRequired()
  414. {
  415. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Binding>("{requiredProperty:''}"); }, "Required property 'RequiredProperty' expects a value but got null. Path '', line 1, position 21.");
  416. }
  417. [Test]
  418. public void CoercedEmptyStringWithRequired_DisallowNull()
  419. {
  420. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Binding_DisallowNull>("{requiredProperty:''}"); }, "Required property 'RequiredProperty' expects a non-null value. Path '', line 1, position 21.");
  421. }
  422. [Test]
  423. public void DisallowNull_NoValue()
  424. {
  425. Binding_DisallowNull o = JsonConvert.DeserializeObject<Binding_DisallowNull>("{}");
  426. Assert.IsNull(o.RequiredProperty);
  427. }
  428. [Test]
  429. public void CoercedEmptyStringWithRequiredConstructor()
  430. {
  431. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<FooRequired>("{Bars:''}"); }, "Required property 'Bars' expects a value but got null. Path '', line 1, position 9.");
  432. }
  433. public class IgnoredProperty
  434. {
  435. [JsonIgnore]
  436. [JsonProperty(Required = Required.Always)]
  437. public string StringProp1 { get; set; }
  438. [JsonIgnore]
  439. public string StringProp2 { get; set; }
  440. }
  441. [Test]
  442. public void NoErrorWhenValueDoesNotMatchIgnoredProperty()
  443. {
  444. IgnoredProperty p = JsonConvert.DeserializeObject<IgnoredProperty>("{'StringProp1':[1,2,3],'StringProp2':{}}");
  445. Assert.IsNull(p.StringProp1);
  446. Assert.IsNull(p.StringProp2);
  447. }
  448. public class Binding
  449. {
  450. [JsonProperty(Required = Required.Always)]
  451. public Binding RequiredProperty { get; set; }
  452. }
  453. public class Binding_DisallowNull
  454. {
  455. [JsonProperty(Required = Required.DisallowNull)]
  456. public Binding RequiredProperty { get; set; }
  457. }
  458. [Test]
  459. public void Serialize_Required_DisallowedNull()
  460. {
  461. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.SerializeObject(new Binding_DisallowNull()); }, "Cannot write a null value for property 'RequiredProperty'. Property requires a non-null value. Path ''.");
  462. }
  463. [Test]
  464. public void Serialize_Required_DisallowedNull_NullValueHandlingIgnore()
  465. {
  466. string json = JsonConvert.SerializeObject(new Binding_DisallowNull(), new JsonSerializerSettings
  467. {
  468. NullValueHandling = NullValueHandling.Ignore
  469. });
  470. Assert.AreEqual("{}", json);
  471. }
  472. [JsonObject(ItemRequired = Required.DisallowNull)]
  473. public class DictionaryWithNoNull
  474. {
  475. public string Name { get; set; }
  476. }
  477. [Test]
  478. public void Serialize_ItemRequired_DisallowedNull()
  479. {
  480. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.SerializeObject(new DictionaryWithNoNull()); }, "Cannot write a null value for property 'Name'. Property requires a non-null value. Path ''.");
  481. }
  482. public class DictionaryKeyContractResolver : DefaultContractResolver
  483. {
  484. protected override string ResolveDictionaryKey(string dictionaryKey)
  485. {
  486. return dictionaryKey;
  487. }
  488. protected override string ResolvePropertyName(string propertyName)
  489. {
  490. #if DNXCORE50
  491. return propertyName.ToUpperInvariant();
  492. #else
  493. return propertyName.ToUpper(CultureInfo.InvariantCulture);
  494. #endif
  495. }
  496. }
  497. [Test]
  498. public void DictionaryKeyContractResolverTest()
  499. {
  500. var person = new
  501. {
  502. Name = "James",
  503. Age = 1,
  504. RoleNames = new Dictionary<string, bool>
  505. {
  506. { "IsAdmin", true },
  507. { "IsModerator", false }
  508. }
  509. };
  510. string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
  511. {
  512. ContractResolver = new DictionaryKeyContractResolver()
  513. });
  514. Assert.AreEqual(@"{
  515. ""NAME"": ""James"",
  516. ""AGE"": 1,
  517. ""ROLENAMES"": {
  518. ""IsAdmin"": true,
  519. ""IsModerator"": false
  520. }
  521. }", json);
  522. }
  523. [Test]
  524. public void IncompleteContainers()
  525. {
  526. ExceptionAssert.Throws<JsonSerializationException>(
  527. () => JsonConvert.DeserializeObject<IList<object>>("[1,"),
  528. "Unexpected end when deserializing array. Path '[0]', line 1, position 3.");
  529. ExceptionAssert.Throws<JsonSerializationException>(
  530. () => JsonConvert.DeserializeObject<IList<int>>("[1,"),
  531. "Unexpected end when deserializing array. Path '[0]', line 1, position 3.");
  532. ExceptionAssert.Throws<JsonSerializationException>(
  533. () => JsonConvert.DeserializeObject<IList<int>>("[1"),
  534. "Unexpected end when deserializing array. Path '[0]', line 1, position 2.");
  535. ExceptionAssert.Throws<JsonSerializationException>(
  536. () => JsonConvert.DeserializeObject<IDictionary<string, int>>("{'key':1,"),
  537. "Unexpected end when deserializing object. Path 'key', line 1, position 9.");
  538. ExceptionAssert.Throws<JsonSerializationException>(
  539. () => JsonConvert.DeserializeObject<IDictionary<string, int>>("{'key':1"),
  540. "Unexpected end when deserializing object. Path 'key', line 1, position 8.");
  541. ExceptionAssert.Throws<JsonSerializationException>(
  542. () => JsonConvert.DeserializeObject<IncompleteTestClass>("{'key':1,"),
  543. "Unexpected end when deserializing object. Path 'key', line 1, position 9.");
  544. ExceptionAssert.Throws<JsonSerializationException>(
  545. () => JsonConvert.DeserializeObject<IncompleteTestClass>("{'key':1"),
  546. "Unexpected end when deserializing object. Path 'key', line 1, position 8.");
  547. }
  548. public class IncompleteTestClass
  549. {
  550. public int Key { get; set; }
  551. }
  552. #if !NET20
  553. public enum EnumA
  554. {
  555. [EnumMember(Value = "value_a")]
  556. ValueA
  557. }
  558. [Test]
  559. public void DeserializeEnumsByName()
  560. {
  561. var e1 = JsonConvert.DeserializeObject<EnumA>("'ValueA'");
  562. Assert.AreEqual(EnumA.ValueA, e1);
  563. var e2 = JsonConvert.DeserializeObject<EnumA>("'value_a'", new StringEnumConverter());
  564. Assert.AreEqual(EnumA.ValueA, e2);
  565. }
  566. #endif
  567. public class RequiredPropertyTestClass
  568. {
  569. [JsonRequired]
  570. internal string Name { get; set; }
  571. }
  572. [Test]
  573. public void RequiredPropertyTest()
  574. {
  575. RequiredPropertyTestClass c1 = new RequiredPropertyTestClass();
  576. ExceptionAssert.Throws<JsonSerializationException>(
  577. () => JsonConvert.SerializeObject(c1),
  578. "Cannot write a null value for property 'Name'. Property requires a value. Path ''.");
  579. RequiredPropertyTestClass c2 = new RequiredPropertyTestClass
  580. {
  581. Name = "Name!"
  582. };
  583. string json = JsonConvert.SerializeObject(c2);
  584. Assert.AreEqual(@"{""Name"":""Name!""}", json);
  585. ExceptionAssert.Throws<JsonSerializationException>(
  586. () => JsonConvert.DeserializeObject<RequiredPropertyTestClass>(@"{}"),
  587. "Required property 'Name' not found in JSON. Path '', line 1, position 2.");
  588. ExceptionAssert.Throws<JsonSerializationException>(
  589. () => JsonConvert.DeserializeObject<RequiredPropertyTestClass>(@"{""Name"":null}"),
  590. "Required property 'Name' expects a value but got null. Path '', line 1, position 13.");
  591. RequiredPropertyTestClass c3 = JsonConvert.DeserializeObject<RequiredPropertyTestClass>(@"{""Name"":""Name!""}");
  592. Assert.AreEqual("Name!", c3.Name);
  593. }
  594. public class RequiredPropertyConstructorTestClass
  595. {
  596. public RequiredPropertyConstructorTestClass(string name)
  597. {
  598. Name = name;
  599. }
  600. [JsonRequired]
  601. internal string Name { get; set; }
  602. }
  603. [Test]
  604. public void RequiredPropertyConstructorTest()
  605. {
  606. RequiredPropertyConstructorTestClass c1 = new RequiredPropertyConstructorTestClass(null);
  607. ExceptionAssert.Throws<JsonSerializationException>(
  608. () => JsonConvert.SerializeObject(c1),
  609. "Cannot write a null value for property 'Name'. Property requires a value. Path ''.");
  610. RequiredPropertyConstructorTestClass c2 = new RequiredPropertyConstructorTestClass("Name!");
  611. string json = JsonConvert.SerializeObject(c2);
  612. Assert.AreEqual(@"{""Name"":""Name!""}", json);
  613. ExceptionAssert.Throws<JsonSerializationException>(
  614. () => JsonConvert.DeserializeObject<RequiredPropertyConstructorTestClass>(@"{}"),
  615. "Required property 'Name' not found in JSON. Path '', line 1, position 2.");
  616. RequiredPropertyConstructorTestClass c3 = JsonConvert.DeserializeObject<RequiredPropertyConstructorTestClass>(@"{""Name"":""Name!""}");
  617. Assert.AreEqual("Name!", c3.Name);
  618. }
  619. public class IgnoredPropertiesTestClass
  620. {
  621. [JsonIgnore]
  622. public Version IgnoredProperty { get; set; }
  623. [JsonIgnore]
  624. public List<Version> IgnoredList { get; set; }
  625. [JsonIgnore]
  626. public Dictionary<string, Version> IgnoredDictionary { get; set; }
  627. [JsonProperty(Required = Required.Always)]
  628. public string Name { get; set; }
  629. }
  630. public class IgnoredPropertiesContractResolver : DefaultContractResolver
  631. {
  632. public override JsonContract ResolveContract(Type type)
  633. {
  634. if (type == typeof(Version))
  635. {
  636. throw new Exception("Error!");
  637. }
  638. return base.ResolveContract(type);
  639. }
  640. }
  641. [Test]
  642. public void NeverResolveIgnoredPropertyTypes()
  643. {
  644. Version v = new Version(1, 2, 3, 4);
  645. IgnoredPropertiesTestClass c1 = new IgnoredPropertiesTestClass
  646. {
  647. IgnoredProperty = v,
  648. IgnoredList = new List<Version>
  649. {
  650. v
  651. },
  652. IgnoredDictionary = new Dictionary<string, Version>
  653. {
  654. { "Value", v }
  655. },
  656. Name = "Name!"
  657. };
  658. string json = JsonConvert.SerializeObject(c1, Formatting.Indented, new JsonSerializerSettings
  659. {
  660. ContractResolver = new IgnoredPropertiesContractResolver()
  661. });
  662. Assert.AreEqual(@"{
  663. ""Name"": ""Name!""
  664. }", json);
  665. string deserializeJson = @"{
  666. ""IgnoredList"": [
  667. {
  668. ""Major"": 1,
  669. ""Minor"": 2,
  670. ""Build"": 3,
  671. ""Revision"": 4,
  672. ""MajorRevision"": 0,
  673. ""MinorRevision"": 4
  674. }
  675. ],
  676. ""IgnoredDictionary"": {
  677. ""Value"": {
  678. ""Major"": 1,
  679. ""Minor"": 2,
  680. ""Build"": 3,
  681. ""Revision"": 4,
  682. ""MajorRevision"": 0,
  683. ""MinorRevision"": 4
  684. }
  685. },
  686. ""Name"": ""Name!""
  687. }";
  688. IgnoredPropertiesTestClass c2 = JsonConvert.DeserializeObject<IgnoredPropertiesTestClass>(deserializeJson, new JsonSerializerSettings
  689. {
  690. ContractResolver = new IgnoredPropertiesContractResolver()
  691. });
  692. Assert.AreEqual("Name!", c2.Name);
  693. }
  694. #if !(NET20 || NET35)
  695. [Test]
  696. public void SerializeValueTuple()
  697. {
  698. ValueTuple<int, int, string> t = ValueTuple.Create(1, 2, "string");
  699. string json = JsonConvert.SerializeObject(t, Formatting.Indented);
  700. StringAssert.AreEqual(@"{
  701. ""Item1"": 1,
  702. ""Item2"": 2,
  703. ""Item3"": ""string""
  704. }", json);
  705. ValueTuple<int, int, string> t2 = JsonConvert.DeserializeObject<ValueTuple<int, int, string>>(json);
  706. Assert.AreEqual(1, t2.Item1);
  707. Assert.AreEqual(2, t2.Item2);
  708. Assert.AreEqual("string", t2.Item3);
  709. }
  710. #endif
  711. [Test]
  712. public void DeserializeStructWithConstructorAttribute()
  713. {
  714. ImmutableStructWithConstructorAttribute result = JsonConvert.DeserializeObject<ImmutableStructWithConstructorAttribute>("{ \"Value\": \"working\" }");
  715. Assert.AreEqual("working", result.Value);
  716. }
  717. public struct ImmutableStructWithConstructorAttribute
  718. {
  719. [JsonConstructor]
  720. public ImmutableStructWithConstructorAttribute(string value)
  721. {
  722. Value = value;
  723. }
  724. public string Value { get; }
  725. }
  726. #if !(DNXCORE50 || NET20)
  727. [MetadataType(typeof(CustomerValidation))]
  728. public partial class CustomerWithMetadataType
  729. {
  730. public System.Guid UpdatedBy_Id { get; set; }
  731. public class CustomerValidation
  732. {
  733. [JsonIgnore]
  734. public System.Guid UpdatedBy_Id { get; set; }
  735. }
  736. }
  737. [Test]
  738. public void SerializeMetadataType()
  739. {
  740. CustomerWithMetadataType c = new CustomerWithMetadataType()
  741. {
  742. UpdatedBy_Id = Guid.NewGuid()
  743. };
  744. string json = JsonConvert.SerializeObject(c);
  745. Assert.AreEqual("{}", json);
  746. CustomerWithMetadataType c2 = JsonConvert.DeserializeObject<CustomerWithMetadataType>("{'UpdatedBy_Id':'F6E0666D-13C7-4745-B486-800812C8F6DE'}");
  747. Assert.AreEqual(Guid.Empty, c2.UpdatedBy_Id);
  748. }
  749. [Serializable]
  750. public partial class FaqItem
  751. {
  752. public FaqItem()
  753. {
  754. this.Sections = new HashSet<FaqSection>();
  755. }
  756. public int FaqId { get; set; }
  757. public string Name { get; set; }
  758. public bool IsDeleted { get; set; }
  759. public virtual ICollection<FaqSection> Sections { get; set; }
  760. }
  761. [MetadataType(typeof(FaqItemMetadata))]
  762. partial class FaqItem
  763. {
  764. [JsonProperty("FullSectionsProp")]
  765. public ICollection<FaqSection> FullSections
  766. {
  767. get { return Sections; }
  768. }
  769. }
  770. public class FaqItemMetadata
  771. {
  772. [JsonIgnore]
  773. public virtual ICollection<FaqSection> Sections { get; set; }
  774. }
  775. public class FaqSection
  776. {
  777. }
  778. public class FaqItemProxy : FaqItem
  779. {
  780. public bool IsProxy { get; set; }
  781. public override ICollection<FaqSection> Sections
  782. {
  783. get { return base.Sections; }
  784. set { base.Sections = value; }
  785. }
  786. }
  787. [Test]
  788. public void SerializeMetadataType2()
  789. {
  790. FaqItem c = new FaqItem()
  791. {
  792. FaqId = 1,
  793. Sections =
  794. {
  795. new FaqSection()
  796. }
  797. };
  798. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  799. StringAssert.AreEqual(@"{
  800. ""FaqId"": 1,
  801. ""Name"": null,
  802. ""IsDeleted"": false,
  803. ""FullSectionsProp"": [
  804. {}
  805. ]
  806. }", json);
  807. FaqItem c2 = JsonConvert.DeserializeObject<FaqItem>(json);
  808. Assert.AreEqual(1, c2.FaqId);
  809. Assert.AreEqual(1, c2.Sections.Count);
  810. }
  811. [Test]
  812. public void SerializeMetadataTypeInheritance()
  813. {
  814. FaqItemProxy c = new FaqItemProxy();
  815. c.FaqId = 1;
  816. c.Sections.Add(new FaqSection());
  817. c.IsProxy = true;
  818. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  819. StringAssert.AreEqual(@"{
  820. ""IsProxy"": true,
  821. ""FaqId"": 1,
  822. ""Name"": null,
  823. ""IsDeleted"": false,
  824. ""FullSectionsProp"": [
  825. {}
  826. ]
  827. }", json);
  828. FaqItemProxy c2 = JsonConvert.DeserializeObject<FaqItemProxy>(json);
  829. Assert.AreEqual(1, c2.FaqId);
  830. Assert.AreEqual(1, c2.Sections.Count);
  831. }
  832. #endif
  833. public class NullTestClass
  834. {
  835. public JObject Value1 { get; set; }
  836. public JValue Value2 { get; set; }
  837. public JRaw Value3 { get; set; }
  838. public JToken Value4 { get; set; }
  839. public object Value5 { get; set; }
  840. }
  841. [Test]
  842. public void DeserializeNullToJTokenProperty()
  843. {
  844. NullTestClass otc = JsonConvert.DeserializeObject<NullTestClass>(@"{
  845. ""Value1"": null,
  846. ""Value2"": null,
  847. ""Value3"": null,
  848. ""Value4"": null,
  849. ""Value5"": null
  850. }");
  851. Assert.IsNull(otc.Value1);
  852. Assert.AreEqual(JTokenType.Null, otc.Value2.Type);
  853. Assert.AreEqual(JTokenType.Raw, otc.Value3.Type);
  854. Assert.AreEqual(JTokenType.Null, otc.Value4.Type);
  855. Assert.IsNull(otc.Value5);
  856. }
  857. public class Link
  858. {
  859. /// <summary>
  860. /// The unique identifier.
  861. /// </summary>
  862. public int Id;
  863. /// <summary>
  864. /// The parent information identifier.
  865. /// </summary>
  866. public int ParentId;
  867. /// <summary>
  868. /// The child information identifier.
  869. /// </summary>
  870. public int ChildId;
  871. }
  872. #if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
  873. [Test]
  874. public void ReadIntegerWithError()
  875. {
  876. string json = @"{
  877. ParentId: 1,
  878. ChildId: 333333333333333333333333333333333333333
  879. }";
  880. Link l = JsonConvert.DeserializeObject<Link>(json, new JsonSerializerSettings
  881. {
  882. Error = (s, a) => a.ErrorContext.Handled = true
  883. });
  884. Assert.AreEqual(0, l.ChildId);
  885. }
  886. #endif
  887. #if !(NET20 || NET35)
  888. [Test]
  889. public void DeserializeObservableCollection()
  890. {
  891. ObservableCollection<string> s = JsonConvert.DeserializeObject<ObservableCollection<string>>("['1','2']");
  892. Assert.AreEqual(2, s.Count);
  893. Assert.AreEqual("1", s[0]);
  894. Assert.AreEqual("2", s[1]);
  895. }
  896. #endif
  897. [Test]
  898. public void DeserializeBoolAsStringInDictionary()
  899. {
  900. Dictionary<string, string> d = JsonConvert.DeserializeObject<Dictionary<string, string>>("{\"Test1\":false}");
  901. Assert.AreEqual(1, d.Count);
  902. Assert.AreEqual("false", d["Test1"]);
  903. }
  904. #if !NET20
  905. [Test]
  906. public void PopulateResetSettings()
  907. {
  908. JsonTextReader reader = new JsonTextReader(new StringReader(@"[""2000-01-01T01:01:01+00:00""]"));
  909. Assert.AreEqual(DateParseHandling.DateTime, reader.DateParseHandling);
  910. JsonSerializer serializer = new JsonSerializer();
  911. serializer.DateParseHandling = DateParseHandling.DateTimeOffset;
  912. IList<object> l = new List<object>();
  913. serializer.Populate(reader, l);
  914. Assert.AreEqual(typeof(DateTimeOffset), l[0].GetType());
  915. Assert.AreEqual(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero), l[0]);
  916. Assert.AreEqual(DateParseHandling.DateTime, reader.DateParseHandling);
  917. }
  918. #endif
  919. public class BaseClass
  920. {
  921. internal bool IsTransient { get; set; }
  922. }
  923. public class ChildClass : BaseClass
  924. {
  925. public new bool IsTransient { get; set; }
  926. }
  927. [Test]
  928. public void NewProperty()
  929. {
  930. Assert.AreEqual(@"{""IsTransient"":true}", JsonConvert.SerializeObject(new ChildClass { IsTransient = true }));
  931. var childClass = JsonConvert.DeserializeObject<ChildClass>(@"{""IsTransient"":true}");
  932. Assert.AreEqual(true, childClass.IsTransient);
  933. }
  934. public class BaseClassVirtual
  935. {
  936. internal virtual bool IsTransient { get; set; }
  937. }
  938. public class ChildClassVirtual : BaseClassVirtual
  939. {
  940. public new virtual bool IsTransient { get; set; }
  941. }
  942. [Test]
  943. public void NewPropertyVirtual()
  944. {
  945. Assert.AreEqual(@"{""IsTransient"":true}", JsonConvert.SerializeObject(new ChildClassVirtual { IsTransient = true }));
  946. var childClass = JsonConvert.DeserializeObject<ChildClassVirtual>(@"{""IsTransient"":true}");
  947. Assert.AreEqual(true, childClass.IsTransient);
  948. }
  949. public class ResponseWithNewGenericProperty<T> : SimpleResponse
  950. {
  951. public new T Data { get; set; }
  952. }
  953. public class ResponseWithNewGenericPropertyVirtual<T> : SimpleResponse
  954. {
  955. public new virtual T Data { get; set; }
  956. }
  957. public class ResponseWithNewGenericPropertyOverride<T> : ResponseWithNewGenericPropertyVirtual<T>
  958. {
  959. public override T Data { get; set; }
  960. }
  961. public abstract class SimpleResponse
  962. {
  963. public string Result { get; set; }
  964. public string Message { get; set; }
  965. public object Data { get; set; }
  966. protected SimpleResponse()
  967. {
  968. }
  969. protected SimpleResponse(string message)
  970. {
  971. Message = message;
  972. }
  973. }
  974. [Test]
  975. public void CanSerializeWithBuiltInTypeAsGenericArgument()
  976. {
  977. var input = new ResponseWithNewGenericProperty<int>()
  978. {
  979. Message = "Trying out integer as type parameter",
  980. Data = 25,
  981. Result = "This should be fine"
  982. };
  983. var json = JsonConvert.SerializeObject(input);
  984. var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericProperty<int>>(json);
  985. Assert.AreEqual(input.Data, deserialized.Data);
  986. Assert.AreEqual(input.Message, deserialized.Message);
  987. Assert.AreEqual(input.Result, deserialized.Result);
  988. }
  989. [Test]
  990. public void CanSerializeWithBuiltInTypeAsGenericArgumentVirtual()
  991. {
  992. var input = new ResponseWithNewGenericPropertyVirtual<int>()
  993. {
  994. Message = "Trying out integer as type parameter",
  995. Data = 25,
  996. Result = "This should be fine"
  997. };
  998. var json = JsonConvert.SerializeObject(input);
  999. var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericPropertyVirtual<int>>(json);
  1000. Assert.AreEqual(input.Data, deserialized.Data);
  1001. Assert.AreEqual(input.Message, deserialized.Message);
  1002. Assert.AreEqual(input.Result, deserialized.Result);
  1003. }
  1004. [Test]
  1005. public void CanSerializeWithBuiltInTypeAsGenericArgumentOverride()
  1006. {
  1007. var input = new ResponseWithNewGenericPropertyOverride<int>()
  1008. {
  1009. Message = "Trying out integer as type parameter",
  1010. Data = 25,
  1011. Result = "This should be fine"
  1012. };
  1013. var json = JsonConvert.SerializeObject(input);
  1014. var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericPropertyOverride<int>>(json);
  1015. Assert.AreEqual(input.Data, deserialized.Data);
  1016. Assert.AreEqual(input.Message, deserialized.Message);
  1017. Assert.AreEqual(input.Result, deserialized.Result);
  1018. }
  1019. [Test]
  1020. public void CanSerializedWithGenericClosedTypeAsArgument()
  1021. {
  1022. var input = new ResponseWithNewGenericProperty<List<int>>()
  1023. {
  1024. Message = "More complex case - generic list of int",
  1025. Data = Enumerable.Range(50, 70).ToList(),
  1026. Result = "This should be fine too"
  1027. };
  1028. var json = JsonConvert.SerializeObject(input);
  1029. var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericProperty<List<int>>>(json);
  1030. CollectionAssert.AreEqual(input.Data, deserialized.Data);
  1031. Assert.AreEqual(input.Message, deserialized.Message);
  1032. Assert.AreEqual(input.Result, deserialized.Result);
  1033. }
  1034. [Test]
  1035. public void DeserializeVersionString()
  1036. {
  1037. string json = "['1.2.3.4']";
  1038. List<Version> deserialized = JsonConvert.DeserializeObject<List<Version>>(json);
  1039. Assert.AreEqual(1, deserialized[0].Major);
  1040. Assert.AreEqual(2, deserialized[0].Minor);
  1041. Assert.AreEqual(3, deserialized[0].Build);
  1042. Assert.AreEqual(4, deserialized[0].Revision);
  1043. }
  1044. [Test]
  1045. public void DeserializeVersionString_Fail()
  1046. {
  1047. string json = "['1.2.3.4444444444444444444444']";
  1048. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<List<Version>>(json); }, @"Error converting value ""1.2.3.4444444444444444444444"" to type 'System.Version'. Path '[0]', line 1, position 31.");
  1049. }
  1050. [Test]
  1051. public void DeserializeJObjectWithComments()
  1052. {
  1053. string json = @"/* Test */
  1054. {
  1055. /*Test*/""A"":/* Test */true/* Test */,
  1056. /* Test */""B"":/* Test */false/* Test */,
  1057. /* Test */""C"":/* Test */[
  1058. /* Test */
  1059. 1/* Test */
  1060. ]/* Test */
  1061. }
  1062. /* Test */";
  1063. JObject o = (JObject)JsonConvert.DeserializeObject(json);
  1064. Assert.AreEqual(3, o.Count);
  1065. Assert.AreEqual(true, (bool)o["A"]);
  1066. Assert.AreEqual(false, (bool)o["B"]);
  1067. Assert.AreEqual(1, o["C"].Count());
  1068. Assert.AreEqual(1, (int)o["C"][0]);
  1069. Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
  1070. json = @"{/* Test */}";
  1071. o = (JObject)JsonConvert.DeserializeObject(json);
  1072. Assert.AreEqual(0, o.Count);
  1073. Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
  1074. json = @"{""A"": true/* Test */}";
  1075. o = (JObject)JsonConvert.DeserializeObject(json);
  1076. Assert.AreEqual(1, o.Count);
  1077. Assert.AreEqual(true, (bool)o["A"]);
  1078. Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
  1079. }
  1080. public class CommentTestObject
  1081. {
  1082. public bool? A { get; set; }
  1083. }
  1084. [Test]
  1085. public void DeserializeCommentTestObjectWithComments()
  1086. {
  1087. CommentTestObject o = JsonConvert.DeserializeObject<CommentTestObject>(@"{/* Test */}");
  1088. Assert.AreEqual(null, o.A);
  1089. o = JsonConvert.DeserializeObject<CommentTestObject>(@"{""A"": true/* Test */}");
  1090. Assert.AreEqual(true, o.A);
  1091. }
  1092. [Test]
  1093. public void JsonSerializerProperties()
  1094. {
  1095. JsonSerializer serializer = new JsonSerializer();
  1096. DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
  1097. #pragma warning disable CS0618 // Type or member is obsolete
  1098. serializer.Binder = customBinder;
  1099. Assert.AreEqual(customBinder, serializer.Binder);
  1100. #pragma warning restore CS0618 // Type or member is obsolete
  1101. Assert.IsInstanceOf(typeof(SerializationBinderAdapter), serializer.SerializationBinder);
  1102. serializer.SerializationBinder = customBinder;
  1103. Assert.AreEqual(customBinder, serializer.SerializationBinder);
  1104. ExceptionAssert.Throws<InvalidOperationException>(() =>
  1105. {
  1106. #pragma warning disable CS0618 // Type or member is obsolete
  1107. var serializationBinder = serializer.Binder;
  1108. #pragma warning restore CS0618 // Type or member is obsolete
  1109. serializationBinder.ToString();
  1110. }, "Cannot get SerializationBinder because an ISerializationBinder was previously set.");
  1111. serializer.CheckAdditionalContent = true;
  1112. Assert.AreEqual(true, serializer.CheckAdditionalContent);
  1113. serializer.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
  1114. Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, serializer.ConstructorHandling);
  1115. #if !(DNXCORE50)
  1116. serializer.Context = new StreamingContext(StreamingContextStates.Other);
  1117. Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), serializer.Context);
  1118. #endif
  1119. CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
  1120. serializer.ContractResolver = resolver;
  1121. Assert.AreEqual(resolver, serializer.ContractResolver);
  1122. serializer.Converters.Add(new StringEnumConverter());
  1123. Assert.AreEqual(1, serializer.Converters.Count);
  1124. serializer.Culture = new CultureInfo("en-nz");
  1125. Assert.AreEqual("en-NZ", serializer.Culture.ToString());
  1126. serializer.EqualityComparer = EqualityComparer<object>.Default;
  1127. Assert.AreEqual(EqualityComparer<object>.Default, serializer.EqualityComparer);
  1128. serializer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
  1129. Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, serializer.DateFormatHandling);
  1130. serializer.DateFormatString = "yyyy";
  1131. Assert.AreEqual("yyyy", serializer.DateFormatString);
  1132. serializer.DateParseHandling = DateParseHandling.None;
  1133. Assert.AreEqual(DateParseHandling.None, serializer.DateParseHandling);
  1134. serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
  1135. Assert.AreEqual(DateTimeZoneHandling.Utc, serializer.DateTimeZoneHandling);
  1136. serializer.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
  1137. Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, serializer.DefaultValueHandling);
  1138. serializer.FloatFormatHandling = FloatFormatHandling.Symbol;
  1139. Assert.AreEqual(FloatFormatHandling.Symbol, serializer.FloatFormatHandling);
  1140. serializer.FloatParseHandling = FloatParseHandling.Decimal;
  1141. Assert.AreEqual(FloatParseHandling.Decimal, serializer.FloatParseHandling);
  1142. serializer.Formatting = Formatting.Indented;
  1143. Assert.AreEqual(Formatting.Indented, serializer.Formatting);
  1144. serializer.MaxDepth = 9001;
  1145. Assert.AreEqual(9001, serializer.MaxDepth);
  1146. serializer.MissingMemberHandling = MissingMemberHandling.Error;
  1147. Assert.AreEqual(MissingMemberHandling.Error, serializer.MissingMemberHandling);
  1148. serializer.NullValueHandling = NullValueHandling.Ignore;
  1149. Assert.AreEqual(NullValueHandling.Ignore, serializer.NullValueHandling);
  1150. serializer.ObjectCreationHandling = ObjectCreationHandling.Replace;
  1151. Assert.AreEqual(ObjectCreationHandling.Replace, serializer.ObjectCreationHandling);
  1152. serializer.PreserveReferencesHandling = PreserveReferencesHandling.All;
  1153. Assert.AreEqual(PreserveReferencesHandling.All, serializer.PreserveReferencesHandling);
  1154. serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  1155. Assert.AreEqual(ReferenceLoopHandling.Ignore, serializer.ReferenceLoopHandling);
  1156. IdReferenceResolver referenceResolver = new IdReferenceResolver();
  1157. serializer.ReferenceResolver = referenceResolver;
  1158. Assert.AreEqual(referenceResolver, serializer.ReferenceResolver);
  1159. serializer.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
  1160. Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, serializer.StringEscapeHandling);
  1161. MemoryTraceWriter traceWriter = new MemoryTraceWriter();
  1162. serializer.TraceWriter = traceWriter;
  1163. Assert.AreEqual(traceWriter, serializer.TraceWriter);
  1164. #if !(PORTABLE || PORTABLE40 || NET20 || DNXCORE50)
  1165. #pragma warning disable 618
  1166. serializer.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
  1167. Assert.AreEqual(FormatterAssemblyStyle.Full, serializer.TypeNameAssemblyFormat);
  1168. #pragma warning restore 618
  1169. Assert.AreEqual(TypeNameAssemblyFormatHandling.Full, serializer.TypeNameAssemblyFormatHandling);
  1170. serializer.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple;
  1171. #pragma warning disable 618
  1172. Assert.AreEqual(FormatterAssemblyStyle.Simple, serializer.TypeNameAssemblyFormat);
  1173. #pragma warning restore 618
  1174. #endif
  1175. serializer.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full;
  1176. Assert.AreEqual(TypeNameAssemblyFormatHandling.Full, serializer.TypeNameAssemblyFormatHandling);
  1177. serializer.TypeNameHandling = TypeNameHandling.All;
  1178. Assert.AreEqual(TypeNameHandling.All, serializer.TypeNameHandling);
  1179. }
  1180. [Test]
  1181. public void JsonSerializerSettingsProperties()
  1182. {
  1183. JsonSerializerSettings settings = new JsonSerializerSettings();
  1184. DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
  1185. #pragma warning disable CS0618 // Type or member is obsolete
  1186. settings.Binder = customBinder;
  1187. Assert.AreEqual(customBinder, settings.Binder);
  1188. #pragma warning restore CS0618 // Type or member is obsolete
  1189. settings.CheckAdditionalContent = true;
  1190. Assert.AreEqual(true, settings.CheckAdditionalContent);
  1191. settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
  1192. Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, settings.ConstructorHandling);
  1193. #if !(DNXCORE50)
  1194. settings.Context = new StreamingContext(StreamingContextStates.Other);
  1195. Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), settings.Context);
  1196. #endif
  1197. CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
  1198. settings.ContractResolver = resolver;
  1199. Assert.AreEqual(resolver, settings.ContractResolver);
  1200. settings.Converters.Add(new StringEnumConverter());
  1201. Assert.AreEqual(1, settings.Converters.Count);
  1202. settings.Culture = new CultureInfo("en-nz");
  1203. Assert.AreEqual("en-NZ", settings.Culture.ToString());
  1204. settings.EqualityComparer = EqualityComparer<object>.Default;
  1205. Assert.AreEqual(EqualityComparer<object>.Default, settings.EqualityComparer);
  1206. settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
  1207. Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, settings.DateFormatHandling);
  1208. settings.DateFormatString = "yyyy";
  1209. Assert.AreEqual("yyyy", settings.DateFormatString);
  1210. settings.DateParseHandling = DateParseHandling.None;
  1211. Assert.AreEqual(DateParseHandling.None, settings.DateParseHandling);
  1212. settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
  1213. Assert.AreEqual(DateTimeZoneHandling.Utc, settings.DateTimeZoneHandling);
  1214. settings.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
  1215. Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, settings.DefaultValueHandling);
  1216. settings.FloatFormatHandling = FloatFormatHandling.Symbol;
  1217. Assert.AreEqual(FloatFormatHandling.Symbol, settings.FloatFormatHandling);
  1218. settings.FloatParseHandling = FloatParseHandling.Decimal;
  1219. Assert.AreEqual(FloatParseHandling.Decimal, settings.FloatParseHandling);
  1220. settings.Formatting = Formatting.Indented;
  1221. Assert.AreEqual(Formatting.Indented, settings.Formatting);
  1222. settings.MaxDepth = 9001;
  1223. Assert.AreEqual(9001, settings.MaxDepth);
  1224. settings.MissingMemberHandling = MissingMemberHandling.Error;
  1225. Assert.AreEqual(MissingMemberHandling.Error, settings.MissingMemberHandling);
  1226. settings.NullValueHandling = NullValueHandling.Ignore;
  1227. Assert.AreEqual(NullValueHandling.Ignore, settings.NullValueHandling);
  1228. settings.ObjectCreationHandling = ObjectCreationHandling.Replace;
  1229. Assert.AreEqual(ObjectCreationHandling.Replace, settings.ObjectCreationHandling);
  1230. settings.PreserveReferencesHandling = PreserveReferencesHandling.All;
  1231. Assert.AreEqual(PreserveReferencesHandling.All, settings.PreserveReferencesHandling);
  1232. settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  1233. Assert.AreEqual(ReferenceLoopHandling.Ignore, settings.ReferenceLoopHandling);
  1234. IdReferenceResolver referenceResolver = new IdReferenceResolver();
  1235. #pragma warning disable 618
  1236. settings.ReferenceResolver = referenceResolver;
  1237. Assert.AreEqual(referenceResolver, settings.ReferenceResolver);
  1238. #pragma warning restore 618
  1239. Assert.AreEqual(referenceResolver, settings.ReferenceResolverProvider());
  1240. settings.ReferenceResolverProvider = () => referenceResolver;
  1241. Assert.AreEqual(referenceResolver, settings.ReferenceResolverProvider());
  1242. settings.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
  1243. Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, settings.StringEscapeHandling);
  1244. MemoryTraceWriter traceWriter = new MemoryTraceWriter();
  1245. settings.TraceWriter = traceWriter;
  1246. Assert.AreEqual(traceWriter, settings.TraceWriter);
  1247. #if !(PORTABLE || PORTABLE40 || NET20 || DNXCORE50)
  1248. #pragma warning disable 618
  1249. settings.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
  1250. Assert.AreEqual(FormatterAssemblyStyle.Full, settings.TypeNameAssemblyFormat);
  1251. #pragma warning restore 618
  1252. Assert.AreEqual(TypeNameAssemblyFormatHandling.Full, settings.TypeNameAssemblyFormatHandling);
  1253. settings.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple;
  1254. #pragma warning disable 618
  1255. Assert.AreEqual(FormatterAssemblyStyle.Simple, settings.TypeNameAssemblyFormat);
  1256. #pragma warning restore 618
  1257. #endif
  1258. settings.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full;
  1259. Assert.AreEqual(TypeNameAssemblyFormatHandling.Full, settings.TypeNameAssemblyFormatHandling);
  1260. settings.TypeNameHandling = TypeNameHandling.All;
  1261. Assert.AreEqual(TypeNameHandling.All, settings.TypeNameHandling);
  1262. }
  1263. [Test]
  1264. public void JsonSerializerProxyProperties()
  1265. {
  1266. JsonSerializerProxy serializerProxy = new JsonSerializerProxy(new JsonSerializerInternalReader(new JsonSerializer()));
  1267. DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
  1268. #pragma warning disable CS0618 // Type or member is obsolete
  1269. serializerProxy.Binder = customBinder;
  1270. Assert.AreEqual(customBinder, serializerProxy.Binder);
  1271. #pragma warning restore CS0618 // Type or member is obsolete
  1272. Assert.IsInstanceOf(typeof(SerializationBinderAdapter), serializerProxy.SerializationBinder);
  1273. serializerProxy.SerializationBinder = customBinder;
  1274. Assert.AreEqual(customBinder, serializerProxy.SerializationBinder);
  1275. ExceptionAssert.Throws<InvalidOperationException>(() =>
  1276. {
  1277. #pragma warning disable CS0618 // Type or member is obsolete
  1278. var serializationBinder = serializerProxy.Binder;
  1279. #pragma warning restore CS0618 // Type or member is obsolete
  1280. serializationBinder.ToString();
  1281. }, "Cannot get SerializationBinder because an ISerializationBinder was previously set.");
  1282. serializerProxy.CheckAdditionalContent = true;
  1283. Assert.AreEqual(true, serializerProxy.CheckAdditionalContent);
  1284. serializerProxy.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
  1285. Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, serializerProxy.ConstructorHandling);
  1286. #if !(DNXCORE50)
  1287. serializerProxy.Context = new StreamingContext(StreamingContextStates.Other);
  1288. Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), serializerProxy.Context);
  1289. #endif
  1290. CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
  1291. serializerProxy.ContractResolver = resolver;
  1292. Assert.AreEqual(resolver, serializerProxy.ContractResolver);
  1293. serializerProxy.Converters.Add(new StringEnumConverter());
  1294. Assert.AreEqual(1, serializerProxy.Converters.Count);
  1295. serializerProxy.Culture = new CultureInfo("en-nz");
  1296. Assert.AreEqual("en-NZ", serializerProxy.Culture.ToString());
  1297. serializerProxy.EqualityComparer = EqualityComparer<object>.Default;
  1298. Assert.AreEqual(EqualityComparer<object>.Default, serializerProxy.EqualityComparer);
  1299. serializerProxy.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
  1300. Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, serializerProxy.DateFormatHandling);
  1301. serializerProxy.DateFormatString = "yyyy";
  1302. Assert.AreEqual("yyyy", serializerProxy.DateFormatString);
  1303. serializerProxy.DateParseHandling = DateParseHandling.None;
  1304. Assert.AreEqual(DateParseHandling.None, serializerProxy.DateParseHandling);
  1305. serializerProxy.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
  1306. Assert.AreEqual(DateTimeZoneHandling.Utc, serializerProxy.DateTimeZoneHandling);
  1307. serializerProxy.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
  1308. Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, serializerProxy.DefaultValueHandling);
  1309. serializerProxy.FloatFormatHandling = FloatFormatHandling.Symbol;
  1310. Assert.AreEqual(FloatFormatHandling.Symbol, serializerProxy.FloatFormatHandling);
  1311. serializerProxy.FloatParseHandling = FloatParseHandling.Decimal;
  1312. Assert.AreEqual(FloatParseHandling.Decimal, serializerProxy.FloatParseHandling);
  1313. serializerProxy.Formatting = Formatting.Indented;
  1314. Assert.AreEqual(Formatting.Indented, serializerProxy.Formatting);
  1315. serializerProxy.MaxDepth = 9001;
  1316. Assert.AreEqual(9001, serializerProxy.MaxDepth);
  1317. serializerProxy.MissingMemberHandling = MissingMemberHandling.Error;
  1318. Assert.AreEqual(MissingMemberHandling.Error, serializerProxy.MissingMemberHandling);
  1319. serializerProxy.NullValueHandling = NullValueHandling.Ignore;
  1320. Assert.AreEqual(NullValueHandling.Ignore, serializerProxy.NullValueHandling);
  1321. serializerProxy.ObjectCreationHandling = ObjectCreationHandling.Replace;
  1322. Assert.AreEqual(ObjectCreationHandling.Replace, serializerProxy.ObjectCreationHandling);
  1323. serializerProxy.PreserveReferencesHandling = PreserveReferencesHandling.All;
  1324. Assert.AreEqual(PreserveReferencesHandling.All, serializerProxy.PreserveReferencesHandling);
  1325. serializerProxy.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  1326. Assert.AreEqual(ReferenceLoopHandling.Ignore, serializerProxy.ReferenceLoopHandling);
  1327. IdReferenceResolver referenceResolver = new IdReferenceResolver();
  1328. serializerProxy.ReferenceResolver = referenceResolver;
  1329. Assert.AreEqual(referenceResolver, serializerProxy.ReferenceResolver);
  1330. serializerProxy.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
  1331. Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, serializerProxy.StringEscapeHandling);
  1332. MemoryTraceWriter traceWriter = new MemoryTraceWriter();
  1333. serializerProxy.TraceWriter = traceWriter;
  1334. Assert.AreEqual(traceWriter, serializerProxy.TraceWriter);
  1335. #if !(PORTABLE || PORTABLE40 || NET20 || DNXCORE50)
  1336. #pragma warning disable 618
  1337. serializerProxy.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
  1338. Assert.AreEqual(FormatterAssemblyStyle.Full, serializerProxy.TypeNameAssemblyFormat);
  1339. #pragma warning restore 618
  1340. Assert.AreEqual(TypeNameAssemblyFormatHandling.Full, serializerProxy.TypeNameAssemblyFormatHandling);
  1341. serializerProxy.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple;
  1342. #pragma warning disable 618
  1343. Assert.AreEqual(FormatterAssemblyStyle.Simple, serializerProxy.TypeNameAssemblyFormat);
  1344. #pragma warning restore 618
  1345. #endif
  1346. serializerProxy.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full;
  1347. Assert.AreEqual(TypeNameAssemblyFormatHandling.Full, serializerProxy.TypeNameAssemblyFormatHandling);
  1348. serializerProxy.TypeNameHandling = TypeNameHandling.All;
  1349. Assert.AreEqual(TypeNameHandling.All, serializerProxy.TypeNameHandling);
  1350. }
  1351. #if !(PORTABLE || PORTABLE40 || DNXCORE50)
  1352. [Test]
  1353. public void DeserializeISerializableIConvertible()
  1354. {
  1355. Ratio ratio = new Ratio(2, 1);
  1356. string json = JsonConvert.SerializeObject(ratio);
  1357. Assert.AreEqual(@"{""n"":2,""d"":1}", json);
  1358. Ratio ratio2 = JsonConvert.DeserializeObject<Ratio>(json);
  1359. Assert.AreEqual(ratio.Denominator, ratio2.Denominator);
  1360. Assert.AreEqual(ratio.Numerator, ratio2.Numerator);
  1361. }
  1362. public class PreserveReferencesCallbackTestObject : ISerializable
  1363. {
  1364. internal string _stringValue;
  1365. internal int _intValue;
  1366. internal PersonReference _person1;
  1367. internal PersonReference _person2;
  1368. internal PersonReference _person3;
  1369. internal PreserveReferencesCallbackTestObject _parent;
  1370. internal SerializationInfo _serializationInfo;
  1371. public PreserveReferencesCallbackTestObject(string stringValue, int intValue, PersonReference p1, PersonReference p2, PersonReference p3)
  1372. {
  1373. _stringValue = stringValue;
  1374. _intValue = intValue;
  1375. _person1 = p1;
  1376. _person2 = p2;
  1377. _person3 = p3;
  1378. }
  1379. protected PreserveReferencesCallbackTestObject(SerializationInfo info, StreamingContext context)
  1380. {
  1381. _serializationInfo = info;
  1382. }
  1383. public void GetObjectData(SerializationInfo info, StreamingContext context)
  1384. {
  1385. info.AddValue("stringValue", _stringValue);
  1386. info.AddValue("intValue", _intValue);
  1387. info.AddValue("person1", _person1, typeof(PersonReference));
  1388. info.AddValue("person2", _person2, typeof(PersonReference));
  1389. info.AddValue("person3", _person3, typeof(PersonReference));
  1390. info.AddValue("parent", _parent, typeof(PreserveReferencesCallbackTestObject));
  1391. }
  1392. [OnDeserialized]
  1393. private void OnDeserializedMethod(StreamingContext context)
  1394. {
  1395. if (_serializationInfo == null)
  1396. {
  1397. return;
  1398. }
  1399. _stringValue = _serializationInfo.GetString("stringValue");
  1400. _intValue = _serializationInfo.GetInt32("intValue");
  1401. _person1 = (PersonReference)_serializationInfo.GetValue("person1", typeof(PersonReference));
  1402. _person2 = (PersonReference)_serializationInfo.GetValue("person2", typeof(PersonReference));
  1403. _person3 = (PersonReference)_serializationInfo.GetValue("person3", typeof(PersonReference));
  1404. _parent = (PreserveReferencesCallbackTestObject)_serializationInfo.GetValue("parent", typeof(PreserveReferencesCallbackTestObject));
  1405. _serializationInfo = null;
  1406. }
  1407. }
  1408. [Test]
  1409. public void PreserveReferencesCallbackTest()
  1410. {
  1411. var p1 = new PersonReference
  1412. {
  1413. Name = "John Smith"
  1414. };
  1415. var p2 = new PersonReference
  1416. {
  1417. Name = "Mary Sue",
  1418. };
  1419. p1.Spouse = p2;
  1420. p2.Spouse = p1;
  1421. var obj = new PreserveReferencesCallbackTestObject("string!", 42, p1, p2, p1);
  1422. obj._parent = obj;
  1423. var settings = new JsonSerializerSettings
  1424. {
  1425. PreserveReferencesHandling = PreserveReferencesHandling.All,
  1426. Formatting = Formatting.Indented
  1427. };
  1428. string json = JsonConvert.SerializeObject(obj, settings);
  1429. StringAssert.AreEqual(json, @"{
  1430. ""$id"": ""1"",
  1431. ""stringValue"": ""string!"",
  1432. ""intValue"": 42,
  1433. ""person1"": {
  1434. ""$id"": ""2"",
  1435. ""Name"": ""John Smith"",
  1436. ""Spouse"": {
  1437. ""$id"": ""3"",
  1438. ""Name"": ""Mary Sue"",
  1439. ""Spouse"": {
  1440. ""$ref"": ""2""
  1441. }
  1442. }
  1443. },
  1444. ""person2"": {
  1445. ""$ref"": ""3""
  1446. },
  1447. ""person3"": {
  1448. ""$ref"": ""2""
  1449. },
  1450. ""parent"": {
  1451. ""$ref"": ""1""
  1452. }
  1453. }");
  1454. PreserveReferencesCallbackTestObject obj2 = JsonConvert.DeserializeObject<PreserveReferencesCallbackTestObject>(json);
  1455. Assert.AreEqual(obj._stringValue, obj2._stringValue);
  1456. Assert.AreEqual(obj._intValue, obj2._intValue);
  1457. Assert.AreEqual(obj._person1.Name, obj2._person1.Name);
  1458. Assert.AreEqual(obj._person2.Name, obj2._person2.Name);
  1459. Assert.AreEqual(obj._person3.Name, obj2._person3.Name);
  1460. Assert.AreEqual(obj2._person1, obj2._person3);
  1461. Assert.AreEqual(obj2._person1.Spouse, obj2._person2);
  1462. Assert.AreEqual(obj2._person2.Spouse, obj2._person1);
  1463. Assert.AreEqual(obj2._parent, obj2);
  1464. }
  1465. #endif
  1466. [Test]
  1467. public void DeserializeLargeFloat()
  1468. {
  1469. object o = JsonConvert.DeserializeObject("100000000000000000000000000000000000000.0");
  1470. CustomAssert.IsInstanceOfType(typeof(double), o);
  1471. Assert.IsTrue(MathUtils.ApproxEquals(1E+38, (double)o));
  1472. }
  1473. [Test]
  1474. public void SerializeDeserializeRegex()
  1475. {
  1476. Regex regex = new Regex("(hi)", RegexOptions.CultureInvariant);
  1477. string json = JsonConvert.SerializeObject(regex, Formatting.Indented);
  1478. Regex r2 = JsonConvert.DeserializeObject<Regex>(json);
  1479. Assert.AreEqual("(hi)", r2.ToString());
  1480. Assert.AreEqual(RegexOptions.CultureInvariant, r2.Options);
  1481. }
  1482. [Test]
  1483. public void EmbedJValueStringInNewJObject()
  1484. {
  1485. string s = null;
  1486. var v = new JValue(s);
  1487. var o = JObject.FromObject(new { title = v });
  1488. JObject oo = new JObject
  1489. {
  1490. { "title", v }
  1491. };
  1492. string output = o.ToString();
  1493. Assert.AreEqual(null, v.Value);
  1494. Assert.AreEqual(JTokenType.String, v.Type);
  1495. StringAssert.AreEqual(@"{
  1496. ""title"": null
  1497. }", output);
  1498. }
  1499. // bug: the generic member (T) that hides the base member will not
  1500. // be used when serializing and deserializing the object,
  1501. // resulting in unexpected behavior during serialization and deserialization.
  1502. public class Foo1
  1503. {
  1504. public object foo { get; set; }
  1505. }
  1506. public class Bar1
  1507. {
  1508. public object bar { get; set; }
  1509. }
  1510. public class Foo1<T> : Foo1
  1511. {
  1512. public new T foo { get; set; }
  1513. public T foo2 { get; set; }
  1514. }
  1515. public class FooBar1 : Foo1
  1516. {
  1517. public new Bar1 foo { get; set; }
  1518. }
  1519. [Test]
  1520. public void BaseClassSerializesAsExpected()
  1521. {
  1522. var original = new Foo1 { foo = "value" };
  1523. var json = JsonConvert.SerializeObject(original);
  1524. var expectedJson = @"{""foo"":""value""}";
  1525. Assert.AreEqual(expectedJson, json); // passes
  1526. }
  1527. [Test]
  1528. public void BaseClassDeserializesAsExpected()
  1529. {
  1530. var json = @"{""foo"":""value""}";
  1531. var deserialized = JsonConvert.DeserializeObject<Foo1>(json);
  1532. Assert.AreEqual("value", deserialized.foo); // passes
  1533. }
  1534. [Test]
  1535. public void DerivedClassHidingBasePropertySerializesAsExpected()
  1536. {
  1537. var original = new FooBar1 { foo = new Bar1 { bar = "value" } };
  1538. var json = JsonConvert.SerializeObject(original);
  1539. var expectedJson = @"{""foo"":{""bar"":""value""}}";
  1540. Assert.AreEqual(expectedJson, json); // passes
  1541. }
  1542. [Test]
  1543. public void DerivedClassHidingBasePropertyDeserializesAsExpected()
  1544. {
  1545. var json = @"{""foo"":{""bar"":""value""}}";
  1546. var deserialized = JsonConvert.DeserializeObject<FooBar1>(json);
  1547. Assert.IsNotNull(deserialized.foo); // passes
  1548. Assert.AreEqual("value", deserialized.foo.bar); // passes
  1549. }
  1550. [Test]
  1551. public void DerivedGenericClassHidingBasePropertySerializesAsExpected()
  1552. {
  1553. var original = new Foo1<Bar1> { foo = new Bar1 { bar = "value" }, foo2 = new Bar1 { bar = "value2" } };
  1554. var json = JsonConvert.SerializeObject(original);
  1555. var expectedJson = @"{""foo"":{""bar"":""value""},""foo2"":{""bar"":""value2""}}";
  1556. Assert.AreEqual(expectedJson, json);
  1557. }
  1558. [Test]
  1559. public void DerivedGenericClassHidingBasePropertyDeserializesAsExpected()
  1560. {
  1561. var json = @"{""foo"":{""bar"":""value""},""foo2"":{""bar"":""value2""}}";
  1562. var deserialized = JsonConvert.DeserializeObject<Foo1<Bar1>>(json);
  1563. Assert.IsNotNull(deserialized.foo2); // passes (bug only occurs for generics that /hide/ another property)
  1564. Assert.AreEqual("value2", deserialized.foo2.bar); // also passes, with no issue
  1565. Assert.IsNotNull(deserialized.foo);
  1566. Assert.AreEqual("value", deserialized.foo.bar);
  1567. }
  1568. [Test]
  1569. public void ConversionOperator()
  1570. {
  1571. // Creating a simple dictionary that has a non-string key
  1572. var dictStore = new Dictionary<DictionaryKeyCast, int>();
  1573. for (var i = 0; i < 800; i++)
  1574. {
  1575. dictStore.Add(new DictionaryKeyCast(i.ToString(CultureInfo.InvariantCulture), i), i);
  1576. }
  1577. var settings = new JsonSerializerSettings { Formatting = Formatting.Indented };
  1578. var jsonSerializer = JsonSerializer.Create(settings);
  1579. var ms = new MemoryStream();
  1580. var streamWriter = new StreamWriter(ms);
  1581. jsonSerializer.Serialize(streamWriter, dictStore);
  1582. streamWriter.Flush();
  1583. ms.Seek(0, SeekOrigin.Begin);
  1584. var stopWatch = Stopwatch.StartNew();
  1585. var deserialize = jsonSerializer.Deserialize(new StreamReader(ms), typeof(Dictionary<DictionaryKeyCast, int>));
  1586. stopWatch.Stop();
  1587. }
  1588. internal class DictionaryKeyCast
  1589. {
  1590. private String _name;
  1591. private int _number;
  1592. public DictionaryKeyCast(String name, int number)
  1593. {
  1594. _name = name;
  1595. _number = number;
  1596. }
  1597. public override string ToString()
  1598. {
  1599. return _name + " " + _number;
  1600. }
  1601. public static implicit operator DictionaryKeyCast(string dictionaryKey)
  1602. {
  1603. var strings = dictionaryKey.Split(' ');
  1604. return new DictionaryKeyCast(strings[0], Convert.ToInt32(strings[1]));
  1605. }
  1606. }
  1607. #if !(NET20 || NET35)
  1608. [DataContract]
  1609. public class BaseDataContractWithHidden
  1610. {
  1611. [DataMember(Name = "virtualMember")]
  1612. public virtual string VirtualMember { get; set; }
  1613. [DataMember(Name = "nonVirtualMember")]
  1614. public string NonVirtualMember { get; set; }
  1615. public virtual object NewMember { get; set; }
  1616. }
  1617. public class ChildDataContractWithHidden : BaseDataContractWithHidden
  1618. {
  1619. [DataMember(Name = "NewMember")]
  1620. public new virtual string NewMember { get; set; }
  1621. public override string VirtualMember { get; set; }
  1622. public string AddedMember { get; set; }
  1623. }
  1624. [Test]
  1625. public void ChildDataContractTestWithHidden()
  1626. {
  1627. var cc = new ChildDataContractWithHidden
  1628. {
  1629. VirtualMember = "VirtualMember!",
  1630. NonVirtualMember = "NonVirtualMember!",
  1631. NewMember = "NewMember!"
  1632. };
  1633. string result = JsonConvert.SerializeObject(cc);
  1634. Assert.AreEqual(@"{""NewMember"":""NewMember!"",""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  1635. }
  1636. // ignore hiding members compiler warning
  1637. #pragma warning disable 108, 114
  1638. [DataContract]
  1639. public class BaseWithContract
  1640. {
  1641. [DataMember(Name = "VirtualWithDataMemberBase")]
  1642. public virtual string VirtualWithDataMember { get; set; }
  1643. [DataMember]
  1644. public virtual string Virtual { get; set; }
  1645. [DataMember(Name = "WithDataMemberBase")]
  1646. public string WithDataMember { get; set; }
  1647. [DataMember]
  1648. public string JustAProperty { get; set; }
  1649. }
  1650. [DataContract]
  1651. public class BaseWithoutContract
  1652. {
  1653. [DataMember(Name = "VirtualWithDataMemberBase")]
  1654. public virtual string VirtualWithDataMember { get; set; }
  1655. [DataMember]
  1656. public virtual string Virtual { get; set; }
  1657. [DataMember(Name = "WithDataMemberBase")]
  1658. public string WithDataMember { get; set; }
  1659. [DataMember]
  1660. public string JustAProperty { get; set; }
  1661. }
  1662. [DataContract]
  1663. public class SubWithoutContractNewProperties : BaseWithContract
  1664. {
  1665. [DataMember(Name = "VirtualWithDataMemberSub")]
  1666. public string VirtualWithDataMember { get; set; }
  1667. public string Virtual { get; set; }
  1668. [DataMember(Name = "WithDataMemberSub")]
  1669. public string WithDataMember { get; set; }
  1670. public string JustAProperty { get; set; }
  1671. }
  1672. [DataContract]
  1673. public class SubWithoutContractVirtualProperties : BaseWithContract
  1674. {
  1675. public override string VirtualWithDataMember { get; set; }
  1676. [DataMember(Name = "VirtualSub")]
  1677. public override string Virtual { get; set; }
  1678. }
  1679. [DataContract]
  1680. public class SubWithContractNewProperties : BaseWithContract
  1681. {
  1682. [DataMember(Name = "VirtualWithDataMemberSub")]
  1683. public string VirtualWithDataMember { get; set; }
  1684. [DataMember(Name = "Virtual2")]
  1685. public string Virtual { get; set; }
  1686. [DataMember(Name = "WithDataMemberSub")]
  1687. public string WithDataMember { get; set; }
  1688. [DataMember(Name = "JustAProperty2")]
  1689. public string JustAProperty { get; set; }
  1690. }
  1691. [DataContract]
  1692. public class SubWithContractVirtualProperties : BaseWithContract
  1693. {
  1694. [DataMember(Name = "VirtualWithDataMemberSub")]
  1695. public virtual string VirtualWithDataMember { get; set; }
  1696. }
  1697. #pragma warning restore 108, 114
  1698. [Test]
  1699. public void SubWithoutContractNewPropertiesTest()
  1700. {
  1701. BaseWithContract baseWith = new SubWithoutContractNewProperties
  1702. {
  1703. JustAProperty = "JustAProperty!",
  1704. Virtual = "Virtual!",
  1705. VirtualWithDataMember = "VirtualWithDataMember!",
  1706. WithDataMember = "WithDataMember!"
  1707. };
  1708. baseWith.JustAProperty = "JustAProperty2!";
  1709. baseWith.Virtual = "Virtual2!";
  1710. baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
  1711. baseWith.WithDataMember = "WithDataMember2!";
  1712. string json = AssertSerializeDeserializeEqual(baseWith);
  1713. StringAssert.AreEqual(@"{
  1714. ""JustAProperty"": ""JustAProperty2!"",
  1715. ""Virtual"": ""Virtual2!"",
  1716. ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
  1717. ""VirtualWithDataMemberSub"": ""VirtualWithDataMember!"",
  1718. ""WithDataMemberBase"": ""WithDataMember2!"",
  1719. ""WithDataMemberSub"": ""WithDataMember!""
  1720. }", json);
  1721. }
  1722. [Test]
  1723. public void SubWithoutContractVirtualPropertiesTest()
  1724. {
  1725. BaseWithContract baseWith = new SubWithoutContractVirtualProperties
  1726. {
  1727. JustAProperty = "JustAProperty!",
  1728. Virtual = "Virtual!",
  1729. VirtualWithDataMember = "VirtualWithDataMember!",
  1730. WithDataMember = "WithDataMember!"
  1731. };
  1732. baseWith.JustAProperty = "JustAProperty2!";
  1733. baseWith.Virtual = "Virtual2!";
  1734. baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
  1735. baseWith.WithDataMember = "WithDataMember2!";
  1736. string json = JsonConvert.SerializeObject(baseWith, Formatting.Indented);
  1737. StringAssert.AreEqual(@"{
  1738. ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
  1739. ""VirtualSub"": ""Virtual2!"",
  1740. ""WithDataMemberBase"": ""WithDataMember2!"",
  1741. ""JustAProperty"": ""JustAProperty2!""
  1742. }", json);
  1743. }
  1744. [Test]
  1745. public void SubWithContractNewPropertiesTest()
  1746. {
  1747. BaseWithContract baseWith = new SubWithContractNewProperties
  1748. {
  1749. JustAProperty = "JustAProperty!",
  1750. Virtual = "Virtual!",
  1751. VirtualWithDataMember = "VirtualWithDataMember!",
  1752. WithDataMember = "WithDataMember!"
  1753. };
  1754. baseWith.JustAProperty = "JustAProperty2!";
  1755. baseWith.Virtual = "Virtual2!";
  1756. baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
  1757. baseWith.WithDataMember = "WithDataMember2!";
  1758. string json = AssertSerializeDeserializeEqual(baseWith);
  1759. StringAssert.AreEqual(@"{
  1760. ""JustAProperty"": ""JustAProperty2!"",
  1761. ""JustAProperty2"": ""JustAProperty!"",
  1762. ""Virtual"": ""Virtual2!"",
  1763. ""Virtual2"": ""Virtual!"",
  1764. ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
  1765. ""VirtualWithDataMemberSub"": ""VirtualWithDataMember!"",
  1766. ""WithDataMemberBase"": ""WithDataMember2!"",
  1767. ""WithDataMemberSub"": ""WithDataMember!""
  1768. }", json);
  1769. }
  1770. [Test]
  1771. public void SubWithContractVirtualPropertiesTest()
  1772. {
  1773. BaseWithContract baseWith = new SubWithContractVirtualProperties
  1774. {
  1775. JustAProperty = "JustAProperty!",
  1776. Virtual = "Virtual!",
  1777. VirtualWithDataMember = "VirtualWithDataMember!",
  1778. WithDataMember = "WithDataMember!"
  1779. };
  1780. baseWith.JustAProperty = "JustAProperty2!";
  1781. baseWith.Virtual = "Virtual2!";
  1782. baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
  1783. baseWith.WithDataMember = "WithDataMember2!";
  1784. string json = AssertSerializeDeserializeEqual(baseWith);
  1785. StringAssert.AreEqual(@"{
  1786. ""JustAProperty"": ""JustAProperty2!"",
  1787. ""Virtual"": ""Virtual2!"",
  1788. ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
  1789. ""VirtualWithDataMemberSub"": ""VirtualWithDataMember!"",
  1790. ""WithDataMemberBase"": ""WithDataMember2!""
  1791. }", json);
  1792. }
  1793. private string AssertSerializeDeserializeEqual(object o)
  1794. {
  1795. MemoryStream ms = new MemoryStream();
  1796. DataContractJsonSerializer s = new DataContractJsonSerializer(o.GetType());
  1797. s.WriteObject(ms, o);
  1798. var data = ms.ToArray();
  1799. JObject dataContractJson = JObject.Parse(Encoding.UTF8.GetString(data, 0, data.Length));
  1800. dataContractJson = new JObject(dataContractJson.Properties().OrderBy(p => p.Name));
  1801. JObject jsonNetJson = JObject.Parse(JsonConvert.SerializeObject(o));
  1802. jsonNetJson = new JObject(jsonNetJson.Properties().OrderBy(p => p.Name));
  1803. //Console.WriteLine("Results for " + o.GetType().Name);
  1804. //Console.WriteLine("DataContractJsonSerializer: " + dataContractJson);
  1805. //Console.WriteLine("JsonDotNetSerializer : " + jsonNetJson);
  1806. Assert.AreEqual(dataContractJson.Count, jsonNetJson.Count);
  1807. foreach (KeyValuePair<string, JToken> property in dataContractJson)
  1808. {
  1809. Assert.IsTrue(JToken.DeepEquals(jsonNetJson[property.Key], property.Value), "Property not equal: " + property.Key);
  1810. }
  1811. return jsonNetJson.ToString();
  1812. }
  1813. #endif
  1814. [Test]
  1815. public void PersonTypedObjectDeserialization()
  1816. {
  1817. Store store = new Store();
  1818. string jsonText = JsonConvert.SerializeObject(store);
  1819. Store deserializedStore = (Store)JsonConvert.DeserializeObject(jsonText, typeof(Store));
  1820. Assert.AreEqual(store.Establised, deserializedStore.Establised);
  1821. Assert.AreEqual(store.product.Count, deserializedStore.product.Count);
  1822. Console.WriteLine(jsonText);
  1823. }
  1824. [Test]
  1825. public void TypedObjectDeserialization()
  1826. {
  1827. Product product = new Product();
  1828. product.Name = "Apple";
  1829. product.ExpiryDate = new DateTime(2008, 12, 28);
  1830. product.Price = 3.99M;
  1831. product.Sizes = new string[] { "Small", "Medium", "Large" };
  1832. string output = JsonConvert.SerializeObject(product);
  1833. //{
  1834. // "Name": "Apple",
  1835. // "ExpiryDate": "\/Date(1230375600000+1300)\/",
  1836. // "Price": 3.99,
  1837. // "Sizes": [
  1838. // "Small",
  1839. // "Medium",
  1840. // "Large"
  1841. // ]
  1842. //}
  1843. Product deserializedProduct = (Product)JsonConvert.DeserializeObject(output, typeof(Product));
  1844. Assert.AreEqual("Apple", deserializedProduct.Name);
  1845. Assert.AreEqual(new DateTime(2008, 12, 28), deserializedProduct.ExpiryDate);
  1846. Assert.AreEqual(3.99m, deserializedProduct.Price);
  1847. Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
  1848. Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
  1849. Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
  1850. }
  1851. //[Test]
  1852. //public void Advanced()
  1853. //{
  1854. // Product product = new Product();
  1855. // product.ExpiryDate = new DateTime(2008, 12, 28);
  1856. // JsonSerializer serializer = new JsonSerializer();
  1857. // serializer.Converters.Add(new JavaScriptDateTimeConverter());
  1858. // serializer.NullValueHandling = NullValueHandling.Ignore;
  1859. // using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
  1860. // using (JsonWriter writer = new JsonTextWriter(sw))
  1861. // {
  1862. // serializer.Serialize(writer, product);
  1863. // // {"ExpiryDate":new Date(1230375600000),"Price":0}
  1864. // }
  1865. //}
  1866. [Test]
  1867. public void JsonConvertSerializer()
  1868. {
  1869. string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
  1870. Product p = JsonConvert.DeserializeObject(value, typeof(Product)) as Product;
  1871. Assert.AreEqual("Orange", p.Name);
  1872. Assert.AreEqual(new DateTime(2010, 1, 24, 12, 0, 0), p.ExpiryDate);
  1873. Assert.AreEqual(3.99m, p.Price);
  1874. }
  1875. [Test]
  1876. public void DeserializeJavaScriptDate()
  1877. {
  1878. DateTime dateValue = new DateTime(2010, 3, 30);
  1879. Dictionary<string, object> testDictionary = new Dictionary<string, object>();
  1880. testDictionary["date"] = dateValue;
  1881. string jsonText = JsonConvert.SerializeObject(testDictionary);
  1882. #if !(NET20 || NET35)
  1883. MemoryStream ms = new MemoryStream();
  1884. DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<string, object>));
  1885. serializer.WriteObject(ms, testDictionary);
  1886. byte[] data = ms.ToArray();
  1887. string output = Encoding.UTF8.GetString(data, 0, data.Length);
  1888. #endif
  1889. Dictionary<string, object> deserializedDictionary = (Dictionary<string, object>)JsonConvert.DeserializeObject(jsonText, typeof(Dictionary<string, object>));
  1890. DateTime deserializedDate = (DateTime)deserializedDictionary["date"];
  1891. Assert.AreEqual(dateValue, deserializedDate);
  1892. }
  1893. [Test]
  1894. public void TestMethodExecutorObject()
  1895. {
  1896. MethodExecutorObject executorObject = new MethodExecutorObject();
  1897. executorObject.serverClassName = "BanSubs";
  1898. executorObject.serverMethodParams = new object[] { "21321546", "101", "1236", "D:\\1.txt" };
  1899. executorObject.clientGetResultFunction = "ClientBanSubsCB";
  1900. string output = JsonConvert.SerializeObject(executorObject);
  1901. MethodExecutorObject executorObject2 = JsonConvert.DeserializeObject(output, typeof(MethodExecutorObject)) as MethodExecutorObject;
  1902. Assert.AreNotSame(executorObject, executorObject2);
  1903. Assert.AreEqual(executorObject2.serverClassName, "BanSubs");
  1904. Assert.AreEqual(executorObject2.serverMethodParams.Length, 4);
  1905. CustomAssert.Contains(executorObject2.serverMethodParams, "101");
  1906. Assert.AreEqual(executorObject2.clientGetResultFunction, "ClientBanSubsCB");
  1907. }
  1908. #if !(DNXCORE50)
  1909. [Test]
  1910. public void HashtableDeserialization()
  1911. {
  1912. string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
  1913. Hashtable p = JsonConvert.DeserializeObject(value, typeof(Hashtable)) as Hashtable;
  1914. Assert.AreEqual("Orange", p["Name"].ToString());
  1915. }
  1916. [Test]
  1917. public void TypedHashtableDeserialization()
  1918. {
  1919. string value = @"{""Name"":""Orange"", ""Hash"":{""ExpiryDate"":""01/24/2010 12:00:00"",""UntypedArray"":[""01/24/2010 12:00:00""]}}";
  1920. TypedSubHashtable p = JsonConvert.DeserializeObject(value, typeof(TypedSubHashtable)) as TypedSubHashtable;
  1921. Assert.AreEqual("01/24/2010 12:00:00", p.Hash["ExpiryDate"].ToString());
  1922. StringAssert.AreEqual(@"[
  1923. ""01/24/2010 12:00:00""
  1924. ]", p.Hash["UntypedArray"].ToString());
  1925. }
  1926. #endif
  1927. [Test]
  1928. public void SerializeDeserializeGetOnlyProperty()
  1929. {
  1930. string value = JsonConvert.SerializeObject(new GetOnlyPropertyClass());
  1931. GetOnlyPropertyClass c = JsonConvert.DeserializeObject<GetOnlyPropertyClass>(value);
  1932. Assert.AreEqual(c.Field, "Field");
  1933. Assert.AreEqual(c.GetOnlyProperty, "GetOnlyProperty");
  1934. }
  1935. [Test]
  1936. public void SerializeDeserializeSetOnlyProperty()
  1937. {
  1938. string value = JsonConvert.SerializeObject(new SetOnlyPropertyClass());
  1939. SetOnlyPropertyClass c = JsonConvert.DeserializeObject<SetOnlyPropertyClass>(value);
  1940. Assert.AreEqual(c.Field, "Field");
  1941. }
  1942. [Test]
  1943. public void JsonIgnoreAttributeTest()
  1944. {
  1945. string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeTestClass());
  1946. Assert.AreEqual(@"{""Field"":0,""Property"":21}", json);
  1947. JsonIgnoreAttributeTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeTestClass>(@"{""Field"":99,""Property"":-1,""IgnoredField"":-1,""IgnoredObject"":[1,2,3,4,5]}");
  1948. Assert.AreEqual(0, c.IgnoredField);
  1949. Assert.AreEqual(99, c.Field);
  1950. }
  1951. [Test]
  1952. public void GoogleSearchAPI()
  1953. {
  1954. string json = @"{
  1955. results:
  1956. [
  1957. {
  1958. GsearchResultClass:""GwebSearch"",
  1959. unescapedUrl : ""http://www.google.com/"",
  1960. url : ""http://www.google.com/"",
  1961. visibleUrl : ""www.google.com"",
  1962. cacheUrl :
  1963. ""http://www.google.com/search?q=cache:zhool8dxBV4J:www.google.com"",
  1964. title : ""Google"",
  1965. titleNoFormatting : ""Google"",
  1966. content : ""Enables users to search the Web, Usenet, and
  1967. images. Features include PageRank, caching and translation of
  1968. results, and an option to find similar pages.""
  1969. },
  1970. {
  1971. GsearchResultClass:""GwebSearch"",
  1972. unescapedUrl : ""http://news.google.com/"",
  1973. url : ""http://news.google.com/"",
  1974. visibleUrl : ""news.google.com"",
  1975. cacheUrl :
  1976. ""http://www.google.com/search?q=cache:Va_XShOz_twJ:news.google.com"",
  1977. title : ""Google News"",
  1978. titleNoFormatting : ""Google News"",
  1979. content : ""Aggregated headlines and a search engine of many of the world's news sources.""
  1980. },
  1981. {
  1982. GsearchResultClass:""GwebSearch"",
  1983. unescapedUrl : ""http://groups.google.com/"",
  1984. url : ""http://groups.google.com/"",
  1985. visibleUrl : ""groups.google.com"",
  1986. cacheUrl :
  1987. ""http://www.google.com/search?q=cache:x2uPD3hfkn0J:groups.google.com"",
  1988. title : ""Google Groups"",
  1989. titleNoFormatting : ""Google Groups"",
  1990. content : ""Enables users to search and browse the Usenet
  1991. archives which consist of over 700 million messages, and post new
  1992. comments.""
  1993. },
  1994. {
  1995. GsearchResultClass:""GwebSearch"",
  1996. unescapedUrl : ""http://maps.google.com/"",
  1997. url : ""http://maps.google.com/"",
  1998. visibleUrl : ""maps.google.com"",
  1999. cacheUrl :
  2000. ""http://www.google.com/search?q=cache:dkf5u2twBXIJ:maps.google.com"",
  2001. title : ""Google Maps"",
  2002. titleNoFormatting : ""Google Maps"",
  2003. content : ""Provides directions, interactive maps, and
  2004. satellite/aerial imagery of the United States. Can also search by
  2005. keyword such as type of business.""
  2006. }
  2007. ],
  2008. adResults:
  2009. [
  2010. {
  2011. GsearchResultClass:""GwebSearch.ad"",
  2012. title : ""Gartner Symposium/ITxpo"",
  2013. content1 : ""Meet brilliant Gartner IT analysts"",
  2014. content2 : ""20-23 May 2007- Barcelona, Spain"",
  2015. url :
  2016. ""http://www.google.com/url?sa=L&ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB&num=1&q=http://www.gartner.com/it/sym/2007/spr8/spr8.jsp%3Fsrc%3D_spain_07_%26WT.srch%3D1&usg=__CxRH06E4Xvm9Muq13S4MgMtnziY="",
  2017. impressionUrl :
  2018. ""http://www.google.com/uds/css/ad-indicator-on.gif?ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB"",
  2019. unescapedUrl :
  2020. ""http://www.google.com/url?sa=L&ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB&num=1&q=http://www.gartner.com/it/sym/2007/spr8/spr8.jsp%3Fsrc%3D_spain_07_%26WT.srch%3D1&usg=__CxRH06E4Xvm9Muq13S4MgMtnziY="",
  2021. visibleUrl : ""www.gartner.com""
  2022. }
  2023. ]
  2024. }
  2025. ";
  2026. object o = JsonConvert.DeserializeObject(json);
  2027. string s = string.Empty;
  2028. s += s;
  2029. }
  2030. [Test]
  2031. public void TorrentDeserializeTest()
  2032. {
  2033. string jsonText = @"{
  2034. """":"""",
  2035. ""label"": [
  2036. [""SomeName"",6]
  2037. ],
  2038. ""torrents"": [
  2039. [""192D99A5C943555CB7F00A852821CF6D6DB3008A"",201,""filename.avi"",178311826,1000,178311826,72815250,408,1603,7,121430,""NameOfLabelPrevioslyDefined"",3,6,0,8,128954,-1,0],
  2040. ],
  2041. ""torrentc"": ""1816000723""
  2042. }";
  2043. JObject o = (JObject)JsonConvert.DeserializeObject(jsonText);
  2044. Assert.AreEqual(4, o.Children().Count());
  2045. JToken torrentsArray = (JToken)o["torrents"];
  2046. JToken nestedTorrentsArray = (JToken)torrentsArray[0];
  2047. Assert.AreEqual(nestedTorrentsArray.Children().Count(), 19);
  2048. }
  2049. [Test]
  2050. public void JsonPropertyClassSerialize()
  2051. {
  2052. JsonPropertyClass test = new JsonPropertyClass();
  2053. test.Pie = "Delicious";
  2054. test.SweetCakesCount = int.MaxValue;
  2055. string jsonText = JsonConvert.SerializeObject(test);
  2056. Assert.AreEqual(@"{""pie"":""Delicious"",""pie1"":""PieChart!"",""sweet_cakes_count"":2147483647}", jsonText);
  2057. JsonPropertyClass test2 = JsonConvert.DeserializeObject<JsonPropertyClass>(jsonText);
  2058. Assert.AreEqual(test.Pie, test2.Pie);
  2059. Assert.AreEqual(test.SweetCakesCount, test2.SweetCakesCount);
  2060. }
  2061. [Test]
  2062. public void BadJsonPropertyClassSerialize()
  2063. {
  2064. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.SerializeObject(new BadJsonPropertyClass()); }, @"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name.");
  2065. }
  2066. [Test]
  2067. public void InvalidBackslash()
  2068. {
  2069. string json = @"[""vvv\jvvv""]";
  2070. ExceptionAssert.Throws<JsonReaderException>(() => { JsonConvert.DeserializeObject<List<string>>(json); }, @"Bad JSON escape sequence: \j. Path '', line 1, position 7.");
  2071. }
  2072. #if !(NET20 || NET35)
  2073. [Test]
  2074. public void Unicode()
  2075. {
  2076. string json = @"[""PRE\u003cPOST""]";
  2077. DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<string>));
  2078. List<string> dataContractResult = (List<string>)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
  2079. List<string> jsonNetResult = JsonConvert.DeserializeObject<List<string>>(json);
  2080. Assert.AreEqual(1, jsonNetResult.Count);
  2081. Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
  2082. }
  2083. [Test]
  2084. public void BackslashEqivilence()
  2085. {
  2086. string json = @"[""vvv\/vvv\tvvv\""vvv\bvvv\nvvv\rvvv\\vvv\fvvv""]";
  2087. #if !(DNXCORE50)
  2088. JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
  2089. List<string> javaScriptSerializerResult = javaScriptSerializer.Deserialize<List<string>>(json);
  2090. #endif
  2091. DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<string>));
  2092. List<string> dataContractResult = (List<string>)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
  2093. List<string> jsonNetResult = JsonConvert.DeserializeObject<List<string>>(json);
  2094. Assert.AreEqual(1, jsonNetResult.Count);
  2095. Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
  2096. #if !(DNXCORE50)
  2097. Assert.AreEqual(javaScriptSerializerResult[0], jsonNetResult[0]);
  2098. #endif
  2099. }
  2100. [Test]
  2101. public void DateTimeTest()
  2102. {
  2103. List<DateTime> testDates = new List<DateTime>
  2104. {
  2105. new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Local),
  2106. new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
  2107. new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc),
  2108. new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local),
  2109. new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
  2110. new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc),
  2111. };
  2112. MemoryStream ms = new MemoryStream();
  2113. DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<DateTime>));
  2114. s.WriteObject(ms, testDates);
  2115. ms.Seek(0, SeekOrigin.Begin);
  2116. StreamReader sr = new StreamReader(ms);
  2117. string expected = sr.ReadToEnd();
  2118. string result = JsonConvert.SerializeObject(testDates, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
  2119. Assert.AreEqual(expected, result);
  2120. }
  2121. [Test]
  2122. public void DateTimeOffsetIso()
  2123. {
  2124. List<DateTimeOffset> testDates = new List<DateTimeOffset>
  2125. {
  2126. new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
  2127. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
  2128. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
  2129. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
  2130. };
  2131. string result = JsonConvert.SerializeObject(testDates);
  2132. Assert.AreEqual(@"[""0100-01-01T01:01:01+00:00"",""2000-01-01T01:01:01+00:00"",""2000-01-01T01:01:01+13:00"",""2000-01-01T01:01:01-03:30""]", result);
  2133. }
  2134. [Test]
  2135. public void DateTimeOffsetMsAjax()
  2136. {
  2137. List<DateTimeOffset> testDates = new List<DateTimeOffset>
  2138. {
  2139. new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
  2140. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
  2141. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
  2142. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
  2143. };
  2144. string result = JsonConvert.SerializeObject(testDates, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
  2145. Assert.AreEqual(@"[""\/Date(-59011455539000+0000)\/"",""\/Date(946688461000+0000)\/"",""\/Date(946641661000+1300)\/"",""\/Date(946701061000-0330)\/""]", result);
  2146. }
  2147. #endif
  2148. [Test]
  2149. public void NonStringKeyDictionary()
  2150. {
  2151. Dictionary<int, int> values = new Dictionary<int, int>();
  2152. values.Add(-5, 6);
  2153. values.Add(int.MinValue, int.MaxValue);
  2154. string json = JsonConvert.SerializeObject(values);
  2155. Assert.AreEqual(@"{""-5"":6,""-2147483648"":2147483647}", json);
  2156. Dictionary<int, int> newValues = JsonConvert.DeserializeObject<Dictionary<int, int>>(json);
  2157. CollectionAssert.AreEqual(values, newValues);
  2158. }
  2159. [Test]
  2160. public void AnonymousObjectSerialization()
  2161. {
  2162. var anonymous =
  2163. new
  2164. {
  2165. StringValue = "I am a string",
  2166. IntValue = int.MaxValue,
  2167. NestedAnonymous = new { NestedValue = byte.MaxValue },
  2168. NestedArray = new[] { 1, 2 },
  2169. Product = new Product() { Name = "TestProduct" }
  2170. };
  2171. string json = JsonConvert.SerializeObject(anonymous);
  2172. Assert.AreEqual(@"{""StringValue"":""I am a string"",""IntValue"":2147483647,""NestedAnonymous"":{""NestedValue"":255},""NestedArray"":[1,2],""Product"":{""Name"":""TestProduct"",""ExpiryDate"":""2000-01-01T00:00:00Z"",""Price"":0.0,""Sizes"":null}}", json);
  2173. anonymous = JsonConvert.DeserializeAnonymousType(json, anonymous);
  2174. Assert.AreEqual("I am a string", anonymous.StringValue);
  2175. Assert.AreEqual(int.MaxValue, anonymous.IntValue);
  2176. Assert.AreEqual(255, anonymous.NestedAnonymous.NestedValue);
  2177. Assert.AreEqual(2, anonymous.NestedArray.Length);
  2178. Assert.AreEqual(1, anonymous.NestedArray[0]);
  2179. Assert.AreEqual(2, anonymous.NestedArray[1]);
  2180. Assert.AreEqual("TestProduct", anonymous.Product.Name);
  2181. }
  2182. [Test]
  2183. public void AnonymousObjectSerializationWithSetting()
  2184. {
  2185. DateTime d = new DateTime(2000, 1, 1);
  2186. var anonymous =
  2187. new
  2188. {
  2189. DateValue = d
  2190. };
  2191. JsonSerializerSettings settings = new JsonSerializerSettings();
  2192. settings.Converters.Add(new IsoDateTimeConverter
  2193. {
  2194. DateTimeFormat = "yyyy"
  2195. });
  2196. string json = JsonConvert.SerializeObject(anonymous, settings);
  2197. Assert.AreEqual(@"{""DateValue"":""2000""}", json);
  2198. anonymous = JsonConvert.DeserializeAnonymousType(json, anonymous, settings);
  2199. Assert.AreEqual(d, anonymous.DateValue);
  2200. }
  2201. [Test]
  2202. public void SerializeObject()
  2203. {
  2204. string json = JsonConvert.SerializeObject(new object());
  2205. Assert.AreEqual("{}", json);
  2206. }
  2207. [Test]
  2208. public void SerializeNull()
  2209. {
  2210. string json = JsonConvert.SerializeObject(null);
  2211. Assert.AreEqual("null", json);
  2212. }
  2213. [Test]
  2214. public void CanDeserializeIntArrayWhenNotFirstPropertyInJson()
  2215. {
  2216. string json = "{foo:'hello',bar:[1,2,3]}";
  2217. ClassWithArray wibble = JsonConvert.DeserializeObject<ClassWithArray>(json);
  2218. Assert.AreEqual("hello", wibble.Foo);
  2219. Assert.AreEqual(4, wibble.Bar.Count);
  2220. Assert.AreEqual(int.MaxValue, wibble.Bar[0]);
  2221. Assert.AreEqual(1, wibble.Bar[1]);
  2222. Assert.AreEqual(2, wibble.Bar[2]);
  2223. Assert.AreEqual(3, wibble.Bar[3]);
  2224. }
  2225. [Test]
  2226. public void CanDeserializeIntArray_WhenArrayIsFirstPropertyInJson()
  2227. {
  2228. string json = "{bar:[1,2,3], foo:'hello'}";
  2229. ClassWithArray wibble = JsonConvert.DeserializeObject<ClassWithArray>(json);
  2230. Assert.AreEqual("hello", wibble.Foo);
  2231. Assert.AreEqual(4, wibble.Bar.Count);
  2232. Assert.AreEqual(int.MaxValue, wibble.Bar[0]);
  2233. Assert.AreEqual(1, wibble.Bar[1]);
  2234. Assert.AreEqual(2, wibble.Bar[2]);
  2235. Assert.AreEqual(3, wibble.Bar[3]);
  2236. }
  2237. [Test]
  2238. public void ObjectCreationHandlingReplace()
  2239. {
  2240. string json = "{bar:[1,2,3], foo:'hello'}";
  2241. JsonSerializer s = new JsonSerializer();
  2242. s.ObjectCreationHandling = ObjectCreationHandling.Replace;
  2243. ClassWithArray wibble = (ClassWithArray)s.Deserialize(new StringReader(json), typeof(ClassWithArray));
  2244. Assert.AreEqual("hello", wibble.Foo);
  2245. Assert.AreEqual(1, wibble.Bar.Count);
  2246. }
  2247. [Test]
  2248. public void CanDeserializeSerializedJson()
  2249. {
  2250. ClassWithArray wibble = new ClassWithArray();
  2251. wibble.Foo = "hello";
  2252. wibble.Bar.Add(1);
  2253. wibble.Bar.Add(2);
  2254. wibble.Bar.Add(3);
  2255. string json = JsonConvert.SerializeObject(wibble);
  2256. ClassWithArray wibbleOut = JsonConvert.DeserializeObject<ClassWithArray>(json);
  2257. Assert.AreEqual("hello", wibbleOut.Foo);
  2258. Assert.AreEqual(5, wibbleOut.Bar.Count);
  2259. Assert.AreEqual(int.MaxValue, wibbleOut.Bar[0]);
  2260. Assert.AreEqual(int.MaxValue, wibbleOut.Bar[1]);
  2261. Assert.AreEqual(1, wibbleOut.Bar[2]);
  2262. Assert.AreEqual(2, wibbleOut.Bar[3]);
  2263. Assert.AreEqual(3, wibbleOut.Bar[4]);
  2264. }
  2265. [Test]
  2266. public void SerializeConverableObjects()
  2267. {
  2268. string json = JsonConvert.SerializeObject(new ConverableMembers(), Formatting.Indented);
  2269. string expected = null;
  2270. #if !(PORTABLE || DNXCORE50)
  2271. expected = @"{
  2272. ""String"": ""string"",
  2273. ""Int32"": 2147483647,
  2274. ""UInt32"": 4294967295,
  2275. ""Byte"": 255,
  2276. ""SByte"": 127,
  2277. ""Short"": 32767,
  2278. ""UShort"": 65535,
  2279. ""Long"": 9223372036854775807,
  2280. ""ULong"": 9223372036854775807,
  2281. ""Double"": 1.7976931348623157E+308,
  2282. ""Float"": 3.40282347E+38,
  2283. ""DBNull"": null,
  2284. ""Bool"": true,
  2285. ""Char"": ""\u0000""
  2286. }";
  2287. #else
  2288. expected = @"{
  2289. ""String"": ""string"",
  2290. ""Int32"": 2147483647,
  2291. ""UInt32"": 4294967295,
  2292. ""Byte"": 255,
  2293. ""SByte"": 127,
  2294. ""Short"": 32767,
  2295. ""UShort"": 65535,
  2296. ""Long"": 9223372036854775807,
  2297. ""ULong"": 9223372036854775807,
  2298. ""Double"": 1.7976931348623157E+308,
  2299. ""Float"": 3.40282347E+38,
  2300. ""Bool"": true,
  2301. ""Char"": ""\u0000""
  2302. }";
  2303. #endif
  2304. StringAssert.AreEqual(expected, json);
  2305. ConverableMembers c = JsonConvert.DeserializeObject<ConverableMembers>(json);
  2306. Assert.AreEqual("string", c.String);
  2307. Assert.AreEqual(double.MaxValue, c.Double);
  2308. #if !(PORTABLE || DNXCORE50 || PORTABLE40)
  2309. Assert.AreEqual(DBNull.Value, c.DBNull);
  2310. #endif
  2311. }
  2312. [Test]
  2313. public void SerializeStack()
  2314. {
  2315. Stack<object> s = new Stack<object>();
  2316. s.Push(1);
  2317. s.Push(2);
  2318. s.Push(3);
  2319. string json = JsonConvert.SerializeObject(s);
  2320. Assert.AreEqual("[3,2,1]", json);
  2321. }
  2322. [Test]
  2323. public void FormattingOverride()
  2324. {
  2325. var obj = new { Formatting = "test" };
  2326. JsonSerializerSettings settings = new JsonSerializerSettings { Formatting = Formatting.Indented };
  2327. string indented = JsonConvert.SerializeObject(obj, settings);
  2328. string none = JsonConvert.SerializeObject(obj, Formatting.None, settings);
  2329. Assert.AreNotEqual(indented, none);
  2330. }
  2331. [Test]
  2332. public void DateTimeTimeZone()
  2333. {
  2334. var date = new DateTime(2001, 4, 4, 0, 0, 0, DateTimeKind.Utc);
  2335. string json = JsonConvert.SerializeObject(date);
  2336. Assert.AreEqual(@"""2001-04-04T00:00:00Z""", json);
  2337. }
  2338. [Test]
  2339. public void GuidTest()
  2340. {
  2341. Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
  2342. string json = JsonConvert.SerializeObject(new ClassWithGuid { GuidField = guid });
  2343. Assert.AreEqual(@"{""GuidField"":""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""}", json);
  2344. ClassWithGuid c = JsonConvert.DeserializeObject<ClassWithGuid>(json);
  2345. Assert.AreEqual(guid, c.GuidField);
  2346. }
  2347. [Test]
  2348. public void EnumTest()
  2349. {
  2350. string json = JsonConvert.SerializeObject(StringComparison.CurrentCultureIgnoreCase);
  2351. Assert.AreEqual(@"1", json);
  2352. StringComparison s = JsonConvert.DeserializeObject<StringComparison>(json);
  2353. Assert.AreEqual(StringComparison.CurrentCultureIgnoreCase, s);
  2354. }
  2355. public class ClassWithTimeSpan
  2356. {
  2357. public TimeSpan TimeSpanField;
  2358. }
  2359. [Test]
  2360. public void TimeSpanTest()
  2361. {
  2362. TimeSpan ts = new TimeSpan(00, 23, 59, 1);
  2363. string json = JsonConvert.SerializeObject(new ClassWithTimeSpan { TimeSpanField = ts }, Formatting.Indented);
  2364. StringAssert.AreEqual(@"{
  2365. ""TimeSpanField"": ""23:59:01""
  2366. }", json);
  2367. ClassWithTimeSpan c = JsonConvert.DeserializeObject<ClassWithTimeSpan>(json);
  2368. Assert.AreEqual(ts, c.TimeSpanField);
  2369. }
  2370. [Test]
  2371. public void JsonIgnoreAttributeOnClassTest()
  2372. {
  2373. string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeOnClassTestClass());
  2374. Assert.AreEqual(@"{""TheField"":0,""Property"":21}", json);
  2375. JsonIgnoreAttributeOnClassTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeOnClassTestClass>(@"{""TheField"":99,""Property"":-1,""IgnoredField"":-1}");
  2376. Assert.AreEqual(0, c.IgnoredField);
  2377. Assert.AreEqual(99, c.Field);
  2378. }
  2379. [Test]
  2380. public void ConstructorCaseSensitivity()
  2381. {
  2382. ConstructorCaseSensitivityClass c = new ConstructorCaseSensitivityClass("param1", "Param1", "Param2");
  2383. string json = JsonConvert.SerializeObject(c);
  2384. ConstructorCaseSensitivityClass deserialized = JsonConvert.DeserializeObject<ConstructorCaseSensitivityClass>(json);
  2385. Assert.AreEqual("param1", deserialized.param1);
  2386. Assert.AreEqual("Param1", deserialized.Param1);
  2387. Assert.AreEqual("Param2", deserialized.Param2);
  2388. }
  2389. [Test]
  2390. public void SerializerShouldUseClassConverter()
  2391. {
  2392. ConverterPrecedenceClass c1 = new ConverterPrecedenceClass("!Test!");
  2393. string json = JsonConvert.SerializeObject(c1);
  2394. Assert.AreEqual(@"[""Class"",""!Test!""]", json);
  2395. ConverterPrecedenceClass c2 = JsonConvert.DeserializeObject<ConverterPrecedenceClass>(json);
  2396. Assert.AreEqual("!Test!", c2.TestValue);
  2397. }
  2398. [Test]
  2399. public void SerializerShouldUseClassConverterOverArgumentConverter()
  2400. {
  2401. ConverterPrecedenceClass c1 = new ConverterPrecedenceClass("!Test!");
  2402. string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
  2403. Assert.AreEqual(@"[""Class"",""!Test!""]", json);
  2404. ConverterPrecedenceClass c2 = JsonConvert.DeserializeObject<ConverterPrecedenceClass>(json, new ArgumentConverterPrecedenceClassConverter());
  2405. Assert.AreEqual("!Test!", c2.TestValue);
  2406. }
  2407. [Test]
  2408. public void SerializerShouldUseMemberConverter_IsoDate()
  2409. {
  2410. DateTime testDate = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  2411. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  2412. string json = JsonConvert.SerializeObject(m1);
  2413. Assert.AreEqual(@"{""DefaultConverter"":""1970-01-01T00:00:00Z"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  2414. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
  2415. Assert.AreEqual(testDate, m2.DefaultConverter);
  2416. Assert.AreEqual(testDate, m2.MemberConverter);
  2417. }
  2418. [Test]
  2419. public void SerializerShouldUseMemberConverter_MsDate()
  2420. {
  2421. DateTime testDate = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  2422. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  2423. string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
  2424. {
  2425. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  2426. });
  2427. Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  2428. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
  2429. Assert.AreEqual(testDate, m2.DefaultConverter);
  2430. Assert.AreEqual(testDate, m2.MemberConverter);
  2431. }
  2432. [Test]
  2433. public void SerializerShouldUseMemberConverter_MsDate_DateParseNone()
  2434. {
  2435. DateTime testDate = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  2436. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  2437. string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
  2438. {
  2439. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
  2440. });
  2441. Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  2442. var m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json, new JsonSerializerSettings
  2443. {
  2444. DateParseHandling = DateParseHandling.None
  2445. });
  2446. Assert.AreEqual(new DateTime(1970, 1, 1), m2.DefaultConverter);
  2447. Assert.AreEqual(new DateTime(1970, 1, 1), m2.MemberConverter);
  2448. }
  2449. [Test]
  2450. public void SerializerShouldUseMemberConverter_IsoDate_DateParseNone()
  2451. {
  2452. DateTime testDate = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  2453. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  2454. string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
  2455. {
  2456. DateFormatHandling = DateFormatHandling.IsoDateFormat,
  2457. });
  2458. Assert.AreEqual(@"{""DefaultConverter"":""1970-01-01T00:00:00Z"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  2459. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
  2460. Assert.AreEqual(testDate, m2.DefaultConverter);
  2461. Assert.AreEqual(testDate, m2.MemberConverter);
  2462. }
  2463. [Test]
  2464. public void SerializerShouldUseMemberConverterOverArgumentConverter()
  2465. {
  2466. DateTime testDate = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  2467. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  2468. string json = JsonConvert.SerializeObject(m1, new JavaScriptDateTimeConverter());
  2469. Assert.AreEqual(@"{""DefaultConverter"":new Date(0),""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  2470. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json, new JavaScriptDateTimeConverter());
  2471. Assert.AreEqual(testDate, m2.DefaultConverter);
  2472. Assert.AreEqual(testDate, m2.MemberConverter);
  2473. }
  2474. [Test]
  2475. public void ConverterAttributeExample()
  2476. {
  2477. DateTime date = Convert.ToDateTime("1970-01-01T00:00:00Z").ToUniversalTime();
  2478. MemberConverterClass c = new MemberConverterClass
  2479. {
  2480. DefaultConverter = date,
  2481. MemberConverter = date
  2482. };
  2483. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  2484. StringAssert.AreEqual(@"{
  2485. ""DefaultConverter"": ""1970-01-01T00:00:00Z"",
  2486. ""MemberConverter"": ""1970-01-01T00:00:00Z""
  2487. }", json);
  2488. }
  2489. [Test]
  2490. public void SerializerShouldUseMemberConverterOverClassAndArgumentConverter()
  2491. {
  2492. ClassAndMemberConverterClass c1 = new ClassAndMemberConverterClass();
  2493. c1.DefaultConverter = new ConverterPrecedenceClass("DefaultConverterValue");
  2494. c1.MemberConverter = new ConverterPrecedenceClass("MemberConverterValue");
  2495. string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
  2496. Assert.AreEqual(@"{""DefaultConverter"":[""Class"",""DefaultConverterValue""],""MemberConverter"":[""Member"",""MemberConverterValue""]}", json);
  2497. ClassAndMemberConverterClass c2 = JsonConvert.DeserializeObject<ClassAndMemberConverterClass>(json, new ArgumentConverterPrecedenceClassConverter());
  2498. Assert.AreEqual("DefaultConverterValue", c2.DefaultConverter.TestValue);
  2499. Assert.AreEqual("MemberConverterValue", c2.MemberConverter.TestValue);
  2500. }
  2501. [Test]
  2502. public void IncompatibleJsonAttributeShouldThrow()
  2503. {
  2504. ExceptionAssert.Throws<JsonSerializationException>(() =>
  2505. {
  2506. IncompatibleJsonAttributeClass c = new IncompatibleJsonAttributeClass();
  2507. JsonConvert.SerializeObject(c);
  2508. }, "Unexpected value when converting date. Expected DateTime or DateTimeOffset, got Newtonsoft.Json.Tests.TestObjects.IncompatibleJsonAttributeClass.");
  2509. }
  2510. [Test]
  2511. public void GenericAbstractProperty()
  2512. {
  2513. string json = JsonConvert.SerializeObject(new GenericImpl());
  2514. Assert.AreEqual(@"{""Id"":0}", json);
  2515. }
  2516. [Test]
  2517. public void DeserializeNullable()
  2518. {
  2519. string json;
  2520. json = JsonConvert.SerializeObject((int?)null);
  2521. Assert.AreEqual("null", json);
  2522. json = JsonConvert.SerializeObject((int?)1);
  2523. Assert.AreEqual("1", json);
  2524. }
  2525. [Test]
  2526. public void SerializeJsonRaw()
  2527. {
  2528. PersonRaw personRaw = new PersonRaw
  2529. {
  2530. FirstName = "FirstNameValue",
  2531. RawContent = new JRaw("[1,2,3,4,5]"),
  2532. LastName = "LastNameValue"
  2533. };
  2534. string json;
  2535. json = JsonConvert.SerializeObject(personRaw);
  2536. Assert.AreEqual(@"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}", json);
  2537. }
  2538. [Test]
  2539. public void DeserializeJsonRaw()
  2540. {
  2541. string json = @"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}";
  2542. PersonRaw personRaw = JsonConvert.DeserializeObject<PersonRaw>(json);
  2543. Assert.AreEqual("FirstNameValue", personRaw.FirstName);
  2544. Assert.AreEqual("[1,2,3,4,5]", personRaw.RawContent.ToString());
  2545. Assert.AreEqual("LastNameValue", personRaw.LastName);
  2546. }
  2547. [Test]
  2548. public void DeserializeNullableMember()
  2549. {
  2550. UserNullable userNullablle = new UserNullable
  2551. {
  2552. Id = new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"),
  2553. FName = "FirstValue",
  2554. LName = "LastValue",
  2555. RoleId = 5,
  2556. NullableRoleId = 6,
  2557. NullRoleId = null,
  2558. Active = true
  2559. };
  2560. string json = JsonConvert.SerializeObject(userNullablle);
  2561. Assert.AreEqual(@"{""Id"":""ad6205e8-0df4-465d-aea6-8ba18e93a7e7"",""FName"":""FirstValue"",""LName"":""LastValue"",""RoleId"":5,""NullableRoleId"":6,""NullRoleId"":null,""Active"":true}", json);
  2562. UserNullable userNullablleDeserialized = JsonConvert.DeserializeObject<UserNullable>(json);
  2563. Assert.AreEqual(new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"), userNullablleDeserialized.Id);
  2564. Assert.AreEqual("FirstValue", userNullablleDeserialized.FName);
  2565. Assert.AreEqual("LastValue", userNullablleDeserialized.LName);
  2566. Assert.AreEqual(5, userNullablleDeserialized.RoleId);
  2567. Assert.AreEqual(6, userNullablleDeserialized.NullableRoleId);
  2568. Assert.AreEqual(null, userNullablleDeserialized.NullRoleId);
  2569. Assert.AreEqual(true, userNullablleDeserialized.Active);
  2570. }
  2571. [Test]
  2572. public void DeserializeInt64ToNullableDouble()
  2573. {
  2574. string json = @"{""Height"":1}";
  2575. DoubleClass c = JsonConvert.DeserializeObject<DoubleClass>(json);
  2576. Assert.AreEqual(1, c.Height);
  2577. }
  2578. [Test]
  2579. public void SerializeTypeProperty()
  2580. {
  2581. string boolRef = typeof(bool).AssemblyQualifiedName;
  2582. TypeClass typeClass = new TypeClass { TypeProperty = typeof(bool) };
  2583. string json = JsonConvert.SerializeObject(typeClass);
  2584. Assert.AreEqual(@"{""TypeProperty"":""" + boolRef + @"""}", json);
  2585. TypeClass typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
  2586. Assert.AreEqual(typeof(bool), typeClass2.TypeProperty);
  2587. string jsonSerializerTestRef = typeof(JsonSerializerTest).AssemblyQualifiedName;
  2588. typeClass = new TypeClass { TypeProperty = typeof(JsonSerializerTest) };
  2589. json = JsonConvert.SerializeObject(typeClass);
  2590. Assert.AreEqual(@"{""TypeProperty"":""" + jsonSerializerTestRef + @"""}", json);
  2591. typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
  2592. Assert.AreEqual(typeof(JsonSerializerTest), typeClass2.TypeProperty);
  2593. }
  2594. [Test]
  2595. public void RequiredMembersClass()
  2596. {
  2597. RequiredMembersClass c = new RequiredMembersClass()
  2598. {
  2599. BirthDate = new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc),
  2600. FirstName = "Bob",
  2601. LastName = "Smith",
  2602. MiddleName = "Cosmo"
  2603. };
  2604. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  2605. StringAssert.AreEqual(@"{
  2606. ""FirstName"": ""Bob"",
  2607. ""MiddleName"": ""Cosmo"",
  2608. ""LastName"": ""Smith"",
  2609. ""BirthDate"": ""2000-12-20T10:55:55Z""
  2610. }", json);
  2611. RequiredMembersClass c2 = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  2612. Assert.AreEqual("Bob", c2.FirstName);
  2613. Assert.AreEqual(new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc), c2.BirthDate);
  2614. }
  2615. [Test]
  2616. public void DeserializeRequiredMembersClassWithNullValues()
  2617. {
  2618. string json = @"{
  2619. ""FirstName"": ""I can't be null bro!"",
  2620. ""MiddleName"": null,
  2621. ""LastName"": null,
  2622. ""BirthDate"": ""\/Date(977309755000)\/""
  2623. }";
  2624. RequiredMembersClass c = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  2625. Assert.AreEqual("I can't be null bro!", c.FirstName);
  2626. Assert.AreEqual(null, c.MiddleName);
  2627. Assert.AreEqual(null, c.LastName);
  2628. }
  2629. [Test]
  2630. public void DeserializeRequiredMembersClassNullRequiredValueProperty()
  2631. {
  2632. try
  2633. {
  2634. string json = @"{
  2635. ""FirstName"": null,
  2636. ""MiddleName"": null,
  2637. ""LastName"": null,
  2638. ""BirthDate"": ""\/Date(977309755000)\/""
  2639. }";
  2640. JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  2641. Assert.Fail();
  2642. }
  2643. catch (JsonSerializationException ex)
  2644. {
  2645. Assert.IsTrue(ex.Message.StartsWith("Required property 'FirstName' expects a value but got null. Path ''"));
  2646. }
  2647. }
  2648. [Test]
  2649. public void SerializeRequiredMembersClassNullRequiredValueProperty()
  2650. {
  2651. ExceptionAssert.Throws<JsonSerializationException>(() =>
  2652. {
  2653. RequiredMembersClass requiredMembersClass = new RequiredMembersClass
  2654. {
  2655. FirstName = null,
  2656. BirthDate = new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc),
  2657. LastName = null,
  2658. MiddleName = null
  2659. };
  2660. string json = JsonConvert.SerializeObject(requiredMembersClass);
  2661. }, "Cannot write a null value for property 'FirstName'. Property requires a value. Path ''.");
  2662. }
  2663. [Test]
  2664. public void RequiredMembersClassMissingRequiredProperty()
  2665. {
  2666. try
  2667. {
  2668. string json = @"{
  2669. ""FirstName"": ""Bob""
  2670. }";
  2671. JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  2672. Assert.Fail();
  2673. }
  2674. catch (JsonSerializationException ex)
  2675. {
  2676. Assert.IsTrue(ex.Message.StartsWith("Required property 'LastName' not found in JSON. Path ''"));
  2677. }
  2678. }
  2679. [Test]
  2680. public void SerializeJaggedArray()
  2681. {
  2682. JaggedArray aa = new JaggedArray();
  2683. aa.Before = "Before!";
  2684. aa.After = "After!";
  2685. aa.Coordinates = new[] { new[] { 1, 1 }, new[] { 1, 2 }, new[] { 2, 1 }, new[] { 2, 2 } };
  2686. string json = JsonConvert.SerializeObject(aa);
  2687. Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}", json);
  2688. }
  2689. [Test]
  2690. public void DeserializeJaggedArray()
  2691. {
  2692. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}";
  2693. JaggedArray aa = JsonConvert.DeserializeObject<JaggedArray>(json);
  2694. Assert.AreEqual("Before!", aa.Before);
  2695. Assert.AreEqual("After!", aa.After);
  2696. Assert.AreEqual(4, aa.Coordinates.Length);
  2697. Assert.AreEqual(2, aa.Coordinates[0].Length);
  2698. Assert.AreEqual(1, aa.Coordinates[0][0]);
  2699. Assert.AreEqual(2, aa.Coordinates[1][1]);
  2700. string after = JsonConvert.SerializeObject(aa);
  2701. Assert.AreEqual(json, after);
  2702. }
  2703. [Test]
  2704. public void DeserializeGoogleGeoCode()
  2705. {
  2706. string json = @"{
  2707. ""name"": ""1600 Amphitheatre Parkway, Mountain View, CA, USA"",
  2708. ""Status"": {
  2709. ""code"": 200,
  2710. ""request"": ""geocode""
  2711. },
  2712. ""Placemark"": [
  2713. {
  2714. ""address"": ""1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"",
  2715. ""AddressDetails"": {
  2716. ""Country"": {
  2717. ""CountryNameCode"": ""US"",
  2718. ""AdministrativeArea"": {
  2719. ""AdministrativeAreaName"": ""CA"",
  2720. ""SubAdministrativeArea"": {
  2721. ""SubAdministrativeAreaName"": ""Santa Clara"",
  2722. ""Locality"": {
  2723. ""LocalityName"": ""Mountain View"",
  2724. ""Thoroughfare"": {
  2725. ""ThoroughfareName"": ""1600 Amphitheatre Pkwy""
  2726. },
  2727. ""PostalCode"": {
  2728. ""PostalCodeNumber"": ""94043""
  2729. }
  2730. }
  2731. }
  2732. }
  2733. },
  2734. ""Accuracy"": 8
  2735. },
  2736. ""Point"": {
  2737. ""coordinates"": [-122.083739, 37.423021, 0]
  2738. }
  2739. }
  2740. ]
  2741. }";
  2742. GoogleMapGeocoderStructure jsonGoogleMapGeocoder = JsonConvert.DeserializeObject<GoogleMapGeocoderStructure>(json);
  2743. }
  2744. [Test]
  2745. public void DeserializeInterfaceProperty()
  2746. {
  2747. InterfacePropertyTestClass testClass = new InterfacePropertyTestClass();
  2748. testClass.co = new Co();
  2749. String strFromTest = JsonConvert.SerializeObject(testClass);
  2750. ExceptionAssert.Throws<JsonSerializationException>(() =>
  2751. {
  2752. InterfacePropertyTestClass testFromDe = (InterfacePropertyTestClass)JsonConvert.DeserializeObject(strFromTest, typeof(InterfacePropertyTestClass));
  2753. }, @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantiated. Path 'co.Name', line 1, position 14.");
  2754. }
  2755. private Person GetPerson()
  2756. {
  2757. Person person = new Person
  2758. {
  2759. Name = "Mike Manager",
  2760. BirthDate = new DateTime(1983, 8, 3, 0, 0, 0, DateTimeKind.Utc),
  2761. Department = "IT",
  2762. LastModified = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc)
  2763. };
  2764. return person;
  2765. }
  2766. [Test]
  2767. public void WriteJsonDates()
  2768. {
  2769. LogEntry entry = new LogEntry
  2770. {
  2771. LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
  2772. Details = "Application started."
  2773. };
  2774. string defaultJson = JsonConvert.SerializeObject(entry);
  2775. // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}
  2776. string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
  2777. // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00.0000000Z"}
  2778. string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
  2779. // {"Details":"Application started.","LogDate":new Date(1234656000000)}
  2780. Assert.AreEqual(@"{""Details"":""Application started."",""LogDate"":""2009-02-15T00:00:00Z""}", defaultJson);
  2781. Assert.AreEqual(@"{""Details"":""Application started."",""LogDate"":""2009-02-15T00:00:00Z""}", isoJson);
  2782. Assert.AreEqual(@"{""Details"":""Application started."",""LogDate"":new Date(1234656000000)}", javascriptJson);
  2783. }
  2784. public void GenericListAndDictionaryInterfaceProperties()
  2785. {
  2786. GenericListAndDictionaryInterfaceProperties o = new GenericListAndDictionaryInterfaceProperties();
  2787. o.IDictionaryProperty = new Dictionary<string, int>
  2788. {
  2789. { "one", 1 },
  2790. { "two", 2 },
  2791. { "three", 3 }
  2792. };
  2793. o.IListProperty = new List<int>
  2794. {
  2795. 1, 2, 3
  2796. };
  2797. o.IEnumerableProperty = new List<int>
  2798. {
  2799. 4, 5, 6
  2800. };
  2801. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  2802. Assert.AreEqual(@"{
  2803. ""IEnumerableProperty"": [
  2804. 4,
  2805. 5,
  2806. 6
  2807. ],
  2808. ""IListProperty"": [
  2809. 1,
  2810. 2,
  2811. 3
  2812. ],
  2813. ""IDictionaryProperty"": {
  2814. ""one"": 1,
  2815. ""two"": 2,
  2816. ""three"": 3
  2817. }
  2818. }", json);
  2819. GenericListAndDictionaryInterfaceProperties deserializedObject = JsonConvert.DeserializeObject<GenericListAndDictionaryInterfaceProperties>(json);
  2820. Assert.IsNotNull(deserializedObject);
  2821. CollectionAssert.AreEqual(o.IListProperty.ToArray(), deserializedObject.IListProperty.ToArray());
  2822. CollectionAssert.AreEqual(o.IEnumerableProperty.ToArray(), deserializedObject.IEnumerableProperty.ToArray());
  2823. CollectionAssert.AreEqual(o.IDictionaryProperty.ToArray(), deserializedObject.IDictionaryProperty.ToArray());
  2824. }
  2825. [Test]
  2826. public void DeserializeBestMatchPropertyCase()
  2827. {
  2828. string json = @"{
  2829. ""firstName"": ""firstName"",
  2830. ""FirstName"": ""FirstName"",
  2831. ""LastName"": ""LastName"",
  2832. ""lastName"": ""lastName"",
  2833. }";
  2834. PropertyCase o = JsonConvert.DeserializeObject<PropertyCase>(json);
  2835. Assert.IsNotNull(o);
  2836. Assert.AreEqual("firstName", o.firstName);
  2837. Assert.AreEqual("FirstName", o.FirstName);
  2838. Assert.AreEqual("LastName", o.LastName);
  2839. Assert.AreEqual("lastName", o.lastName);
  2840. }
  2841. public sealed class ConstructorAndDefaultValueAttributeTestClass
  2842. {
  2843. public ConstructorAndDefaultValueAttributeTestClass(string testProperty1)
  2844. {
  2845. TestProperty1 = testProperty1;
  2846. }
  2847. public string TestProperty1 { get; set; }
  2848. [DefaultValue(21)]
  2849. public int TestProperty2 { get; set; }
  2850. }
  2851. [Test]
  2852. public void PopulateDefaultValueWhenUsingConstructor()
  2853. {
  2854. string json = "{ 'testProperty1': 'value' }";
  2855. ConstructorAndDefaultValueAttributeTestClass c = JsonConvert.DeserializeObject<ConstructorAndDefaultValueAttributeTestClass>(json, new JsonSerializerSettings
  2856. {
  2857. DefaultValueHandling = DefaultValueHandling.Populate
  2858. });
  2859. Assert.AreEqual("value", c.TestProperty1);
  2860. Assert.AreEqual(21, c.TestProperty2);
  2861. c = JsonConvert.DeserializeObject<ConstructorAndDefaultValueAttributeTestClass>(json, new JsonSerializerSettings
  2862. {
  2863. DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate
  2864. });
  2865. Assert.AreEqual("value", c.TestProperty1);
  2866. Assert.AreEqual(21, c.TestProperty2);
  2867. }
  2868. public sealed class ConstructorAndRequiredTestClass
  2869. {
  2870. public ConstructorAndRequiredTestClass(string testProperty1)
  2871. {
  2872. TestProperty1 = testProperty1;
  2873. }
  2874. public string TestProperty1 { get; set; }
  2875. [JsonProperty(Required = Required.AllowNull)]
  2876. public int TestProperty2 { get; set; }
  2877. }
  2878. [Test]
  2879. public void RequiredWhenUsingConstructor()
  2880. {
  2881. try
  2882. {
  2883. string json = "{ 'testProperty1': 'value' }";
  2884. JsonConvert.DeserializeObject<ConstructorAndRequiredTestClass>(json);
  2885. Assert.Fail();
  2886. }
  2887. catch (JsonSerializationException ex)
  2888. {
  2889. Assert.IsTrue(ex.Message.StartsWith("Required property 'TestProperty2' not found in JSON. Path ''"));
  2890. }
  2891. }
  2892. [Test]
  2893. public void DeserializePropertiesOnToNonDefaultConstructor()
  2894. {
  2895. SubKlass i = new SubKlass("my subprop");
  2896. i.SuperProp = "overrided superprop";
  2897. string json = JsonConvert.SerializeObject(i);
  2898. Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", json);
  2899. SubKlass ii = JsonConvert.DeserializeObject<SubKlass>(json);
  2900. string newJson = JsonConvert.SerializeObject(ii);
  2901. Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", newJson);
  2902. }
  2903. [Test]
  2904. public void DeserializePropertiesOnToNonDefaultConstructorWithReferenceTracking()
  2905. {
  2906. SubKlass i = new SubKlass("my subprop");
  2907. i.SuperProp = "overrided superprop";
  2908. string json = JsonConvert.SerializeObject(i, new JsonSerializerSettings
  2909. {
  2910. PreserveReferencesHandling = PreserveReferencesHandling.Objects
  2911. });
  2912. Assert.AreEqual(@"{""$id"":""1"",""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", json);
  2913. SubKlass ii = JsonConvert.DeserializeObject<SubKlass>(json, new JsonSerializerSettings
  2914. {
  2915. PreserveReferencesHandling = PreserveReferencesHandling.Objects
  2916. });
  2917. string newJson = JsonConvert.SerializeObject(ii, new JsonSerializerSettings
  2918. {
  2919. PreserveReferencesHandling = PreserveReferencesHandling.Objects
  2920. });
  2921. Assert.AreEqual(@"{""$id"":""1"",""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", newJson);
  2922. }
  2923. [Test]
  2924. public void SerializeJsonPropertyWithHandlingValues()
  2925. {
  2926. JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
  2927. o.DefaultValueHandlingIgnoreProperty = "Default!";
  2928. o.DefaultValueHandlingIncludeProperty = "Default!";
  2929. o.DefaultValueHandlingPopulateProperty = "Default!";
  2930. o.DefaultValueHandlingIgnoreAndPopulateProperty = "Default!";
  2931. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  2932. StringAssert.AreEqual(@"{
  2933. ""DefaultValueHandlingIncludeProperty"": ""Default!"",
  2934. ""DefaultValueHandlingPopulateProperty"": ""Default!"",
  2935. ""NullValueHandlingIncludeProperty"": null,
  2936. ""ReferenceLoopHandlingErrorProperty"": null,
  2937. ""ReferenceLoopHandlingIgnoreProperty"": null,
  2938. ""ReferenceLoopHandlingSerializeProperty"": null
  2939. }", json);
  2940. json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
  2941. StringAssert.AreEqual(@"{
  2942. ""DefaultValueHandlingIncludeProperty"": ""Default!"",
  2943. ""DefaultValueHandlingPopulateProperty"": ""Default!"",
  2944. ""NullValueHandlingIncludeProperty"": null
  2945. }", json);
  2946. }
  2947. [Test]
  2948. public void DeserializeJsonPropertyWithHandlingValues()
  2949. {
  2950. string json = "{}";
  2951. JsonPropertyWithHandlingValues o = JsonConvert.DeserializeObject<JsonPropertyWithHandlingValues>(json);
  2952. Assert.AreEqual("Default!", o.DefaultValueHandlingIgnoreAndPopulateProperty);
  2953. Assert.AreEqual("Default!", o.DefaultValueHandlingPopulateProperty);
  2954. Assert.AreEqual(null, o.DefaultValueHandlingIgnoreProperty);
  2955. Assert.AreEqual(null, o.DefaultValueHandlingIncludeProperty);
  2956. }
  2957. [Test]
  2958. public void JsonPropertyWithHandlingValues_ReferenceLoopError()
  2959. {
  2960. string classRef = typeof(JsonPropertyWithHandlingValues).FullName;
  2961. ExceptionAssert.Throws<JsonSerializationException>(() =>
  2962. {
  2963. JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
  2964. o.ReferenceLoopHandlingErrorProperty = o;
  2965. JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
  2966. }, "Self referencing loop detected for property 'ReferenceLoopHandlingErrorProperty' with type '" + classRef + "'. Path ''.");
  2967. }
  2968. [Test]
  2969. public void PartialClassDeserialize()
  2970. {
  2971. string json = @"{
  2972. ""request"": ""ux.settings.update"",
  2973. ""sid"": ""14c561bd-32a8-457e-b4e5-4bba0832897f"",
  2974. ""uid"": ""30c39065-0f31-de11-9442-001e3786a8ec"",
  2975. ""fidOrder"": [
  2976. ""id"",
  2977. ""andytest_name"",
  2978. ""andytest_age"",
  2979. ""andytest_address"",
  2980. ""andytest_phone"",
  2981. ""date"",
  2982. ""title"",
  2983. ""titleId""
  2984. ],
  2985. ""entityName"": ""Andy Test"",
  2986. ""setting"": ""entity.field.order""
  2987. }";
  2988. RequestOnly r = JsonConvert.DeserializeObject<RequestOnly>(json);
  2989. Assert.AreEqual("ux.settings.update", r.Request);
  2990. NonRequest n = JsonConvert.DeserializeObject<NonRequest>(json);
  2991. Assert.AreEqual(new Guid("14c561bd-32a8-457e-b4e5-4bba0832897f"), n.Sid);
  2992. Assert.AreEqual(new Guid("30c39065-0f31-de11-9442-001e3786a8ec"), n.Uid);
  2993. Assert.AreEqual(8, n.FidOrder.Count);
  2994. Assert.AreEqual("id", n.FidOrder[0]);
  2995. Assert.AreEqual("titleId", n.FidOrder[n.FidOrder.Count - 1]);
  2996. }
  2997. #if !(NET20 || DNXCORE50)
  2998. [MetadataType(typeof(OptInClassMetadata))]
  2999. public class OptInClass
  3000. {
  3001. [DataContract]
  3002. public class OptInClassMetadata
  3003. {
  3004. [DataMember]
  3005. public string Name { get; set; }
  3006. [DataMember]
  3007. public int Age { get; set; }
  3008. public string NotIncluded { get; set; }
  3009. }
  3010. public string Name { get; set; }
  3011. public int Age { get; set; }
  3012. public string NotIncluded { get; set; }
  3013. }
  3014. [Test]
  3015. public void OptInClassMetadataSerialization()
  3016. {
  3017. OptInClass optInClass = new OptInClass();
  3018. optInClass.Age = 26;
  3019. optInClass.Name = "James NK";
  3020. optInClass.NotIncluded = "Poor me :(";
  3021. string json = JsonConvert.SerializeObject(optInClass, Formatting.Indented);
  3022. StringAssert.AreEqual(@"{
  3023. ""Name"": ""James NK"",
  3024. ""Age"": 26
  3025. }", json);
  3026. OptInClass newOptInClass = JsonConvert.DeserializeObject<OptInClass>(@"{
  3027. ""Name"": ""James NK"",
  3028. ""NotIncluded"": ""Ignore me!"",
  3029. ""Age"": 26
  3030. }");
  3031. Assert.AreEqual(26, newOptInClass.Age);
  3032. Assert.AreEqual("James NK", newOptInClass.Name);
  3033. Assert.AreEqual(null, newOptInClass.NotIncluded);
  3034. }
  3035. #endif
  3036. #if !NET20
  3037. [DataContract]
  3038. public class DataContractPrivateMembers
  3039. {
  3040. public DataContractPrivateMembers()
  3041. {
  3042. }
  3043. public DataContractPrivateMembers(string name, int age, int rank, string title)
  3044. {
  3045. _name = name;
  3046. Age = age;
  3047. Rank = rank;
  3048. Title = title;
  3049. }
  3050. [DataMember]
  3051. private string _name;
  3052. [DataMember(Name = "_age")]
  3053. private int Age { get; set; }
  3054. [JsonProperty]
  3055. private int Rank { get; set; }
  3056. [JsonProperty(PropertyName = "JsonTitle")]
  3057. [DataMember(Name = "DataTitle")]
  3058. private string Title { get; set; }
  3059. public string NotIncluded { get; set; }
  3060. public override string ToString()
  3061. {
  3062. return "_name: " + _name + ", _age: " + Age + ", Rank: " + Rank + ", JsonTitle: " + Title;
  3063. }
  3064. }
  3065. [Test]
  3066. public void SerializeDataContractPrivateMembers()
  3067. {
  3068. DataContractPrivateMembers c = new DataContractPrivateMembers("Jeff", 26, 10, "Dr");
  3069. c.NotIncluded = "Hi";
  3070. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3071. StringAssert.AreEqual(@"{
  3072. ""_name"": ""Jeff"",
  3073. ""_age"": 26,
  3074. ""Rank"": 10,
  3075. ""JsonTitle"": ""Dr""
  3076. }", json);
  3077. DataContractPrivateMembers cc = JsonConvert.DeserializeObject<DataContractPrivateMembers>(json);
  3078. Assert.AreEqual("_name: Jeff, _age: 26, Rank: 10, JsonTitle: Dr", cc.ToString());
  3079. }
  3080. #endif
  3081. [Test]
  3082. public void DeserializeDictionaryInterface()
  3083. {
  3084. string json = @"{
  3085. ""Name"": ""Name!"",
  3086. ""Dictionary"": {
  3087. ""Item"": 11
  3088. }
  3089. }";
  3090. DictionaryInterfaceClass c = JsonConvert.DeserializeObject<DictionaryInterfaceClass>(
  3091. json,
  3092. new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace });
  3093. Assert.AreEqual("Name!", c.Name);
  3094. Assert.AreEqual(1, c.Dictionary.Count);
  3095. Assert.AreEqual(11, c.Dictionary["Item"]);
  3096. }
  3097. [Test]
  3098. public void DeserializeDictionaryInterfaceWithExistingValues()
  3099. {
  3100. string json = @"{
  3101. ""Random"": {
  3102. ""blah"": 1
  3103. },
  3104. ""Name"": ""Name!"",
  3105. ""Dictionary"": {
  3106. ""Item"": 11,
  3107. ""Item1"": 12
  3108. },
  3109. ""Collection"": [
  3110. 999
  3111. ],
  3112. ""Employee"": {
  3113. ""Manager"": {
  3114. ""Name"": ""ManagerName!""
  3115. }
  3116. }
  3117. }";
  3118. DictionaryInterfaceClass c = JsonConvert.DeserializeObject<DictionaryInterfaceClass>(json,
  3119. new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Reuse });
  3120. Assert.AreEqual("Name!", c.Name);
  3121. Assert.AreEqual(3, c.Dictionary.Count);
  3122. Assert.AreEqual(11, c.Dictionary["Item"]);
  3123. Assert.AreEqual(1, c.Dictionary["existing"]);
  3124. Assert.AreEqual(4, c.Collection.Count);
  3125. Assert.AreEqual(1, c.Collection.ElementAt(0));
  3126. Assert.AreEqual(999, c.Collection.ElementAt(3));
  3127. Assert.AreEqual("EmployeeName!", c.Employee.Name);
  3128. Assert.AreEqual("ManagerName!", c.Employee.Manager.Name);
  3129. Assert.IsNotNull(c.Random);
  3130. }
  3131. [Test]
  3132. public void TypedObjectDeserializationWithComments()
  3133. {
  3134. string json = @"/*comment1*/ { /*comment2*/
  3135. ""Name"": /*comment3*/ ""Apple"" /*comment4*/, /*comment5*/
  3136. ""ExpiryDate"": ""\/Date(1230422400000)\/"",
  3137. ""Price"": 3.99,
  3138. ""Sizes"": /*comment6*/ [ /*comment7*/
  3139. ""Small"", /*comment8*/
  3140. ""Medium"" /*comment9*/,
  3141. /*comment10*/ ""Large""
  3142. /*comment11*/ ] /*comment12*/
  3143. } /*comment13*/";
  3144. Product deserializedProduct = (Product)JsonConvert.DeserializeObject(json, typeof(Product));
  3145. Assert.AreEqual("Apple", deserializedProduct.Name);
  3146. Assert.AreEqual(new DateTime(2008, 12, 28, 0, 0, 0, DateTimeKind.Utc), deserializedProduct.ExpiryDate);
  3147. Assert.AreEqual(3.99m, deserializedProduct.Price);
  3148. Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
  3149. Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
  3150. Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
  3151. }
  3152. [Test]
  3153. public void NestedInsideOuterObject()
  3154. {
  3155. string json = @"{
  3156. ""short"": {
  3157. ""original"": ""http://www.contrast.ie/blog/online&#45;marketing&#45;2009/"",
  3158. ""short"": ""m2sqc6"",
  3159. ""shortened"": ""http://short.ie/m2sqc6"",
  3160. ""error"": {
  3161. ""code"": 0,
  3162. ""msg"": ""No action taken""
  3163. }
  3164. }
  3165. }";
  3166. JObject o = JObject.Parse(json);
  3167. Shortie s = JsonConvert.DeserializeObject<Shortie>(o["short"].ToString());
  3168. Assert.IsNotNull(s);
  3169. Assert.AreEqual(s.Original, "http://www.contrast.ie/blog/online&#45;marketing&#45;2009/");
  3170. Assert.AreEqual(s.Short, "m2sqc6");
  3171. Assert.AreEqual(s.Shortened, "http://short.ie/m2sqc6");
  3172. }
  3173. [Test]
  3174. public void UriSerialization()
  3175. {
  3176. Uri uri = new Uri("http://codeplex.com");
  3177. string json = JsonConvert.SerializeObject(uri);
  3178. Assert.AreEqual("http://codeplex.com/", uri.ToString());
  3179. Uri newUri = JsonConvert.DeserializeObject<Uri>(json);
  3180. Assert.AreEqual(uri, newUri);
  3181. }
  3182. [Test]
  3183. public void AnonymousPlusLinqToSql()
  3184. {
  3185. var value = new
  3186. {
  3187. bar = new JObject(new JProperty("baz", 13))
  3188. };
  3189. string json = JsonConvert.SerializeObject(value);
  3190. Assert.AreEqual(@"{""bar"":{""baz"":13}}", json);
  3191. }
  3192. [Test]
  3193. public void SerializeEnumerableAsObject()
  3194. {
  3195. Content content = new Content
  3196. {
  3197. Text = "Blah, blah, blah",
  3198. Children = new List<Content>
  3199. {
  3200. new Content { Text = "First" },
  3201. new Content { Text = "Second" }
  3202. }
  3203. };
  3204. string json = JsonConvert.SerializeObject(content, Formatting.Indented);
  3205. StringAssert.AreEqual(@"{
  3206. ""Children"": [
  3207. {
  3208. ""Children"": null,
  3209. ""Text"": ""First""
  3210. },
  3211. {
  3212. ""Children"": null,
  3213. ""Text"": ""Second""
  3214. }
  3215. ],
  3216. ""Text"": ""Blah, blah, blah""
  3217. }", json);
  3218. }
  3219. [Test]
  3220. public void DeserializeEnumerableAsObject()
  3221. {
  3222. string json = @"{
  3223. ""Children"": [
  3224. {
  3225. ""Children"": null,
  3226. ""Text"": ""First""
  3227. },
  3228. {
  3229. ""Children"": null,
  3230. ""Text"": ""Second""
  3231. }
  3232. ],
  3233. ""Text"": ""Blah, blah, blah""
  3234. }";
  3235. Content content = JsonConvert.DeserializeObject<Content>(json);
  3236. Assert.AreEqual("Blah, blah, blah", content.Text);
  3237. Assert.AreEqual(2, content.Children.Count);
  3238. Assert.AreEqual("First", content.Children[0].Text);
  3239. Assert.AreEqual("Second", content.Children[1].Text);
  3240. }
  3241. [Test]
  3242. public void RoleTransferTest()
  3243. {
  3244. string json = @"{""Operation"":""1"",""RoleName"":""Admin"",""Direction"":""0""}";
  3245. RoleTransfer r = JsonConvert.DeserializeObject<RoleTransfer>(json);
  3246. Assert.AreEqual(RoleTransferOperation.Second, r.Operation);
  3247. Assert.AreEqual("Admin", r.RoleName);
  3248. Assert.AreEqual(RoleTransferDirection.First, r.Direction);
  3249. }
  3250. [Test]
  3251. public void DeserializeGenericDictionary()
  3252. {
  3253. string json = @"{""key1"":""value1"",""key2"":""value2""}";
  3254. Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  3255. Assert.AreEqual(2, values.Count);
  3256. Assert.AreEqual("value1", values["key1"]);
  3257. Assert.AreEqual("value2", values["key2"]);
  3258. }
  3259. #if !NET20
  3260. [Test]
  3261. public void DeserializeEmptyStringToNullableDateTime()
  3262. {
  3263. string json = @"{""DateTimeField"":""""}";
  3264. NullableDateTimeTestClass c = JsonConvert.DeserializeObject<NullableDateTimeTestClass>(json);
  3265. Assert.AreEqual(null, c.DateTimeField);
  3266. }
  3267. #endif
  3268. [Test]
  3269. public void FailWhenClassWithNoDefaultConstructorHasMultipleConstructorsWithArguments()
  3270. {
  3271. string json = @"{""sublocation"":""AlertEmailSender.Program.Main"",""userId"":0,""type"":0,""summary"":""Loading settings variables"",""details"":null,""stackTrace"":"" at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)\r\n at System.Environment.get_StackTrace()\r\n at mr.Logging.Event..ctor(String summary) in C:\\Projects\\MRUtils\\Logging\\Event.vb:line 71\r\n at AlertEmailSender.Program.Main(String[] args) in C:\\Projects\\AlertEmailSender\\AlertEmailSender\\Program.cs:line 25"",""tag"":null,""time"":""\/Date(1249591032026-0400)\/""}";
  3272. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Event>(json); }, @"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Events.Event. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'sublocation', line 1, position 15.");
  3273. }
  3274. [Test]
  3275. public void DeserializeObjectSetOnlyProperty()
  3276. {
  3277. string json = @"{'SetOnlyProperty':[1,2,3,4,5]}";
  3278. SetOnlyPropertyClass2 setOnly = JsonConvert.DeserializeObject<SetOnlyPropertyClass2>(json);
  3279. JArray a = (JArray)setOnly.GetValue();
  3280. Assert.AreEqual(5, a.Count);
  3281. Assert.AreEqual(1, (int)a[0]);
  3282. Assert.AreEqual(5, (int)a[a.Count - 1]);
  3283. }
  3284. [Test]
  3285. public void DeserializeOptInClasses()
  3286. {
  3287. string json = @"{id: ""12"", name: ""test"", items: [{id: ""112"", name: ""testing""}]}";
  3288. ListTestClass l = JsonConvert.DeserializeObject<ListTestClass>(json);
  3289. }
  3290. [Test]
  3291. public void DeserializeNullableListWithNulls()
  3292. {
  3293. List<decimal?> l = JsonConvert.DeserializeObject<List<decimal?>>("[ 3.3, null, 1.1 ] ");
  3294. Assert.AreEqual(3, l.Count);
  3295. Assert.AreEqual(3.3m, l[0]);
  3296. Assert.AreEqual(null, l[1]);
  3297. Assert.AreEqual(1.1m, l[2]);
  3298. }
  3299. [Test]
  3300. public void CannotDeserializeArrayIntoObject()
  3301. {
  3302. string json = @"[]";
  3303. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Person>(json); }, @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Newtonsoft.Json.Tests.TestObjects.Organization.Person' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
  3304. To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
  3305. Path '', line 1, position 1.");
  3306. }
  3307. [Test]
  3308. public void CannotDeserializeArrayIntoDictionary()
  3309. {
  3310. string json = @"[]";
  3311. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Dictionary<string, string>>(json); }, @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
  3312. To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
  3313. Path '', line 1, position 1.");
  3314. }
  3315. #if !(PORTABLE || DNXCORE50)
  3316. [Test]
  3317. public void CannotDeserializeArrayIntoSerializable()
  3318. {
  3319. string json = @"[]";
  3320. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Exception>(json); }, @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Exception' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
  3321. To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
  3322. Path '', line 1, position 1.");
  3323. }
  3324. #endif
  3325. [Test]
  3326. public void CannotDeserializeArrayIntoDouble()
  3327. {
  3328. string json = @"[]";
  3329. ExceptionAssert.Throws<JsonReaderException>(
  3330. () => { JsonConvert.DeserializeObject<double>(json); },
  3331. @"Unexpected character encountered while parsing value: [. Path '', line 1, position 1.");
  3332. }
  3333. #if !(NET35 || NET20 || PORTABLE40)
  3334. [Test]
  3335. public void CannotDeserializeArrayIntoDynamic()
  3336. {
  3337. string json = @"[]";
  3338. ExceptionAssert.Throws<JsonSerializationException>(
  3339. () => { JsonConvert.DeserializeObject<DynamicDictionary>(json); },
  3340. @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Newtonsoft.Json.Tests.Linq.DynamicDictionary' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
  3341. To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
  3342. Path '', line 1, position 1.");
  3343. }
  3344. #endif
  3345. [Test]
  3346. public void CannotDeserializeArrayIntoLinqToJson()
  3347. {
  3348. string json = @"[]";
  3349. ExceptionAssert.Throws<InvalidCastException>(
  3350. () => { JsonConvert.DeserializeObject<JObject>(json); },
  3351. new[]
  3352. {
  3353. "Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.",
  3354. "Cannot cast from source type to destination type." // mono
  3355. });
  3356. }
  3357. [Test]
  3358. public void CannotDeserializeConstructorIntoObject()
  3359. {
  3360. string json = @"new Constructor(123)";
  3361. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Person>(json); }, @"Error converting value ""Constructor"" to type 'Newtonsoft.Json.Tests.TestObjects.Organization.Person'. Path '', line 1, position 16.");
  3362. }
  3363. [Test]
  3364. public void CannotDeserializeConstructorIntoObjectNested()
  3365. {
  3366. string json = @"[new Constructor(123)]";
  3367. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<List<Person>>(json); }, @"Error converting value ""Constructor"" to type 'Newtonsoft.Json.Tests.TestObjects.Organization.Person'. Path '[0]', line 1, position 17.");
  3368. }
  3369. [Test]
  3370. public void CannotDeserializeObjectIntoArray()
  3371. {
  3372. string json = @"{}";
  3373. try
  3374. {
  3375. JsonConvert.DeserializeObject<List<Person>>(json);
  3376. Assert.Fail();
  3377. }
  3378. catch (JsonSerializationException ex)
  3379. {
  3380. Assert.IsTrue(ex.Message.StartsWith(@"Cannot deserialize the current JSON object (e.g. {""name"":""value""}) into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Organization.Person]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly." + Environment.NewLine +
  3381. @"To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object." + Environment.NewLine +
  3382. @"Path ''"));
  3383. }
  3384. }
  3385. [Test]
  3386. public void CannotPopulateArrayIntoObject()
  3387. {
  3388. string json = @"[]";
  3389. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.PopulateObject(json, new Person()); }, @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Organization.Person'. Path '', line 1, position 1.");
  3390. }
  3391. [Test]
  3392. public void CannotPopulateObjectIntoArray()
  3393. {
  3394. string json = @"{}";
  3395. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.PopulateObject(json, new List<Person>()); }, @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Organization.Person]'. Path '', line 1, position 2.");
  3396. }
  3397. [Test]
  3398. public void DeserializeEmptyString()
  3399. {
  3400. string json = @"{""Name"":""""}";
  3401. Person p = JsonConvert.DeserializeObject<Person>(json);
  3402. Assert.AreEqual("", p.Name);
  3403. }
  3404. [Test]
  3405. public void SerializePropertyGetError()
  3406. {
  3407. ExceptionAssert.Throws<JsonSerializationException>(() =>
  3408. {
  3409. JsonConvert.SerializeObject(new MemoryStream(), new JsonSerializerSettings
  3410. {
  3411. ContractResolver = new DefaultContractResolver
  3412. {
  3413. #if !(PORTABLE || DNXCORE50 || PORTABLE40)
  3414. IgnoreSerializableAttribute = true
  3415. #endif
  3416. }
  3417. });
  3418. }, @"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.");
  3419. }
  3420. [Test]
  3421. public void DeserializePropertySetError()
  3422. {
  3423. ExceptionAssert.Throws<JsonSerializationException>(() =>
  3424. {
  3425. JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:0}", new JsonSerializerSettings
  3426. {
  3427. ContractResolver = new DefaultContractResolver
  3428. {
  3429. #if !(PORTABLE || DNXCORE50 || PORTABLE40)
  3430. IgnoreSerializableAttribute = true
  3431. #endif
  3432. }
  3433. });
  3434. }, @"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'.");
  3435. }
  3436. [Test]
  3437. public void DeserializeEnsureTypeEmptyStringToIntError()
  3438. {
  3439. ExceptionAssert.Throws<JsonSerializationException>(() =>
  3440. {
  3441. JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}", new JsonSerializerSettings
  3442. {
  3443. ContractResolver = new DefaultContractResolver
  3444. {
  3445. #if !(PORTABLE || DNXCORE50 || PORTABLE40)
  3446. IgnoreSerializableAttribute = true
  3447. #endif
  3448. }
  3449. });
  3450. }, @"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 15.");
  3451. }
  3452. [Test]
  3453. public void DeserializeEnsureTypeNullToIntError()
  3454. {
  3455. ExceptionAssert.Throws<JsonSerializationException>(() =>
  3456. {
  3457. JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}", new JsonSerializerSettings
  3458. {
  3459. ContractResolver = new DefaultContractResolver
  3460. {
  3461. #if !(PORTABLE || DNXCORE50 || PORTABLE40)
  3462. IgnoreSerializableAttribute = true
  3463. #endif
  3464. }
  3465. });
  3466. }, @"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 17.");
  3467. }
  3468. [Test]
  3469. public void SerializeGenericListOfStrings()
  3470. {
  3471. List<String> strings = new List<String>();
  3472. strings.Add("str_1");
  3473. strings.Add("str_2");
  3474. strings.Add("str_3");
  3475. string json = JsonConvert.SerializeObject(strings);
  3476. Assert.AreEqual(@"[""str_1"",""str_2"",""str_3""]", json);
  3477. }
  3478. [Test]
  3479. public void ConstructorReadonlyFieldsTest()
  3480. {
  3481. ConstructorReadonlyFields c1 = new ConstructorReadonlyFields("String!", int.MaxValue);
  3482. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  3483. StringAssert.AreEqual(@"{
  3484. ""A"": ""String!"",
  3485. ""B"": 2147483647
  3486. }", json);
  3487. ConstructorReadonlyFields c2 = JsonConvert.DeserializeObject<ConstructorReadonlyFields>(json);
  3488. Assert.AreEqual("String!", c2.A);
  3489. Assert.AreEqual(int.MaxValue, c2.B);
  3490. }
  3491. [Test]
  3492. public void SerializeStruct()
  3493. {
  3494. StructTest structTest = new StructTest
  3495. {
  3496. StringProperty = "StringProperty!",
  3497. StringField = "StringField",
  3498. IntProperty = 5,
  3499. IntField = 10
  3500. };
  3501. string json = JsonConvert.SerializeObject(structTest, Formatting.Indented);
  3502. StringAssert.AreEqual(@"{
  3503. ""StringField"": ""StringField"",
  3504. ""IntField"": 10,
  3505. ""StringProperty"": ""StringProperty!"",
  3506. ""IntProperty"": 5
  3507. }", json);
  3508. StructTest deserialized = JsonConvert.DeserializeObject<StructTest>(json);
  3509. Assert.AreEqual(structTest.StringProperty, deserialized.StringProperty);
  3510. Assert.AreEqual(structTest.StringField, deserialized.StringField);
  3511. Assert.AreEqual(structTest.IntProperty, deserialized.IntProperty);
  3512. Assert.AreEqual(structTest.IntField, deserialized.IntField);
  3513. }
  3514. [Test]
  3515. public void SerializeListWithJsonConverter()
  3516. {
  3517. Foo f = new Foo();
  3518. f.Bars.Add(new Bar { Id = 0 });
  3519. f.Bars.Add(new Bar { Id = 1 });
  3520. f.Bars.Add(new Bar { Id = 2 });
  3521. string json = JsonConvert.SerializeObject(f, Formatting.Indented);
  3522. StringAssert.AreEqual(@"{
  3523. ""Bars"": [
  3524. 0,
  3525. 1,
  3526. 2
  3527. ]
  3528. }", json);
  3529. Foo newFoo = JsonConvert.DeserializeObject<Foo>(json);
  3530. Assert.AreEqual(3, newFoo.Bars.Count);
  3531. Assert.AreEqual(0, newFoo.Bars[0].Id);
  3532. Assert.AreEqual(1, newFoo.Bars[1].Id);
  3533. Assert.AreEqual(2, newFoo.Bars[2].Id);
  3534. }
  3535. [Test]
  3536. public void SerializeGuidKeyedDictionary()
  3537. {
  3538. Dictionary<Guid, int> dictionary = new Dictionary<Guid, int>();
  3539. dictionary.Add(new Guid("F60EAEE0-AE47-488E-B330-59527B742D77"), 1);
  3540. dictionary.Add(new Guid("C2594C02-EBA1-426A-AA87-8DD8871350B0"), 2);
  3541. string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
  3542. StringAssert.AreEqual(@"{
  3543. ""f60eaee0-ae47-488e-b330-59527b742d77"": 1,
  3544. ""c2594c02-eba1-426a-aa87-8dd8871350b0"": 2
  3545. }", json);
  3546. }
  3547. [Test]
  3548. public void SerializePersonKeyedDictionary()
  3549. {
  3550. Dictionary<Person, int> dictionary = new Dictionary<Person, int>();
  3551. dictionary.Add(new Person { Name = "p1" }, 1);
  3552. dictionary.Add(new Person { Name = "p2" }, 2);
  3553. string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
  3554. StringAssert.AreEqual(@"{
  3555. ""Newtonsoft.Json.Tests.TestObjects.Organization.Person"": 1,
  3556. ""Newtonsoft.Json.Tests.TestObjects.Organization.Person"": 2
  3557. }", json);
  3558. }
  3559. [Test]
  3560. public void DeserializePersonKeyedDictionary()
  3561. {
  3562. try
  3563. {
  3564. string json =
  3565. @"{
  3566. ""Newtonsoft.Json.Tests.TestObjects.Organization.Person"": 1,
  3567. ""Newtonsoft.Json.Tests.TestObjects.Organization.Person"": 2
  3568. }";
  3569. JsonConvert.DeserializeObject<Dictionary<Person, int>>(json);
  3570. Assert.Fail();
  3571. }
  3572. catch (JsonSerializationException ex)
  3573. {
  3574. Assert.IsTrue(ex.Message.StartsWith("Could not convert string 'Newtonsoft.Json.Tests.TestObjects.Organization.Person' to dictionary key type 'Newtonsoft.Json.Tests.TestObjects.Organization.Person'. Create a TypeConverter to convert from the string to the key type object. Path '['Newtonsoft.Json.Tests.TestObjects.Organization.Person']'"));
  3575. }
  3576. }
  3577. [Test]
  3578. public void SerializeFragment()
  3579. {
  3580. string googleSearchText = @"{
  3581. ""responseData"": {
  3582. ""results"": [
  3583. {
  3584. ""GsearchResultClass"": ""GwebSearch"",
  3585. ""unescapedUrl"": ""http://en.wikipedia.org/wiki/Paris_Hilton"",
  3586. ""url"": ""http://en.wikipedia.org/wiki/Paris_Hilton"",
  3587. ""visibleUrl"": ""en.wikipedia.org"",
  3588. ""cacheUrl"": ""http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org"",
  3589. ""title"": ""<b>Paris Hilton</b> - Wikipedia, the free encyclopedia"",
  3590. ""titleNoFormatting"": ""Paris Hilton - Wikipedia, the free encyclopedia"",
  3591. ""content"": ""[1] In 2006, she released her debut album...""
  3592. },
  3593. {
  3594. ""GsearchResultClass"": ""GwebSearch"",
  3595. ""unescapedUrl"": ""http://www.imdb.com/name/nm0385296/"",
  3596. ""url"": ""http://www.imdb.com/name/nm0385296/"",
  3597. ""visibleUrl"": ""www.imdb.com"",
  3598. ""cacheUrl"": ""http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com"",
  3599. ""title"": ""<b>Paris Hilton</b>"",
  3600. ""titleNoFormatting"": ""Paris Hilton"",
  3601. ""content"": ""Self: Zoolander. Socialite <b>Paris Hilton</b>...""
  3602. }
  3603. ],
  3604. ""cursor"": {
  3605. ""pages"": [
  3606. {
  3607. ""start"": ""0"",
  3608. ""label"": 1
  3609. },
  3610. {
  3611. ""start"": ""4"",
  3612. ""label"": 2
  3613. },
  3614. {
  3615. ""start"": ""8"",
  3616. ""label"": 3
  3617. },
  3618. {
  3619. ""start"": ""12"",
  3620. ""label"": 4
  3621. }
  3622. ],
  3623. ""estimatedResultCount"": ""59600000"",
  3624. ""currentPageIndex"": 0,
  3625. ""moreResultsUrl"": ""http://www.google.com/search?oe=utf8&ie=utf8...""
  3626. }
  3627. },
  3628. ""responseDetails"": null,
  3629. ""responseStatus"": 200
  3630. }";
  3631. JObject googleSearch = JObject.Parse(googleSearchText);
  3632. // get JSON result objects into a list
  3633. IList<JToken> results = googleSearch["responseData"]["results"].Children().ToList();
  3634. // serialize JSON results into .NET objects
  3635. IList<SearchResult> searchResults = new List<SearchResult>();
  3636. foreach (JToken result in results)
  3637. {
  3638. SearchResult searchResult = JsonConvert.DeserializeObject<SearchResult>(result.ToString());
  3639. searchResults.Add(searchResult);
  3640. }
  3641. // Title = <b>Paris Hilton</b> - Wikipedia, the free encyclopedia
  3642. // Content = [1] In 2006, she released her debut album...
  3643. // Url = http://en.wikipedia.org/wiki/Paris_Hilton
  3644. // Title = <b>Paris Hilton</b>
  3645. // Content = Self: Zoolander. Socialite <b>Paris Hilton</b>...
  3646. // Url = http://www.imdb.com/name/nm0385296/
  3647. Assert.AreEqual(2, searchResults.Count);
  3648. Assert.AreEqual("<b>Paris Hilton</b> - Wikipedia, the free encyclopedia", searchResults[0].Title);
  3649. Assert.AreEqual("<b>Paris Hilton</b>", searchResults[1].Title);
  3650. }
  3651. [Test]
  3652. public void DeserializeBaseReferenceWithDerivedValue()
  3653. {
  3654. PersonPropertyClass personPropertyClass = new PersonPropertyClass();
  3655. WagePerson wagePerson = (WagePerson)personPropertyClass.Person;
  3656. wagePerson.BirthDate = new DateTime(2000, 11, 29, 23, 59, 59, DateTimeKind.Utc);
  3657. wagePerson.Department = "McDees";
  3658. wagePerson.HourlyWage = 12.50m;
  3659. wagePerson.LastModified = new DateTime(2000, 11, 29, 23, 59, 59, DateTimeKind.Utc);
  3660. wagePerson.Name = "Jim Bob";
  3661. string json = JsonConvert.SerializeObject(personPropertyClass, Formatting.Indented);
  3662. StringAssert.AreEqual(
  3663. @"{
  3664. ""Person"": {
  3665. ""HourlyWage"": 12.50,
  3666. ""Name"": ""Jim Bob"",
  3667. ""BirthDate"": ""2000-11-29T23:59:59Z"",
  3668. ""LastModified"": ""2000-11-29T23:59:59Z""
  3669. }
  3670. }",
  3671. json);
  3672. PersonPropertyClass newPersonPropertyClass = JsonConvert.DeserializeObject<PersonPropertyClass>(json);
  3673. Assert.AreEqual(wagePerson.HourlyWage, ((WagePerson)newPersonPropertyClass.Person).HourlyWage);
  3674. }
  3675. public class ExistingValueClass
  3676. {
  3677. public Dictionary<string, string> Dictionary { get; set; }
  3678. public List<string> List { get; set; }
  3679. public ExistingValueClass()
  3680. {
  3681. Dictionary = new Dictionary<string, string>
  3682. {
  3683. { "existing", "yup" }
  3684. };
  3685. List = new List<string>
  3686. {
  3687. "existing"
  3688. };
  3689. }
  3690. }
  3691. [Test]
  3692. public void DeserializePopulateDictionaryAndList()
  3693. {
  3694. ExistingValueClass d = JsonConvert.DeserializeObject<ExistingValueClass>(@"{'Dictionary':{appended:'appended',existing:'new'}}");
  3695. Assert.IsNotNull(d);
  3696. Assert.IsNotNull(d.Dictionary);
  3697. Assert.AreEqual(typeof(Dictionary<string, string>), d.Dictionary.GetType());
  3698. Assert.AreEqual(typeof(List<string>), d.List.GetType());
  3699. Assert.AreEqual(2, d.Dictionary.Count);
  3700. Assert.AreEqual("new", d.Dictionary["existing"]);
  3701. Assert.AreEqual("appended", d.Dictionary["appended"]);
  3702. Assert.AreEqual(1, d.List.Count);
  3703. Assert.AreEqual("existing", d.List[0]);
  3704. }
  3705. public interface IKeyValueId
  3706. {
  3707. int Id { get; set; }
  3708. string Key { get; set; }
  3709. string Value { get; set; }
  3710. }
  3711. public class KeyValueId : IKeyValueId
  3712. {
  3713. public int Id { get; set; }
  3714. public string Key { get; set; }
  3715. public string Value { get; set; }
  3716. }
  3717. public class ThisGenericTest<T> where T : IKeyValueId
  3718. {
  3719. private Dictionary<string, T> _dict1 = new Dictionary<string, T>();
  3720. public string MyProperty { get; set; }
  3721. public void Add(T item)
  3722. {
  3723. _dict1.Add(item.Key, item);
  3724. }
  3725. public T this[string key]
  3726. {
  3727. get { return _dict1[key]; }
  3728. set { _dict1[key] = value; }
  3729. }
  3730. public T this[int id]
  3731. {
  3732. get { return _dict1.Values.FirstOrDefault(x => x.Id == id); }
  3733. set
  3734. {
  3735. var item = this[id];
  3736. if (item == null)
  3737. {
  3738. Add(value);
  3739. }
  3740. else
  3741. {
  3742. _dict1[item.Key] = value;
  3743. }
  3744. }
  3745. }
  3746. public string ToJson()
  3747. {
  3748. return JsonConvert.SerializeObject(this, Formatting.Indented);
  3749. }
  3750. public T[] TheItems
  3751. {
  3752. get { return _dict1.Values.ToArray<T>(); }
  3753. set
  3754. {
  3755. foreach (var item in value)
  3756. {
  3757. Add(item);
  3758. }
  3759. }
  3760. }
  3761. }
  3762. [Test]
  3763. public void IgnoreIndexedProperties()
  3764. {
  3765. ThisGenericTest<KeyValueId> g = new ThisGenericTest<KeyValueId>();
  3766. g.Add(new KeyValueId { Id = 1, Key = "key1", Value = "value1" });
  3767. g.Add(new KeyValueId { Id = 2, Key = "key2", Value = "value2" });
  3768. g.MyProperty = "some value";
  3769. string json = g.ToJson();
  3770. StringAssert.AreEqual(@"{
  3771. ""MyProperty"": ""some value"",
  3772. ""TheItems"": [
  3773. {
  3774. ""Id"": 1,
  3775. ""Key"": ""key1"",
  3776. ""Value"": ""value1""
  3777. },
  3778. {
  3779. ""Id"": 2,
  3780. ""Key"": ""key2"",
  3781. ""Value"": ""value2""
  3782. }
  3783. ]
  3784. }", json);
  3785. ThisGenericTest<KeyValueId> gen = JsonConvert.DeserializeObject<ThisGenericTest<KeyValueId>>(json);
  3786. Assert.AreEqual("some value", gen.MyProperty);
  3787. }
  3788. public class JRawValueTestObject
  3789. {
  3790. public JRaw Value { get; set; }
  3791. }
  3792. [Test]
  3793. public void JRawValue()
  3794. {
  3795. JRawValueTestObject deserialized = JsonConvert.DeserializeObject<JRawValueTestObject>("{value:3}");
  3796. Assert.AreEqual("3", deserialized.Value.ToString());
  3797. deserialized = JsonConvert.DeserializeObject<JRawValueTestObject>("{value:'3'}");
  3798. Assert.AreEqual(@"""3""", deserialized.Value.ToString());
  3799. }
  3800. [Test]
  3801. public void DeserializeDictionaryWithNoDefaultConstructor()
  3802. {
  3803. string json = "{key1:'value1',key2:'value2',key3:'value3'}";
  3804. var dic = JsonConvert.DeserializeObject<DictionaryWithNoDefaultConstructor>(json);
  3805. Assert.AreEqual(3, dic.Count);
  3806. Assert.AreEqual("value1", dic["key1"]);
  3807. Assert.AreEqual("value2", dic["key2"]);
  3808. Assert.AreEqual("value3", dic["key3"]);
  3809. }
  3810. [Test]
  3811. public void DeserializeDictionaryWithNoDefaultConstructor_PreserveReferences()
  3812. {
  3813. string json = "{'$id':'1',key1:'value1',key2:'value2',key3:'value3'}";
  3814. ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<DictionaryWithNoDefaultConstructor>(json, new JsonSerializerSettings
  3815. {
  3816. PreserveReferencesHandling = PreserveReferencesHandling.All,
  3817. MetadataPropertyHandling = MetadataPropertyHandling.Default
  3818. }), "Cannot preserve reference to readonly dictionary, or dictionary created from a non-default constructor: Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Path 'key1', line 1, position 16.");
  3819. }
  3820. public class DictionaryWithNoDefaultConstructor : Dictionary<string, string>
  3821. {
  3822. public DictionaryWithNoDefaultConstructor(IEnumerable<KeyValuePair<string, string>> initial)
  3823. {
  3824. foreach (KeyValuePair<string, string> pair in initial)
  3825. {
  3826. Add(pair.Key, pair.Value);
  3827. }
  3828. }
  3829. }
  3830. [JsonObject(MemberSerialization.OptIn)]
  3831. public class A
  3832. {
  3833. [JsonProperty("A1")]
  3834. private string _A1;
  3835. public string A1
  3836. {
  3837. get { return _A1; }
  3838. set { _A1 = value; }
  3839. }
  3840. [JsonProperty("A2")]
  3841. private string A2 { get; set; }
  3842. }
  3843. [JsonObject(MemberSerialization.OptIn)]
  3844. public class B : A
  3845. {
  3846. public string B1 { get; set; }
  3847. [JsonProperty("B2")]
  3848. private string _B2;
  3849. public string B2
  3850. {
  3851. get { return _B2; }
  3852. set { _B2 = value; }
  3853. }
  3854. [JsonProperty("B3")]
  3855. private string B3 { get; set; }
  3856. }
  3857. [Test]
  3858. public void SerializeNonPublicBaseJsonProperties()
  3859. {
  3860. B value = new B();
  3861. string json = JsonConvert.SerializeObject(value, Formatting.Indented);
  3862. StringAssert.AreEqual(@"{
  3863. ""B2"": null,
  3864. ""A1"": null,
  3865. ""B3"": null,
  3866. ""A2"": null
  3867. }", json);
  3868. }
  3869. #if !NET20
  3870. public class DateTimeOffsetWrapper
  3871. {
  3872. public DateTimeOffset DateTimeOffsetValue { get; set; }
  3873. public DateTime DateTimeValue { get; set; }
  3874. }
  3875. [Test]
  3876. public void DeserializeDateTimeOffsetAndDateTime()
  3877. {
  3878. string jsonIsoText =
  3879. @"{""DateTimeOffsetValue"":""2012-02-25T19:55:50.6095676+00:00"", ""DateTimeValue"":""2012-02-25T19:55:50.6095676+00:00""}";
  3880. DateTimeOffsetWrapper cISO = JsonConvert.DeserializeObject<DateTimeOffsetWrapper>(jsonIsoText, new JsonSerializerSettings
  3881. {
  3882. DateParseHandling = DateParseHandling.DateTimeOffset,
  3883. Converters =
  3884. {
  3885. new IsoDateTimeConverter()
  3886. }
  3887. });
  3888. DateTimeOffsetWrapper c = JsonConvert.DeserializeObject<DateTimeOffsetWrapper>(jsonIsoText, new JsonSerializerSettings
  3889. {
  3890. DateParseHandling = DateParseHandling.DateTimeOffset
  3891. });
  3892. Assert.AreEqual(c.DateTimeOffsetValue, cISO.DateTimeOffsetValue);
  3893. }
  3894. #endif
  3895. [Test]
  3896. public void CircularConstructorDeserialize()
  3897. {
  3898. CircularConstructor1 c1 = new CircularConstructor1(null)
  3899. {
  3900. StringProperty = "Value!"
  3901. };
  3902. CircularConstructor2 c2 = new CircularConstructor2(null)
  3903. {
  3904. IntProperty = 1
  3905. };
  3906. c1.C2 = c2;
  3907. c2.C1 = c1;
  3908. string json = JsonConvert.SerializeObject(c1, new JsonSerializerSettings
  3909. {
  3910. ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
  3911. Formatting = Formatting.Indented
  3912. });
  3913. StringAssert.AreEqual(@"{
  3914. ""C2"": {
  3915. ""IntProperty"": 1
  3916. },
  3917. ""StringProperty"": ""Value!""
  3918. }", json);
  3919. CircularConstructor1 newC1 = JsonConvert.DeserializeObject<CircularConstructor1>(@"{
  3920. ""C2"": {
  3921. ""IntProperty"": 1,
  3922. ""C1"": {}
  3923. },
  3924. ""StringProperty"": ""Value!""
  3925. }");
  3926. Assert.AreEqual("Value!", newC1.StringProperty);
  3927. Assert.AreEqual(1, newC1.C2.IntProperty);
  3928. Assert.AreEqual(null, newC1.C2.C1.StringProperty);
  3929. Assert.AreEqual(null, newC1.C2.C1.C2);
  3930. }
  3931. public class CircularConstructor1
  3932. {
  3933. public CircularConstructor2 C2 { get; internal set; }
  3934. public string StringProperty { get; set; }
  3935. public CircularConstructor1(CircularConstructor2 c2)
  3936. {
  3937. C2 = c2;
  3938. }
  3939. }
  3940. public class CircularConstructor2
  3941. {
  3942. public CircularConstructor1 C1 { get; internal set; }
  3943. public int IntProperty { get; set; }
  3944. public CircularConstructor2(CircularConstructor1 c1)
  3945. {
  3946. C1 = c1;
  3947. }
  3948. }
  3949. public class TestClass
  3950. {
  3951. public string Key { get; set; }
  3952. public object Value { get; set; }
  3953. }
  3954. [Test]
  3955. public void DeserializeToObjectProperty()
  3956. {
  3957. var json = "{ Key: 'abc', Value: 123 }";
  3958. var item = JsonConvert.DeserializeObject<TestClass>(json);
  3959. Assert.AreEqual(123L, item.Value);
  3960. }
  3961. public abstract class Animal
  3962. {
  3963. public abstract string Name { get; }
  3964. }
  3965. public class Human : Animal
  3966. {
  3967. public override string Name
  3968. {
  3969. get { return typeof(Human).Name; }
  3970. }
  3971. public string Ethnicity { get; set; }
  3972. }
  3973. #if !(NET20 || NET35)
  3974. public class DataContractJsonSerializerTestClass
  3975. {
  3976. public TimeSpan TimeSpanProperty { get; set; }
  3977. public Guid GuidProperty { get; set; }
  3978. public Animal AnimalProperty { get; set; }
  3979. }
  3980. [Test]
  3981. public void DataContractJsonSerializerTest()
  3982. {
  3983. DataContractJsonSerializerTestClass c = new DataContractJsonSerializerTestClass()
  3984. {
  3985. TimeSpanProperty = new TimeSpan(200, 20, 59, 30, 900),
  3986. GuidProperty = new Guid("66143115-BE2A-4a59-AF0A-348E1EA15B1E"),
  3987. AnimalProperty = new Human() { Ethnicity = "European" }
  3988. };
  3989. MemoryStream ms = new MemoryStream();
  3990. DataContractJsonSerializer serializer = new DataContractJsonSerializer(
  3991. typeof(DataContractJsonSerializerTestClass),
  3992. new Type[] { typeof(Human) });
  3993. serializer.WriteObject(ms, c);
  3994. byte[] jsonBytes = ms.ToArray();
  3995. string json = Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length);
  3996. //Console.WriteLine(JObject.Parse(json).ToString());
  3997. //Console.WriteLine();
  3998. //Console.WriteLine(JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings
  3999. // {
  4000. // // TypeNameHandling = TypeNameHandling.Objects
  4001. // }));
  4002. }
  4003. #endif
  4004. public class ModelStateDictionary<T> : IDictionary<string, T>
  4005. {
  4006. private readonly Dictionary<string, T> _innerDictionary = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
  4007. public ModelStateDictionary()
  4008. {
  4009. }
  4010. public ModelStateDictionary(ModelStateDictionary<T> dictionary)
  4011. {
  4012. if (dictionary == null)
  4013. {
  4014. throw new ArgumentNullException(nameof(dictionary));
  4015. }
  4016. foreach (var entry in dictionary)
  4017. {
  4018. _innerDictionary.Add(entry.Key, entry.Value);
  4019. }
  4020. }
  4021. public int Count
  4022. {
  4023. get { return _innerDictionary.Count; }
  4024. }
  4025. public bool IsReadOnly
  4026. {
  4027. get { return ((IDictionary<string, T>)_innerDictionary).IsReadOnly; }
  4028. }
  4029. public ICollection<string> Keys
  4030. {
  4031. get { return _innerDictionary.Keys; }
  4032. }
  4033. public T this[string key]
  4034. {
  4035. get
  4036. {
  4037. T value;
  4038. _innerDictionary.TryGetValue(key, out value);
  4039. return value;
  4040. }
  4041. set { _innerDictionary[key] = value; }
  4042. }
  4043. public ICollection<T> Values
  4044. {
  4045. get { return _innerDictionary.Values; }
  4046. }
  4047. public void Add(KeyValuePair<string, T> item)
  4048. {
  4049. ((IDictionary<string, T>)_innerDictionary).Add(item);
  4050. }
  4051. public void Add(string key, T value)
  4052. {
  4053. _innerDictionary.Add(key, value);
  4054. }
  4055. public void Clear()
  4056. {
  4057. _innerDictionary.Clear();
  4058. }
  4059. public bool Contains(KeyValuePair<string, T> item)
  4060. {
  4061. return ((IDictionary<string, T>)_innerDictionary).Contains(item);
  4062. }
  4063. public bool ContainsKey(string key)
  4064. {
  4065. return _innerDictionary.ContainsKey(key);
  4066. }
  4067. public void CopyTo(KeyValuePair<string, T>[] array, int arrayIndex)
  4068. {
  4069. ((IDictionary<string, T>)_innerDictionary).CopyTo(array, arrayIndex);
  4070. }
  4071. public IEnumerator<KeyValuePair<string, T>> GetEnumerator()
  4072. {
  4073. return _innerDictionary.GetEnumerator();
  4074. }
  4075. public void Merge(ModelStateDictionary<T> dictionary)
  4076. {
  4077. if (dictionary == null)
  4078. {
  4079. return;
  4080. }
  4081. foreach (var entry in dictionary)
  4082. {
  4083. this[entry.Key] = entry.Value;
  4084. }
  4085. }
  4086. public bool Remove(KeyValuePair<string, T> item)
  4087. {
  4088. return ((IDictionary<string, T>)_innerDictionary).Remove(item);
  4089. }
  4090. public bool Remove(string key)
  4091. {
  4092. return _innerDictionary.Remove(key);
  4093. }
  4094. public bool TryGetValue(string key, out T value)
  4095. {
  4096. return _innerDictionary.TryGetValue(key, out value);
  4097. }
  4098. IEnumerator IEnumerable.GetEnumerator()
  4099. {
  4100. return ((IEnumerable)_innerDictionary).GetEnumerator();
  4101. }
  4102. }
  4103. [Test]
  4104. public void SerializeNonIDictionary()
  4105. {
  4106. ModelStateDictionary<string> modelStateDictionary = new ModelStateDictionary<string>();
  4107. modelStateDictionary.Add("key", "value");
  4108. string json = JsonConvert.SerializeObject(modelStateDictionary);
  4109. Assert.AreEqual(@"{""key"":""value""}", json);
  4110. ModelStateDictionary<string> newModelStateDictionary = JsonConvert.DeserializeObject<ModelStateDictionary<string>>(json);
  4111. Assert.AreEqual(1, newModelStateDictionary.Count);
  4112. Assert.AreEqual("value", newModelStateDictionary["key"]);
  4113. }
  4114. #if !(PORTABLE || DNXCORE50 || PORTABLE40)
  4115. public class ISerializableTestObject : ISerializable
  4116. {
  4117. internal string _stringValue;
  4118. internal int _intValue;
  4119. internal DateTimeOffset _dateTimeOffsetValue;
  4120. internal Person _personValue;
  4121. internal Person _nullPersonValue;
  4122. internal int? _nullableInt;
  4123. internal bool _booleanValue;
  4124. internal byte _byteValue;
  4125. internal char _charValue;
  4126. internal DateTime _dateTimeValue;
  4127. internal decimal _decimalValue;
  4128. internal short _shortValue;
  4129. internal long _longValue;
  4130. internal sbyte _sbyteValue;
  4131. internal float _floatValue;
  4132. internal ushort _ushortValue;
  4133. internal uint _uintValue;
  4134. internal ulong _ulongValue;
  4135. public ISerializableTestObject(string stringValue, int intValue, DateTimeOffset dateTimeOffset, Person personValue)
  4136. {
  4137. _stringValue = stringValue;
  4138. _intValue = intValue;
  4139. _dateTimeOffsetValue = dateTimeOffset;
  4140. _personValue = personValue;
  4141. _dateTimeValue = new DateTime(0, DateTimeKind.Utc);
  4142. }
  4143. protected ISerializableTestObject(SerializationInfo info, StreamingContext context)
  4144. {
  4145. _stringValue = info.GetString("stringValue");
  4146. _intValue = info.GetInt32("intValue");
  4147. _dateTimeOffsetValue = (DateTimeOffset)info.GetValue("dateTimeOffsetValue", typeof(DateTimeOffset));
  4148. _personValue = (Person)info.GetValue("personValue", typeof(Person));
  4149. _nullPersonValue = (Person)info.GetValue("nullPersonValue", typeof(Person));
  4150. _nullableInt = (int?)info.GetValue("nullableInt", typeof(int?));
  4151. _booleanValue = info.GetBoolean("booleanValue");
  4152. _byteValue = info.GetByte("byteValue");
  4153. _charValue = info.GetChar("charValue");
  4154. _dateTimeValue = info.GetDateTime("dateTimeValue");
  4155. _decimalValue = info.GetDecimal("decimalValue");
  4156. _shortValue = info.GetInt16("shortValue");
  4157. _longValue = info.GetInt64("longValue");
  4158. _sbyteValue = info.GetSByte("sbyteValue");
  4159. _floatValue = info.GetSingle("floatValue");
  4160. _ushortValue = info.GetUInt16("ushortValue");
  4161. _uintValue = info.GetUInt32("uintValue");
  4162. _ulongValue = info.GetUInt64("ulongValue");
  4163. }
  4164. public void GetObjectData(SerializationInfo info, StreamingContext context)
  4165. {
  4166. info.AddValue("stringValue", _stringValue);
  4167. info.AddValue("intValue", _intValue);
  4168. info.AddValue("dateTimeOffsetValue", _dateTimeOffsetValue);
  4169. info.AddValue("personValue", _personValue);
  4170. info.AddValue("nullPersonValue", _nullPersonValue);
  4171. info.AddValue("nullableInt", null);
  4172. info.AddValue("booleanValue", _booleanValue);
  4173. info.AddValue("byteValue", _byteValue);
  4174. info.AddValue("charValue", _charValue);
  4175. info.AddValue("dateTimeValue", _dateTimeValue);
  4176. info.AddValue("decimalValue", _decimalValue);
  4177. info.AddValue("shortValue", _shortValue);
  4178. info.AddValue("longValue", _longValue);
  4179. info.AddValue("sbyteValue", _sbyteValue);
  4180. info.AddValue("floatValue", _floatValue);
  4181. info.AddValue("ushortValue", _ushortValue);
  4182. info.AddValue("uintValue", _uintValue);
  4183. info.AddValue("ulongValue", _ulongValue);
  4184. }
  4185. }
  4186. #if DEBUG
  4187. [Test]
  4188. public void SerializeISerializableInPartialTrustWithIgnoreInterface()
  4189. {
  4190. try
  4191. {
  4192. JsonTypeReflector.SetFullyTrusted(false);
  4193. ISerializableTestObject value = new ISerializableTestObject("string!", 0, default(DateTimeOffset), null);
  4194. string json = JsonConvert.SerializeObject(value, new JsonSerializerSettings
  4195. {
  4196. ContractResolver = new DefaultContractResolver
  4197. {
  4198. IgnoreSerializableInterface = true
  4199. }
  4200. });
  4201. Assert.AreEqual("{}", json);
  4202. value = JsonConvert.DeserializeObject<ISerializableTestObject>("{booleanValue:true}", new JsonSerializerSettings
  4203. {
  4204. ContractResolver = new DefaultContractResolver
  4205. {
  4206. IgnoreSerializableInterface = true
  4207. }
  4208. });
  4209. Assert.IsNotNull(value);
  4210. Assert.AreEqual(false, value._booleanValue);
  4211. }
  4212. finally
  4213. {
  4214. JsonTypeReflector.SetFullyTrusted(true);
  4215. }
  4216. }
  4217. [Test]
  4218. public void SerializeISerializableInPartialTrust()
  4219. {
  4220. try
  4221. {
  4222. ExceptionAssert.Throws<JsonSerializationException>(() =>
  4223. {
  4224. JsonTypeReflector.SetFullyTrusted(false);
  4225. JsonConvert.DeserializeObject<ISerializableTestObject>("{booleanValue:true}");
  4226. }, @"Type 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ISerializableTestObject' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine +
  4227. @"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine +
  4228. @"Path 'booleanValue', line 1, position 14.");
  4229. }
  4230. finally
  4231. {
  4232. JsonTypeReflector.SetFullyTrusted(true);
  4233. }
  4234. }
  4235. [Test]
  4236. public void DeserializeISerializableInPartialTrust()
  4237. {
  4238. try
  4239. {
  4240. ExceptionAssert.Throws<JsonSerializationException>(() =>
  4241. {
  4242. JsonTypeReflector.SetFullyTrusted(false);
  4243. ISerializableTestObject value = new ISerializableTestObject("string!", 0, default(DateTimeOffset), null);
  4244. JsonConvert.SerializeObject(value);
  4245. }, @"Type 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ISerializableTestObject' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine +
  4246. @"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine +
  4247. @"Path ''.");
  4248. }
  4249. finally
  4250. {
  4251. JsonTypeReflector.SetFullyTrusted(true);
  4252. }
  4253. }
  4254. #endif
  4255. [Test]
  4256. public void SerializeISerializableTestObject_IsoDate()
  4257. {
  4258. Person person = new Person();
  4259. person.BirthDate = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
  4260. person.LastModified = person.BirthDate;
  4261. person.Department = "Department!";
  4262. person.Name = "Name!";
  4263. DateTimeOffset dateTimeOffset = new DateTimeOffset(2000, 12, 20, 22, 59, 59, TimeSpan.FromHours(2));
  4264. string dateTimeOffsetText;
  4265. #if !NET20
  4266. dateTimeOffsetText = @"2000-12-20T22:59:59+02:00";
  4267. #else
  4268. dateTimeOffsetText = @"12/20/2000 22:59:59 +02:00";
  4269. #endif
  4270. ISerializableTestObject o = new ISerializableTestObject("String!", int.MinValue, dateTimeOffset, person);
  4271. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  4272. StringAssert.AreEqual(@"{
  4273. ""stringValue"": ""String!"",
  4274. ""intValue"": -2147483648,
  4275. ""dateTimeOffsetValue"": """ + dateTimeOffsetText + @""",
  4276. ""personValue"": {
  4277. ""Name"": ""Name!"",
  4278. ""BirthDate"": ""2000-01-01T01:01:01Z"",
  4279. ""LastModified"": ""2000-01-01T01:01:01Z""
  4280. },
  4281. ""nullPersonValue"": null,
  4282. ""nullableInt"": null,
  4283. ""booleanValue"": false,
  4284. ""byteValue"": 0,
  4285. ""charValue"": ""\u0000"",
  4286. ""dateTimeValue"": ""0001-01-01T00:00:00Z"",
  4287. ""decimalValue"": 0.0,
  4288. ""shortValue"": 0,
  4289. ""longValue"": 0,
  4290. ""sbyteValue"": 0,
  4291. ""floatValue"": 0.0,
  4292. ""ushortValue"": 0,
  4293. ""uintValue"": 0,
  4294. ""ulongValue"": 0
  4295. }", json);
  4296. ISerializableTestObject o2 = JsonConvert.DeserializeObject<ISerializableTestObject>(json);
  4297. Assert.AreEqual("String!", o2._stringValue);
  4298. Assert.AreEqual(int.MinValue, o2._intValue);
  4299. Assert.AreEqual(dateTimeOffset, o2._dateTimeOffsetValue);
  4300. Assert.AreEqual("Name!", o2._personValue.Name);
  4301. Assert.AreEqual(null, o2._nullPersonValue);
  4302. Assert.AreEqual(null, o2._nullableInt);
  4303. }
  4304. [Test]
  4305. public void SerializeISerializableTestObject_MsAjax()
  4306. {
  4307. Person person = new Person();
  4308. person.BirthDate = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
  4309. person.LastModified = person.BirthDate;
  4310. person.Department = "Department!";
  4311. person.Name = "Name!";
  4312. DateTimeOffset dateTimeOffset = new DateTimeOffset(2000, 12, 20, 22, 59, 59, TimeSpan.FromHours(2));
  4313. string dateTimeOffsetText;
  4314. #if !NET20
  4315. dateTimeOffsetText = @"\/Date(977345999000+0200)\/";
  4316. #else
  4317. dateTimeOffsetText = @"12/20/2000 22:59:59 +02:00";
  4318. #endif
  4319. ISerializableTestObject o = new ISerializableTestObject("String!", int.MinValue, dateTimeOffset, person);
  4320. string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
  4321. {
  4322. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  4323. });
  4324. StringAssert.AreEqual(@"{
  4325. ""stringValue"": ""String!"",
  4326. ""intValue"": -2147483648,
  4327. ""dateTimeOffsetValue"": """ + dateTimeOffsetText + @""",
  4328. ""personValue"": {
  4329. ""Name"": ""Name!"",
  4330. ""BirthDate"": ""\/Date(946688461000)\/"",
  4331. ""LastModified"": ""\/Date(946688461000)\/""
  4332. },
  4333. ""nullPersonValue"": null,
  4334. ""nullableInt"": null,
  4335. ""booleanValue"": false,
  4336. ""byteValue"": 0,
  4337. ""charValue"": ""\u0000"",
  4338. ""dateTimeValue"": ""\/Date(-62135596800000)\/"",
  4339. ""decimalValue"": 0.0,
  4340. ""shortValue"": 0,
  4341. ""longValue"": 0,
  4342. ""sbyteValue"": 0,
  4343. ""floatValue"": 0.0,
  4344. ""ushortValue"": 0,
  4345. ""uintValue"": 0,
  4346. ""ulongValue"": 0
  4347. }", json);
  4348. ISerializableTestObject o2 = JsonConvert.DeserializeObject<ISerializableTestObject>(json);
  4349. Assert.AreEqual("String!", o2._stringValue);
  4350. Assert.AreEqual(int.MinValue, o2._intValue);
  4351. Assert.AreEqual(dateTimeOffset, o2._dateTimeOffsetValue);
  4352. Assert.AreEqual("Name!", o2._personValue.Name);
  4353. Assert.AreEqual(null, o2._nullPersonValue);
  4354. Assert.AreEqual(null, o2._nullableInt);
  4355. }
  4356. #endif
  4357. public class KVPair<TKey, TValue>
  4358. {
  4359. public TKey Key { get; set; }
  4360. public TValue Value { get; set; }
  4361. public KVPair(TKey k, TValue v)
  4362. {
  4363. Key = k;
  4364. Value = v;
  4365. }
  4366. }
  4367. [Test]
  4368. public void DeserializeUsingNonDefaultConstructorWithLeftOverValues()
  4369. {
  4370. List<KVPair<string, string>> kvPairs =
  4371. JsonConvert.DeserializeObject<List<KVPair<string, string>>>(
  4372. "[{\"Key\":\"Two\",\"Value\":\"2\"},{\"Key\":\"One\",\"Value\":\"1\"}]");
  4373. Assert.AreEqual(2, kvPairs.Count);
  4374. Assert.AreEqual("Two", kvPairs[0].Key);
  4375. Assert.AreEqual("2", kvPairs[0].Value);
  4376. Assert.AreEqual("One", kvPairs[1].Key);
  4377. Assert.AreEqual("1", kvPairs[1].Value);
  4378. }
  4379. [Test]
  4380. public void SerializeClassWithInheritedProtectedMember()
  4381. {
  4382. AA myA = new AA(2);
  4383. string json = JsonConvert.SerializeObject(myA, Formatting.Indented);
  4384. StringAssert.AreEqual(@"{
  4385. ""AA_field1"": 2,
  4386. ""AA_property1"": 2,
  4387. ""AA_property2"": 2,
  4388. ""AA_property3"": 2,
  4389. ""AA_property4"": 2
  4390. }", json);
  4391. BB myB = new BB(3, 4);
  4392. json = JsonConvert.SerializeObject(myB, Formatting.Indented);
  4393. StringAssert.AreEqual(@"{
  4394. ""BB_field1"": 4,
  4395. ""BB_field2"": 4,
  4396. ""AA_field1"": 3,
  4397. ""BB_property1"": 4,
  4398. ""BB_property2"": 4,
  4399. ""BB_property3"": 4,
  4400. ""BB_property4"": 4,
  4401. ""BB_property5"": 4,
  4402. ""BB_property7"": 4,
  4403. ""AA_property1"": 3,
  4404. ""AA_property2"": 3,
  4405. ""AA_property3"": 3,
  4406. ""AA_property4"": 3
  4407. }", json);
  4408. }
  4409. #if !(PORTABLE)
  4410. [Test]
  4411. public void DeserializeClassWithInheritedProtectedMember()
  4412. {
  4413. AA myA = JsonConvert.DeserializeObject<AA>(
  4414. @"{
  4415. ""AA_field1"": 2,
  4416. ""AA_field2"": 2,
  4417. ""AA_property1"": 2,
  4418. ""AA_property2"": 2,
  4419. ""AA_property3"": 2,
  4420. ""AA_property4"": 2,
  4421. ""AA_property5"": 2,
  4422. ""AA_property6"": 2
  4423. }");
  4424. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field1", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  4425. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field2", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  4426. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property1", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  4427. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property2", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  4428. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property3", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  4429. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property4", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  4430. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property5", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  4431. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property6", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  4432. BB myB = JsonConvert.DeserializeObject<BB>(
  4433. @"{
  4434. ""BB_field1"": 4,
  4435. ""BB_field2"": 4,
  4436. ""AA_field1"": 3,
  4437. ""AA_field2"": 3,
  4438. ""AA_property1"": 2,
  4439. ""AA_property2"": 2,
  4440. ""AA_property3"": 2,
  4441. ""AA_property4"": 2,
  4442. ""AA_property5"": 2,
  4443. ""AA_property6"": 2,
  4444. ""BB_property1"": 3,
  4445. ""BB_property2"": 3,
  4446. ""BB_property3"": 3,
  4447. ""BB_property4"": 3,
  4448. ""BB_property5"": 3,
  4449. ""BB_property6"": 3,
  4450. ""BB_property7"": 3,
  4451. ""BB_property8"": 3
  4452. }");
  4453. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field1", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  4454. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field2", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  4455. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property1", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  4456. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property2", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  4457. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property3", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  4458. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property4", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  4459. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property5", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  4460. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property6", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  4461. Assert.AreEqual(4, myB.BB_field1);
  4462. Assert.AreEqual(4, myB.BB_field2);
  4463. Assert.AreEqual(3, myB.BB_property1);
  4464. Assert.AreEqual(3, myB.BB_property2);
  4465. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property3", BindingFlags.Instance | BindingFlags.Public), myB));
  4466. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property4", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  4467. Assert.AreEqual(0, myB.BB_property5);
  4468. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property6", BindingFlags.Instance | BindingFlags.Public), myB));
  4469. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property7", BindingFlags.Instance | BindingFlags.Public), myB));
  4470. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property8", BindingFlags.Instance | BindingFlags.Public), myB));
  4471. }
  4472. #endif
  4473. public class AA
  4474. {
  4475. [JsonProperty]
  4476. protected int AA_field1;
  4477. protected int AA_field2;
  4478. [JsonProperty]
  4479. protected int AA_property1 { get; set; }
  4480. [JsonProperty]
  4481. protected int AA_property2 { get; private set; }
  4482. [JsonProperty]
  4483. protected int AA_property3 { private get; set; }
  4484. [JsonProperty]
  4485. private int AA_property4 { get; set; }
  4486. protected int AA_property5 { get; private set; }
  4487. protected int AA_property6 { private get; set; }
  4488. public AA()
  4489. {
  4490. }
  4491. public AA(int f)
  4492. {
  4493. AA_field1 = f;
  4494. AA_field2 = f;
  4495. AA_property1 = f;
  4496. AA_property2 = f;
  4497. AA_property3 = f;
  4498. AA_property4 = f;
  4499. AA_property5 = f;
  4500. AA_property6 = f;
  4501. }
  4502. }
  4503. public class BB : AA
  4504. {
  4505. [JsonProperty]
  4506. public int BB_field1;
  4507. public int BB_field2;
  4508. [JsonProperty]
  4509. public int BB_property1 { get; set; }
  4510. [JsonProperty]
  4511. public int BB_property2 { get; private set; }
  4512. [JsonProperty]
  4513. public int BB_property3 { private get; set; }
  4514. [JsonProperty]
  4515. private int BB_property4 { get; set; }
  4516. public int BB_property5 { get; private set; }
  4517. public int BB_property6 { private get; set; }
  4518. [JsonProperty]
  4519. public int BB_property7 { protected get; set; }
  4520. public int BB_property8 { protected get; set; }
  4521. public BB()
  4522. {
  4523. }
  4524. public BB(int f, int g)
  4525. : base(f)
  4526. {
  4527. BB_field1 = g;
  4528. BB_field2 = g;
  4529. BB_property1 = g;
  4530. BB_property2 = g;
  4531. BB_property3 = g;
  4532. BB_property4 = g;
  4533. BB_property5 = g;
  4534. BB_property6 = g;
  4535. BB_property7 = g;
  4536. BB_property8 = g;
  4537. }
  4538. }
  4539. #if !NET20
  4540. public class XNodeTestObject
  4541. {
  4542. public XDocument Document { get; set; }
  4543. public XElement Element { get; set; }
  4544. }
  4545. #endif
  4546. #if !(DNXCORE50)
  4547. public class XmlNodeTestObject
  4548. {
  4549. public XmlDocument Document { get; set; }
  4550. }
  4551. #endif
  4552. #if !(NET20 || PORTABLE40)
  4553. [Test]
  4554. public void SerializeDeserializeXNodeProperties()
  4555. {
  4556. XNodeTestObject testObject = new XNodeTestObject();
  4557. testObject.Document = XDocument.Parse("<root>hehe, root</root>");
  4558. testObject.Element = XElement.Parse(@"<fifth xmlns:json=""http://json.org"" json:Awesome=""true"">element</fifth>");
  4559. string json = JsonConvert.SerializeObject(testObject, Formatting.Indented);
  4560. string expected = @"{
  4561. ""Document"": {
  4562. ""root"": ""hehe, root""
  4563. },
  4564. ""Element"": {
  4565. ""fifth"": {
  4566. ""@xmlns:json"": ""http://json.org"",
  4567. ""@json:Awesome"": ""true"",
  4568. ""#text"": ""element""
  4569. }
  4570. }
  4571. }";
  4572. StringAssert.AreEqual(expected, json);
  4573. XNodeTestObject newTestObject = JsonConvert.DeserializeObject<XNodeTestObject>(json);
  4574. Assert.AreEqual(testObject.Document.ToString(), newTestObject.Document.ToString());
  4575. Assert.AreEqual(testObject.Element.ToString(), newTestObject.Element.ToString());
  4576. Assert.IsNull(newTestObject.Element.Parent);
  4577. }
  4578. #endif
  4579. #if !(PORTABLE || DNXCORE50 || PORTABLE40)
  4580. [Test]
  4581. public void SerializeDeserializeXmlNodeProperties()
  4582. {
  4583. XmlNodeTestObject testObject = new XmlNodeTestObject();
  4584. XmlDocument document = new XmlDocument();
  4585. document.LoadXml("<root>hehe, root</root>");
  4586. testObject.Document = document;
  4587. string json = JsonConvert.SerializeObject(testObject, Formatting.Indented);
  4588. string expected = @"{
  4589. ""Document"": {
  4590. ""root"": ""hehe, root""
  4591. }
  4592. }";
  4593. StringAssert.AreEqual(expected, json);
  4594. XmlNodeTestObject newTestObject = JsonConvert.DeserializeObject<XmlNodeTestObject>(json);
  4595. Assert.AreEqual(testObject.Document.InnerXml, newTestObject.Document.InnerXml);
  4596. }
  4597. #endif
  4598. [Test]
  4599. public void FullClientMapSerialization()
  4600. {
  4601. ClientMap source = new ClientMap()
  4602. {
  4603. position = new Pos() { X = 100, Y = 200 },
  4604. center = new PosDouble() { X = 251.6, Y = 361.3 }
  4605. };
  4606. string json = JsonConvert.SerializeObject(source, new PosConverter(), new PosDoubleConverter());
  4607. Assert.AreEqual("{\"position\":new Pos(100,200),\"center\":new PosD(251.6,361.3)}", json);
  4608. }
  4609. public class ClientMap
  4610. {
  4611. public Pos position { get; set; }
  4612. public PosDouble center { get; set; }
  4613. }
  4614. public class Pos
  4615. {
  4616. public int X { get; set; }
  4617. public int Y { get; set; }
  4618. }
  4619. public class PosDouble
  4620. {
  4621. public double X { get; set; }
  4622. public double Y { get; set; }
  4623. }
  4624. public class PosConverter : JsonConverter
  4625. {
  4626. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  4627. {
  4628. Pos p = (Pos)value;
  4629. if (p != null)
  4630. {
  4631. writer.WriteRawValue(String.Format("new Pos({0},{1})", p.X, p.Y));
  4632. }
  4633. else
  4634. {
  4635. writer.WriteNull();
  4636. }
  4637. }
  4638. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  4639. {
  4640. throw new NotImplementedException();
  4641. }
  4642. public override bool CanConvert(Type objectType)
  4643. {
  4644. return objectType == typeof(Pos);
  4645. }
  4646. }
  4647. public class PosDoubleConverter : JsonConverter
  4648. {
  4649. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  4650. {
  4651. PosDouble p = (PosDouble)value;
  4652. if (p != null)
  4653. {
  4654. writer.WriteRawValue(String.Format(CultureInfo.InvariantCulture, "new PosD({0},{1})", p.X, p.Y));
  4655. }
  4656. else
  4657. {
  4658. writer.WriteNull();
  4659. }
  4660. }
  4661. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  4662. {
  4663. throw new NotImplementedException();
  4664. }
  4665. public override bool CanConvert(Type objectType)
  4666. {
  4667. return objectType == typeof(PosDouble);
  4668. }
  4669. }
  4670. [Test]
  4671. public void SerializeRefAdditionalContent()
  4672. {
  4673. //Additional text found in JSON string after finishing deserializing object.
  4674. //Test 1
  4675. var reference = new Dictionary<string, object>();
  4676. reference.Add("$ref", "Persons");
  4677. reference.Add("$id", 1);
  4678. var child = new Dictionary<string, object>();
  4679. child.Add("_id", 2);
  4680. child.Add("Name", "Isabell");
  4681. child.Add("Father", reference);
  4682. var json = JsonConvert.SerializeObject(child, Formatting.Indented);
  4683. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Dictionary<string, object>>(json); }, "Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Path 'Father.$id', line 6, position 10.");
  4684. }
  4685. [Test]
  4686. public void SerializeRefBadType()
  4687. {
  4688. ExceptionAssert.Throws<JsonSerializationException>(() =>
  4689. {
  4690. //Additional text found in JSON string after finishing deserializing object.
  4691. //Test 1
  4692. var reference = new Dictionary<string, object>();
  4693. reference.Add("$ref", 1);
  4694. reference.Add("$id", 1);
  4695. var child = new Dictionary<string, object>();
  4696. child.Add("_id", 2);
  4697. child.Add("Name", "Isabell");
  4698. child.Add("Father", reference);
  4699. var json = JsonConvert.SerializeObject(child, Formatting.Indented);
  4700. JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  4701. }, "JSON reference $ref property must have a string or null value. Path 'Father.$ref', line 5, position 13.");
  4702. }
  4703. [Test]
  4704. public void SerializeRefNull()
  4705. {
  4706. var reference = new Dictionary<string, object>();
  4707. reference.Add("$ref", null);
  4708. reference.Add("$id", null);
  4709. reference.Add("blah", "blah!");
  4710. var child = new Dictionary<string, object>();
  4711. child.Add("_id", 2);
  4712. child.Add("Name", "Isabell");
  4713. child.Add("Father", reference);
  4714. string json = JsonConvert.SerializeObject(child);
  4715. Assert.AreEqual(@"{""_id"":2,""Name"":""Isabell"",""Father"":{""$ref"":null,""$id"":null,""blah"":""blah!""}}", json);
  4716. Dictionary<string, object> result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  4717. Assert.AreEqual(3, result.Count);
  4718. Assert.AreEqual(1, ((JObject)result["Father"]).Count);
  4719. Assert.AreEqual("blah!", (string)((JObject)result["Father"])["blah"]);
  4720. }
  4721. public class ConstructorCompexIgnoredProperty
  4722. {
  4723. [JsonIgnore]
  4724. public Product Ignored { get; set; }
  4725. public string First { get; set; }
  4726. public int Second { get; set; }
  4727. public ConstructorCompexIgnoredProperty(string first, int second)
  4728. {
  4729. First = first;
  4730. Second = second;
  4731. }
  4732. }
  4733. [Test]
  4734. public void DeserializeIgnoredPropertyInConstructor()
  4735. {
  4736. string json = @"{""First"":""First"",""Second"":2,""Ignored"":{""Name"":""James""},""AdditionalContent"":{""LOL"":true}}";
  4737. ConstructorCompexIgnoredProperty cc = JsonConvert.DeserializeObject<ConstructorCompexIgnoredProperty>(json);
  4738. Assert.AreEqual("First", cc.First);
  4739. Assert.AreEqual(2, cc.Second);
  4740. Assert.AreEqual(null, cc.Ignored);
  4741. }
  4742. [Test]
  4743. public void DeserializeFloatAsDecimal()
  4744. {
  4745. string json = @"{'value':9.9}";
  4746. var dic = JsonConvert.DeserializeObject<IDictionary<string, object>>(
  4747. json, new JsonSerializerSettings
  4748. {
  4749. FloatParseHandling = FloatParseHandling.Decimal
  4750. });
  4751. Assert.AreEqual(typeof(decimal), dic["value"].GetType());
  4752. Assert.AreEqual(9.9m, dic["value"]);
  4753. }
  4754. public class DictionaryKey
  4755. {
  4756. public string Value { get; set; }
  4757. public override string ToString()
  4758. {
  4759. return Value;
  4760. }
  4761. public static implicit operator DictionaryKey(string value)
  4762. {
  4763. return new DictionaryKey() { Value = value };
  4764. }
  4765. }
  4766. [Test]
  4767. public void SerializeDeserializeDictionaryKey()
  4768. {
  4769. Dictionary<DictionaryKey, string> dictionary = new Dictionary<DictionaryKey, string>();
  4770. dictionary.Add(new DictionaryKey() { Value = "First!" }, "First");
  4771. dictionary.Add(new DictionaryKey() { Value = "Second!" }, "Second");
  4772. string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
  4773. StringAssert.AreEqual(@"{
  4774. ""First!"": ""First"",
  4775. ""Second!"": ""Second""
  4776. }", json);
  4777. Dictionary<DictionaryKey, string> newDictionary =
  4778. JsonConvert.DeserializeObject<Dictionary<DictionaryKey, string>>(json);
  4779. Assert.AreEqual(2, newDictionary.Count);
  4780. }
  4781. [Test]
  4782. public void SerializeNullableArray()
  4783. {
  4784. string jsonText = JsonConvert.SerializeObject(new double?[] { 2.4, 4.3, null }, Formatting.Indented);
  4785. StringAssert.AreEqual(@"[
  4786. 2.4,
  4787. 4.3,
  4788. null
  4789. ]", jsonText);
  4790. }
  4791. [Test]
  4792. public void DeserializeNullableArray()
  4793. {
  4794. double?[] d = (double?[])JsonConvert.DeserializeObject(@"[
  4795. 2.4,
  4796. 4.3,
  4797. null
  4798. ]", typeof(double?[]));
  4799. Assert.AreEqual(3, d.Length);
  4800. Assert.AreEqual(2.4, d[0]);
  4801. Assert.AreEqual(4.3, d[1]);
  4802. Assert.AreEqual(null, d[2]);
  4803. }
  4804. #if !NET20
  4805. [Test]
  4806. public void SerializeHashSet()
  4807. {
  4808. string jsonText = JsonConvert.SerializeObject(new HashSet<string>()
  4809. {
  4810. "One",
  4811. "2",
  4812. "III"
  4813. }, Formatting.Indented);
  4814. StringAssert.AreEqual(@"[
  4815. ""One"",
  4816. ""2"",
  4817. ""III""
  4818. ]", jsonText);
  4819. HashSet<string> d = JsonConvert.DeserializeObject<HashSet<string>>(jsonText);
  4820. Assert.AreEqual(3, d.Count);
  4821. Assert.IsTrue(d.Contains("One"));
  4822. Assert.IsTrue(d.Contains("2"));
  4823. Assert.IsTrue(d.Contains("III"));
  4824. }
  4825. #endif
  4826. private class MyClass
  4827. {
  4828. public byte[] Prop1 { get; set; }
  4829. public MyClass()
  4830. {
  4831. Prop1 = new byte[0];
  4832. }
  4833. }
  4834. [Test]
  4835. public void DeserializeByteArray()
  4836. {
  4837. JsonSerializer serializer1 = new JsonSerializer();
  4838. serializer1.Converters.Add(new IsoDateTimeConverter());
  4839. serializer1.NullValueHandling = NullValueHandling.Ignore;
  4840. string json = @"[{""Prop1"":""""},{""Prop1"":""""}]";
  4841. JsonTextReader reader = new JsonTextReader(new StringReader(json));
  4842. MyClass[] z = (MyClass[])serializer1.Deserialize(reader, typeof(MyClass[]));
  4843. Assert.AreEqual(2, z.Length);
  4844. Assert.AreEqual(0, z[0].Prop1.Length);
  4845. Assert.AreEqual(0, z[1].Prop1.Length);
  4846. }
  4847. #if !(NET20 || DNXCORE50)
  4848. public class StringDictionaryTestClass
  4849. {
  4850. public StringDictionary StringDictionaryProperty { get; set; }
  4851. }
  4852. [Test]
  4853. public void StringDictionaryTest()
  4854. {
  4855. string classRef = typeof(StringDictionary).FullName;
  4856. StringDictionaryTestClass s1 = new StringDictionaryTestClass()
  4857. {
  4858. StringDictionaryProperty = new StringDictionary()
  4859. {
  4860. { "1", "One" },
  4861. { "2", "II" },
  4862. { "3", "3" }
  4863. }
  4864. };
  4865. string json = JsonConvert.SerializeObject(s1, Formatting.Indented);
  4866. // .NET 4.5.3 added IDictionary<string, string> to StringDictionary
  4867. if (s1.StringDictionaryProperty is IDictionary<string, string>)
  4868. {
  4869. StringDictionaryTestClass d = JsonConvert.DeserializeObject<StringDictionaryTestClass>(json);
  4870. Assert.AreEqual(3, d.StringDictionaryProperty.Count);
  4871. Assert.AreEqual("One", d.StringDictionaryProperty["1"]);
  4872. Assert.AreEqual("II", d.StringDictionaryProperty["2"]);
  4873. Assert.AreEqual("3", d.StringDictionaryProperty["3"]);
  4874. }
  4875. else
  4876. {
  4877. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<StringDictionaryTestClass>(json); }, "Cannot create and populate list type " + classRef + ". Path 'StringDictionaryProperty', line 2, position 31.");
  4878. }
  4879. }
  4880. #endif
  4881. [JsonObject(MemberSerialization.OptIn)]
  4882. public struct StructWithAttribute
  4883. {
  4884. public string MyString { get; set; }
  4885. [JsonProperty]
  4886. public int MyInt { get; set; }
  4887. }
  4888. [Test]
  4889. public void SerializeStructWithJsonObjectAttribute()
  4890. {
  4891. StructWithAttribute testStruct = new StructWithAttribute
  4892. {
  4893. MyInt = int.MaxValue
  4894. };
  4895. string json = JsonConvert.SerializeObject(testStruct, Formatting.Indented);
  4896. StringAssert.AreEqual(@"{
  4897. ""MyInt"": 2147483647
  4898. }", json);
  4899. StructWithAttribute newStruct = JsonConvert.DeserializeObject<StructWithAttribute>(json);
  4900. Assert.AreEqual(int.MaxValue, newStruct.MyInt);
  4901. }
  4902. public class TimeZoneOffsetObject
  4903. {
  4904. public DateTimeOffset Offset { get; set; }
  4905. }
  4906. #if !NET20
  4907. [Test]
  4908. public void ReadWriteTimeZoneOffsetIso()
  4909. {
  4910. var serializeObject = JsonConvert.SerializeObject(new TimeZoneOffsetObject
  4911. {
  4912. Offset = new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6))
  4913. });
  4914. Assert.AreEqual("{\"Offset\":\"2000-01-01T00:00:00+06:00\"}", serializeObject);
  4915. JsonTextReader reader = new JsonTextReader(new StringReader(serializeObject))
  4916. {
  4917. DateParseHandling = DateParseHandling.None
  4918. };
  4919. JsonSerializer serializer = new JsonSerializer();
  4920. var deserializeObject = serializer.Deserialize<TimeZoneOffsetObject>(reader);
  4921. Assert.AreEqual(TimeSpan.FromHours(6), deserializeObject.Offset.Offset);
  4922. Assert.AreEqual(new DateTime(2000, 1, 1), deserializeObject.Offset.Date);
  4923. }
  4924. [Test]
  4925. public void DeserializePropertyNullableDateTimeOffsetExactIso()
  4926. {
  4927. NullableDateTimeTestClass d = JsonConvert.DeserializeObject<NullableDateTimeTestClass>("{\"DateTimeOffsetField\":\"2000-01-01T00:00:00+06:00\"}");
  4928. Assert.AreEqual(new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6)), d.DateTimeOffsetField);
  4929. }
  4930. [Test]
  4931. public void ReadWriteTimeZoneOffsetMsAjax()
  4932. {
  4933. var serializeObject = JsonConvert.SerializeObject(new TimeZoneOffsetObject
  4934. {
  4935. Offset = new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6))
  4936. }, Formatting.None, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
  4937. Assert.AreEqual("{\"Offset\":\"\\/Date(946663200000+0600)\\/\"}", serializeObject);
  4938. JsonTextReader reader = new JsonTextReader(new StringReader(serializeObject));
  4939. JsonSerializer serializer = new JsonSerializer();
  4940. serializer.DateParseHandling = DateParseHandling.None;
  4941. var deserializeObject = serializer.Deserialize<TimeZoneOffsetObject>(reader);
  4942. Assert.AreEqual(TimeSpan.FromHours(6), deserializeObject.Offset.Offset);
  4943. Assert.AreEqual(new DateTime(2000, 1, 1), deserializeObject.Offset.Date);
  4944. }
  4945. [Test]
  4946. public void DeserializePropertyNullableDateTimeOffsetExactMsAjax()
  4947. {
  4948. NullableDateTimeTestClass d = JsonConvert.DeserializeObject<NullableDateTimeTestClass>("{\"DateTimeOffsetField\":\"\\/Date(946663200000+0600)\\/\"}");
  4949. Assert.AreEqual(new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6)), d.DateTimeOffsetField);
  4950. }
  4951. #endif
  4952. public abstract class LogEvent
  4953. {
  4954. [JsonProperty("event")]
  4955. public abstract string EventName { get; }
  4956. }
  4957. public class DerivedEvent : LogEvent
  4958. {
  4959. public override string EventName
  4960. {
  4961. get { return "derived"; }
  4962. }
  4963. }
  4964. [Test]
  4965. public void OverridenPropertyMembers()
  4966. {
  4967. string json = JsonConvert.SerializeObject(new DerivedEvent(), Formatting.Indented);
  4968. StringAssert.AreEqual(@"{
  4969. ""event"": ""derived""
  4970. }", json);
  4971. }
  4972. #if !(NET35 || NET20 || PORTABLE40)
  4973. [Test]
  4974. public void SerializeExpandoObject()
  4975. {
  4976. dynamic expando = new ExpandoObject();
  4977. expando.Int = 1;
  4978. expando.Decimal = 99.9d;
  4979. expando.Complex = new ExpandoObject();
  4980. expando.Complex.String = "I am a string";
  4981. expando.Complex.DateTime = new DateTime(2000, 12, 20, 18, 55, 0, DateTimeKind.Utc);
  4982. string json = JsonConvert.SerializeObject(expando, Formatting.Indented);
  4983. StringAssert.AreEqual(@"{
  4984. ""Int"": 1,
  4985. ""Decimal"": 99.9,
  4986. ""Complex"": {
  4987. ""String"": ""I am a string"",
  4988. ""DateTime"": ""2000-12-20T18:55:00Z""
  4989. }
  4990. }", json);
  4991. IDictionary<string, object> newExpando = JsonConvert.DeserializeObject<ExpandoObject>(json);
  4992. CustomAssert.IsInstanceOfType(typeof(long), newExpando["Int"]);
  4993. Assert.AreEqual((long)expando.Int, newExpando["Int"]);
  4994. CustomAssert.IsInstanceOfType(typeof(double), newExpando["Decimal"]);
  4995. Assert.AreEqual(expando.Decimal, newExpando["Decimal"]);
  4996. CustomAssert.IsInstanceOfType(typeof(ExpandoObject), newExpando["Complex"]);
  4997. IDictionary<string, object> o = (ExpandoObject)newExpando["Complex"];
  4998. CustomAssert.IsInstanceOfType(typeof(string), o["String"]);
  4999. Assert.AreEqual(expando.Complex.String, o["String"]);
  5000. CustomAssert.IsInstanceOfType(typeof(DateTime), o["DateTime"]);
  5001. Assert.AreEqual(expando.Complex.DateTime, o["DateTime"]);
  5002. }
  5003. #endif
  5004. [Test]
  5005. public void DeserializeDecimalExact()
  5006. {
  5007. decimal d = JsonConvert.DeserializeObject<decimal>("123456789876543.21");
  5008. Assert.AreEqual(123456789876543.21m, d);
  5009. }
  5010. [Test]
  5011. public void DeserializeNullableDecimalExact()
  5012. {
  5013. decimal? d = JsonConvert.DeserializeObject<decimal?>("123456789876543.21");
  5014. Assert.AreEqual(123456789876543.21m, d);
  5015. }
  5016. [Test]
  5017. public void DeserializeDecimalPropertyExact()
  5018. {
  5019. string json = "{Amount:123456789876543.21}";
  5020. JsonTextReader reader = new JsonTextReader(new StringReader(json));
  5021. reader.FloatParseHandling = FloatParseHandling.Decimal;
  5022. JsonSerializer serializer = new JsonSerializer();
  5023. Invoice i = serializer.Deserialize<Invoice>(reader);
  5024. Assert.AreEqual(123456789876543.21m, i.Amount);
  5025. }
  5026. [Test]
  5027. public void DeserializeDecimalArrayExact()
  5028. {
  5029. string json = "[123456789876543.21]";
  5030. IList<decimal> a = JsonConvert.DeserializeObject<IList<decimal>>(json);
  5031. Assert.AreEqual(123456789876543.21m, a[0]);
  5032. }
  5033. [Test]
  5034. public void DeserializeDecimalDictionaryExact()
  5035. {
  5036. string json = "{'Value':123456789876543.21}";
  5037. JsonTextReader reader = new JsonTextReader(new StringReader(json));
  5038. reader.FloatParseHandling = FloatParseHandling.Decimal;
  5039. JsonSerializer serializer = new JsonSerializer();
  5040. IDictionary<string, decimal> d = serializer.Deserialize<IDictionary<string, decimal>>(reader);
  5041. Assert.AreEqual(123456789876543.21m, d["Value"]);
  5042. }
  5043. public struct Vector
  5044. {
  5045. public float X;
  5046. public float Y;
  5047. public float Z;
  5048. public override string ToString()
  5049. {
  5050. return string.Format("({0},{1},{2})", X, Y, Z);
  5051. }
  5052. }
  5053. public class VectorParent
  5054. {
  5055. public Vector Position;
  5056. }
  5057. [Test]
  5058. public void DeserializeStructProperty()
  5059. {
  5060. VectorParent obj = new VectorParent();
  5061. obj.Position = new Vector { X = 1, Y = 2, Z = 3 };
  5062. string str = JsonConvert.SerializeObject(obj);
  5063. obj = JsonConvert.DeserializeObject<VectorParent>(str);
  5064. Assert.AreEqual(1, obj.Position.X);
  5065. Assert.AreEqual(2, obj.Position.Y);
  5066. Assert.AreEqual(3, obj.Position.Z);
  5067. }
  5068. [JsonObject(MemberSerialization.OptIn)]
  5069. public class Derived : Base
  5070. {
  5071. [JsonProperty]
  5072. public string IDoWork { get; private set; }
  5073. private Derived()
  5074. {
  5075. }
  5076. internal Derived(string dontWork, string doWork)
  5077. : base(dontWork)
  5078. {
  5079. IDoWork = doWork;
  5080. }
  5081. }
  5082. [JsonObject(MemberSerialization.OptIn)]
  5083. public class Base
  5084. {
  5085. [JsonProperty]
  5086. public string IDontWork { get; private set; }
  5087. protected Base()
  5088. {
  5089. }
  5090. internal Base(string dontWork)
  5091. {
  5092. IDontWork = dontWork;
  5093. }
  5094. }
  5095. [Test]
  5096. public void PrivateSetterOnBaseClassProperty()
  5097. {
  5098. var derived = new Derived("meh", "woo");
  5099. var settings = new JsonSerializerSettings
  5100. {
  5101. TypeNameHandling = TypeNameHandling.Objects,
  5102. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
  5103. };
  5104. string json = JsonConvert.SerializeObject(derived, Formatting.Indented, settings);
  5105. var meh = JsonConvert.DeserializeObject<Base>(json, settings);
  5106. Assert.AreEqual(((Derived)meh).IDoWork, "woo");
  5107. Assert.AreEqual(meh.IDontWork, "meh");
  5108. }
  5109. #if !(NET20 || DNXCORE50)
  5110. [DataContract]
  5111. public struct StructISerializable : ISerializable
  5112. {
  5113. private string _name;
  5114. public StructISerializable(SerializationInfo info, StreamingContext context)
  5115. {
  5116. _name = info.GetString("Name");
  5117. }
  5118. [DataMember]
  5119. public string Name
  5120. {
  5121. get { return _name; }
  5122. set { _name = value; }
  5123. }
  5124. public void GetObjectData(SerializationInfo info, StreamingContext context)
  5125. {
  5126. info.AddValue("Name", _name);
  5127. }
  5128. }
  5129. [DataContract]
  5130. public class NullableStructPropertyClass
  5131. {
  5132. private StructISerializable _foo1;
  5133. private StructISerializable? _foo2;
  5134. [DataMember]
  5135. public StructISerializable Foo1
  5136. {
  5137. get { return _foo1; }
  5138. set { _foo1 = value; }
  5139. }
  5140. [DataMember]
  5141. public StructISerializable? Foo2
  5142. {
  5143. get { return _foo2; }
  5144. set { _foo2 = value; }
  5145. }
  5146. }
  5147. [Test]
  5148. public void DeserializeNullableStruct()
  5149. {
  5150. NullableStructPropertyClass nullableStructPropertyClass = new NullableStructPropertyClass()
  5151. {
  5152. Foo1 = new StructISerializable() { Name = "foo 1" },
  5153. Foo2 = new StructISerializable() { Name = "foo 2" }
  5154. };
  5155. NullableStructPropertyClass barWithNull = new NullableStructPropertyClass()
  5156. {
  5157. Foo1 = new StructISerializable() { Name = "foo 1" },
  5158. Foo2 = null
  5159. };
  5160. //throws error on deserialization because bar1.Foo2 is of type Foo?
  5161. string s = JsonConvert.SerializeObject(nullableStructPropertyClass);
  5162. NullableStructPropertyClass deserialized = deserialize(s);
  5163. Assert.AreEqual(deserialized.Foo1.Name, "foo 1");
  5164. Assert.AreEqual(deserialized.Foo2.Value.Name, "foo 2");
  5165. //no error Foo2 is null
  5166. s = JsonConvert.SerializeObject(barWithNull);
  5167. deserialized = deserialize(s);
  5168. Assert.AreEqual(deserialized.Foo1.Name, "foo 1");
  5169. Assert.AreEqual(deserialized.Foo2, null);
  5170. }
  5171. private static NullableStructPropertyClass deserialize(string serStr)
  5172. {
  5173. return JsonConvert.DeserializeObject<NullableStructPropertyClass>(
  5174. serStr,
  5175. new JsonSerializerSettings
  5176. {
  5177. NullValueHandling = NullValueHandling.Ignore,
  5178. MissingMemberHandling = MissingMemberHandling.Ignore
  5179. });
  5180. }
  5181. #endif
  5182. public class Response
  5183. {
  5184. public string Name { get; set; }
  5185. public JToken Data { get; set; }
  5186. }
  5187. [Test]
  5188. public void DeserializeJToken()
  5189. {
  5190. Response response = new Response
  5191. {
  5192. Name = "Success",
  5193. Data = new JObject(new JProperty("First", "Value1"), new JProperty("Second", "Value2"))
  5194. };
  5195. string json = JsonConvert.SerializeObject(response, Formatting.Indented);
  5196. Response deserializedResponse = JsonConvert.DeserializeObject<Response>(json);
  5197. Assert.AreEqual("Success", deserializedResponse.Name);
  5198. Assert.IsTrue(deserializedResponse.Data.DeepEquals(response.Data));
  5199. }
  5200. [Test]
  5201. public void DeserializeMinValueDecimal()
  5202. {
  5203. var data = new DecimalTest(decimal.MinValue);
  5204. var json = JsonConvert.SerializeObject(data);
  5205. var obj = JsonConvert.DeserializeObject<DecimalTest>(json, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Default });
  5206. Assert.AreEqual(decimal.MinValue, obj.Value);
  5207. }
  5208. [Test]
  5209. public void NonPublicConstructorWithJsonConstructorTest()
  5210. {
  5211. NonPublicConstructorWithJsonConstructor c = JsonConvert.DeserializeObject<NonPublicConstructorWithJsonConstructor>("{}");
  5212. Assert.AreEqual("NonPublic", c.Constructor);
  5213. }
  5214. [Test]
  5215. public void PublicConstructorOverridenByJsonConstructorTest()
  5216. {
  5217. PublicConstructorOverridenByJsonConstructor c = JsonConvert.DeserializeObject<PublicConstructorOverridenByJsonConstructor>("{Value:'value!'}");
  5218. Assert.AreEqual("Public Parameterized", c.Constructor);
  5219. Assert.AreEqual("value!", c.Value);
  5220. }
  5221. [Test]
  5222. public void MultipleParametrizedConstructorsJsonConstructorTest()
  5223. {
  5224. MultipleParametrizedConstructorsJsonConstructor c = JsonConvert.DeserializeObject<MultipleParametrizedConstructorsJsonConstructor>("{Value:'value!', Age:1}");
  5225. Assert.AreEqual("Public Parameterized 2", c.Constructor);
  5226. Assert.AreEqual("value!", c.Value);
  5227. Assert.AreEqual(1, c.Age);
  5228. }
  5229. [Test]
  5230. public void DeserializeEnumerable()
  5231. {
  5232. EnumerableClass c = new EnumerableClass
  5233. {
  5234. Enumerable = new List<string> { "One", "Two", "Three" }
  5235. };
  5236. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  5237. StringAssert.AreEqual(@"{
  5238. ""Enumerable"": [
  5239. ""One"",
  5240. ""Two"",
  5241. ""Three""
  5242. ]
  5243. }", json);
  5244. EnumerableClass c2 = JsonConvert.DeserializeObject<EnumerableClass>(json);
  5245. Assert.AreEqual("One", c2.Enumerable.ElementAt(0));
  5246. Assert.AreEqual("Two", c2.Enumerable.ElementAt(1));
  5247. Assert.AreEqual("Three", c2.Enumerable.ElementAt(2));
  5248. }
  5249. [Test]
  5250. public void SerializeAttributesOnBase()
  5251. {
  5252. ComplexItem i = new ComplexItem();
  5253. string json = JsonConvert.SerializeObject(i, Formatting.Indented);
  5254. StringAssert.AreEqual(@"{
  5255. ""Name"": null
  5256. }", json);
  5257. }
  5258. [Test]
  5259. public void DeserializeStringEnglish()
  5260. {
  5261. string json = @"{
  5262. 'Name': 'James Hughes',
  5263. 'Age': '40',
  5264. 'Height': '44.4',
  5265. 'Price': '4'
  5266. }";
  5267. DeserializeStringConvert p = JsonConvert.DeserializeObject<DeserializeStringConvert>(json);
  5268. Assert.AreEqual(40, p.Age);
  5269. Assert.AreEqual(44.4, p.Height);
  5270. Assert.AreEqual(4m, p.Price);
  5271. }
  5272. [Test]
  5273. public void DeserializeNullDateTimeValueTest()
  5274. {
  5275. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject("null", typeof(DateTime)); }, "Error converting value {null} to type 'System.DateTime'. Path '', line 1, position 4.");
  5276. }
  5277. [Test]
  5278. public void DeserializeNullNullableDateTimeValueTest()
  5279. {
  5280. object dateTime = JsonConvert.DeserializeObject("null", typeof(DateTime?));
  5281. Assert.IsNull(dateTime);
  5282. }
  5283. [Test]
  5284. public void MultiIndexSuperTest()
  5285. {
  5286. MultiIndexSuper e = new MultiIndexSuper();
  5287. string json = JsonConvert.SerializeObject(e, Formatting.Indented);
  5288. Assert.AreEqual(@"{}", json);
  5289. }
  5290. public class MultiIndexSuper : MultiIndexBase
  5291. {
  5292. }
  5293. public abstract class MultiIndexBase
  5294. {
  5295. protected internal object this[string propertyName]
  5296. {
  5297. get { return null; }
  5298. set { }
  5299. }
  5300. protected internal object this[object property]
  5301. {
  5302. get { return null; }
  5303. set { }
  5304. }
  5305. }
  5306. public class CommentTestClass
  5307. {
  5308. public bool Indexed { get; set; }
  5309. public int StartYear { get; set; }
  5310. public IList<decimal> Values { get; set; }
  5311. }
  5312. [Test]
  5313. public void CommentTestClassTest()
  5314. {
  5315. string json = @"{""indexed"":true, ""startYear"":1939, ""values"":
  5316. [ 3000, /* 1940-1949 */
  5317. 3000, 3600, 3600, 3600, 3600, 4200, 4200, 4200, 4200, 4800, /* 1950-1959 */
  5318. 4800, 4800, 4800, 4800, 4800, 4800, 6600, 6600, 7800, 7800, /* 1960-1969 */
  5319. 7800, 7800, 9000, 10800, 13200, 14100, 15300, 16500, 17700, 22900, /* 1970-1979 */
  5320. 25900, 29700, 32400, 35700, 37800, 39600, 42000, 43800, 45000, 48000, /* 1980-1989 */
  5321. 51300, 53400, 55500, 57600, 60600, 61200, 62700, 65400, 68400, 72600, /* 1990-1999 */
  5322. 76200, 80400, 84900, 87000, 87900, 90000, 94200, 97500, 102000, 106800, /* 2000-2009 */
  5323. 106800, 106800] /* 2010-2011 */
  5324. }";
  5325. CommentTestClass commentTestClass = JsonConvert.DeserializeObject<CommentTestClass>(json);
  5326. Assert.AreEqual(true, commentTestClass.Indexed);
  5327. Assert.AreEqual(1939, commentTestClass.StartYear);
  5328. Assert.AreEqual(63, commentTestClass.Values.Count);
  5329. }
  5330. private class DTOWithParameterisedConstructor
  5331. {
  5332. public DTOWithParameterisedConstructor(string A)
  5333. {
  5334. this.A = A;
  5335. B = 2;
  5336. }
  5337. public string A { get; set; }
  5338. public int? B { get; set; }
  5339. }
  5340. private class DTOWithoutParameterisedConstructor
  5341. {
  5342. public DTOWithoutParameterisedConstructor()
  5343. {
  5344. B = 2;
  5345. }
  5346. public string A { get; set; }
  5347. public int? B { get; set; }
  5348. }
  5349. [Test]
  5350. public void PopulationBehaviourForOmittedPropertiesIsTheSameForParameterisedConstructorAsForDefaultConstructor()
  5351. {
  5352. string json = @"{A:""Test""}";
  5353. var withoutParameterisedConstructor = JsonConvert.DeserializeObject<DTOWithoutParameterisedConstructor>(json);
  5354. var withParameterisedConstructor = JsonConvert.DeserializeObject<DTOWithParameterisedConstructor>(json);
  5355. Assert.AreEqual(withoutParameterisedConstructor.B, withParameterisedConstructor.B);
  5356. }
  5357. public class EnumerableArrayPropertyClass
  5358. {
  5359. public IEnumerable<int> Numbers
  5360. {
  5361. get
  5362. {
  5363. return new[] { 1, 2, 3 }; //fails
  5364. //return new List<int>(new[] { 1, 2, 3 }); //works
  5365. }
  5366. }
  5367. }
  5368. [Test]
  5369. public void SkipPopulatingArrayPropertyClass()
  5370. {
  5371. string json = JsonConvert.SerializeObject(new EnumerableArrayPropertyClass());
  5372. JsonConvert.DeserializeObject<EnumerableArrayPropertyClass>(json);
  5373. }
  5374. #if !(NET20)
  5375. [DataContract]
  5376. public class BaseDataContract
  5377. {
  5378. [DataMember(Name = "virtualMember")]
  5379. public virtual string VirtualMember { get; set; }
  5380. [DataMember(Name = "nonVirtualMember")]
  5381. public string NonVirtualMember { get; set; }
  5382. }
  5383. public class ChildDataContract : BaseDataContract
  5384. {
  5385. public override string VirtualMember { get; set; }
  5386. public string NewMember { get; set; }
  5387. }
  5388. [Test]
  5389. public void ChildDataContractTest()
  5390. {
  5391. ChildDataContract cc = new ChildDataContract
  5392. {
  5393. VirtualMember = "VirtualMember!",
  5394. NonVirtualMember = "NonVirtualMember!"
  5395. };
  5396. string result = JsonConvert.SerializeObject(cc, Formatting.Indented);
  5397. // Assert.AreEqual(@"{
  5398. // ""VirtualMember"": ""VirtualMember!"",
  5399. // ""NewMember"": null,
  5400. // ""nonVirtualMember"": ""NonVirtualMember!""
  5401. //}", result);
  5402. StringAssert.AreEqual(@"{
  5403. ""virtualMember"": ""VirtualMember!"",
  5404. ""nonVirtualMember"": ""NonVirtualMember!""
  5405. }", result);
  5406. }
  5407. [Test]
  5408. public void ChildDataContractTestWithDataContractSerializer()
  5409. {
  5410. ChildDataContract cc = new ChildDataContract
  5411. {
  5412. VirtualMember = "VirtualMember!",
  5413. NonVirtualMember = "NonVirtualMember!"
  5414. };
  5415. DataContractSerializer serializer = new DataContractSerializer(typeof(ChildDataContract));
  5416. MemoryStream ms = new MemoryStream();
  5417. serializer.WriteObject(ms, cc);
  5418. string xml = Encoding.UTF8.GetString(ms.ToArray(), 0, Convert.ToInt32(ms.Length));
  5419. Assert.AreEqual(@"<JsonSerializerTest.ChildDataContract xmlns=""http://schemas.datacontract.org/2004/07/Newtonsoft.Json.Tests.Serialization"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><nonVirtualMember>NonVirtualMember!</nonVirtualMember><virtualMember>VirtualMember!</virtualMember><NewMember i:nil=""true""/></JsonSerializerTest.ChildDataContract>", xml);
  5420. }
  5421. #endif
  5422. [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
  5423. public class BaseObject
  5424. {
  5425. [JsonProperty(PropertyName = "virtualMember")]
  5426. public virtual string VirtualMember { get; set; }
  5427. [JsonProperty(PropertyName = "nonVirtualMember")]
  5428. public string NonVirtualMember { get; set; }
  5429. }
  5430. public class ChildObject : BaseObject
  5431. {
  5432. public override string VirtualMember { get; set; }
  5433. public string NewMember { get; set; }
  5434. }
  5435. public class ChildWithDifferentOverrideObject : BaseObject
  5436. {
  5437. [JsonProperty(PropertyName = "differentVirtualMember")]
  5438. public override string VirtualMember { get; set; }
  5439. }
  5440. [Test]
  5441. public void ChildObjectTest()
  5442. {
  5443. ChildObject cc = new ChildObject
  5444. {
  5445. VirtualMember = "VirtualMember!",
  5446. NonVirtualMember = "NonVirtualMember!"
  5447. };
  5448. string result = JsonConvert.SerializeObject(cc);
  5449. Assert.AreEqual(@"{""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  5450. }
  5451. [Test]
  5452. public void ChildWithDifferentOverrideObjectTest()
  5453. {
  5454. ChildWithDifferentOverrideObject cc = new ChildWithDifferentOverrideObject
  5455. {
  5456. VirtualMember = "VirtualMember!",
  5457. NonVirtualMember = "NonVirtualMember!"
  5458. };
  5459. string result = JsonConvert.SerializeObject(cc);
  5460. Assert.AreEqual(@"{""differentVirtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  5461. }
  5462. [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
  5463. public interface IInterfaceObject
  5464. {
  5465. [JsonProperty(PropertyName = "virtualMember")]
  5466. [JsonConverter(typeof(IsoDateTimeConverter))]
  5467. DateTime InterfaceMember { get; set; }
  5468. }
  5469. public class ImplementInterfaceObject : IInterfaceObject
  5470. {
  5471. public DateTime InterfaceMember { get; set; }
  5472. public string NewMember { get; set; }
  5473. [JsonProperty(PropertyName = "newMemberWithProperty")]
  5474. public string NewMemberWithProperty { get; set; }
  5475. }
  5476. [Test]
  5477. public void ImplementInterfaceObjectTest()
  5478. {
  5479. ImplementInterfaceObject cc = new ImplementInterfaceObject
  5480. {
  5481. InterfaceMember = new DateTime(2010, 12, 31, 0, 0, 0, DateTimeKind.Utc),
  5482. NewMember = "NewMember!"
  5483. };
  5484. string result = JsonConvert.SerializeObject(cc, Formatting.Indented);
  5485. StringAssert.AreEqual(@"{
  5486. ""virtualMember"": ""2010-12-31T00:00:00Z"",
  5487. ""newMemberWithProperty"": null
  5488. }", result);
  5489. }
  5490. public class NonDefaultConstructorWithReadOnlyCollectionProperty
  5491. {
  5492. public string Title { get; set; }
  5493. public IList<string> Categories { get; private set; }
  5494. public NonDefaultConstructorWithReadOnlyCollectionProperty(string title)
  5495. {
  5496. Title = title;
  5497. Categories = new List<string>();
  5498. }
  5499. }
  5500. [Test]
  5501. public void NonDefaultConstructorWithReadOnlyCollectionPropertyTest()
  5502. {
  5503. NonDefaultConstructorWithReadOnlyCollectionProperty c1 = new NonDefaultConstructorWithReadOnlyCollectionProperty("blah");
  5504. c1.Categories.Add("one");
  5505. c1.Categories.Add("two");
  5506. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  5507. StringAssert.AreEqual(@"{
  5508. ""Title"": ""blah"",
  5509. ""Categories"": [
  5510. ""one"",
  5511. ""two""
  5512. ]
  5513. }", json);
  5514. NonDefaultConstructorWithReadOnlyCollectionProperty c2 = JsonConvert.DeserializeObject<NonDefaultConstructorWithReadOnlyCollectionProperty>(json);
  5515. Assert.AreEqual(c1.Title, c2.Title);
  5516. Assert.AreEqual(c1.Categories.Count, c2.Categories.Count);
  5517. Assert.AreEqual("one", c2.Categories[0]);
  5518. Assert.AreEqual("two", c2.Categories[1]);
  5519. }
  5520. public class NonDefaultConstructorWithReadOnlyDictionaryProperty
  5521. {
  5522. public string Title { get; set; }
  5523. public IDictionary<string, int> Categories { get; private set; }
  5524. public NonDefaultConstructorWithReadOnlyDictionaryProperty(string title)
  5525. {
  5526. Title = title;
  5527. Categories = new Dictionary<string, int>();
  5528. }
  5529. }
  5530. [Test]
  5531. public void NonDefaultConstructorWithReadOnlyDictionaryPropertyTest()
  5532. {
  5533. NonDefaultConstructorWithReadOnlyDictionaryProperty c1 = new NonDefaultConstructorWithReadOnlyDictionaryProperty("blah");
  5534. c1.Categories.Add("one", 1);
  5535. c1.Categories.Add("two", 2);
  5536. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  5537. StringAssert.AreEqual(@"{
  5538. ""Title"": ""blah"",
  5539. ""Categories"": {
  5540. ""one"": 1,
  5541. ""two"": 2
  5542. }
  5543. }", json);
  5544. NonDefaultConstructorWithReadOnlyDictionaryProperty c2 = JsonConvert.DeserializeObject<NonDefaultConstructorWithReadOnlyDictionaryProperty>(json);
  5545. Assert.AreEqual(c1.Title, c2.Title);
  5546. Assert.AreEqual(c1.Categories.Count, c2.Categories.Count);
  5547. Assert.AreEqual(1, c2.Categories["one"]);
  5548. Assert.AreEqual(2, c2.Categories["two"]);
  5549. }
  5550. [JsonObject(MemberSerialization.OptIn)]
  5551. public class ClassAttributeBase
  5552. {
  5553. [JsonProperty]
  5554. public string BaseClassValue { get; set; }
  5555. }
  5556. public class ClassAttributeDerived : ClassAttributeBase
  5557. {
  5558. [JsonProperty]
  5559. public string DerivedClassValue { get; set; }
  5560. public string NonSerialized { get; set; }
  5561. }
  5562. public class CollectionClassAttributeDerived : ClassAttributeBase, ICollection<object>
  5563. {
  5564. [JsonProperty]
  5565. public string CollectionDerivedClassValue { get; set; }
  5566. public void Add(object item)
  5567. {
  5568. throw new NotImplementedException();
  5569. }
  5570. public void Clear()
  5571. {
  5572. throw new NotImplementedException();
  5573. }
  5574. public bool Contains(object item)
  5575. {
  5576. throw new NotImplementedException();
  5577. }
  5578. public void CopyTo(object[] array, int arrayIndex)
  5579. {
  5580. throw new NotImplementedException();
  5581. }
  5582. public int Count
  5583. {
  5584. get { throw new NotImplementedException(); }
  5585. }
  5586. public bool IsReadOnly
  5587. {
  5588. get { throw new NotImplementedException(); }
  5589. }
  5590. public bool Remove(object item)
  5591. {
  5592. throw new NotImplementedException();
  5593. }
  5594. public IEnumerator<object> GetEnumerator()
  5595. {
  5596. throw new NotImplementedException();
  5597. }
  5598. IEnumerator IEnumerable.GetEnumerator()
  5599. {
  5600. throw new NotImplementedException();
  5601. }
  5602. }
  5603. [Test]
  5604. public void ClassAttributesInheritance()
  5605. {
  5606. string json = JsonConvert.SerializeObject(new ClassAttributeDerived
  5607. {
  5608. BaseClassValue = "BaseClassValue!",
  5609. DerivedClassValue = "DerivedClassValue!",
  5610. NonSerialized = "NonSerialized!"
  5611. }, Formatting.Indented);
  5612. StringAssert.AreEqual(@"{
  5613. ""DerivedClassValue"": ""DerivedClassValue!"",
  5614. ""BaseClassValue"": ""BaseClassValue!""
  5615. }", json);
  5616. json = JsonConvert.SerializeObject(new CollectionClassAttributeDerived
  5617. {
  5618. BaseClassValue = "BaseClassValue!",
  5619. CollectionDerivedClassValue = "CollectionDerivedClassValue!"
  5620. }, Formatting.Indented);
  5621. StringAssert.AreEqual(@"{
  5622. ""CollectionDerivedClassValue"": ""CollectionDerivedClassValue!"",
  5623. ""BaseClassValue"": ""BaseClassValue!""
  5624. }", json);
  5625. }
  5626. public class PrivateMembersClassWithAttributes
  5627. {
  5628. public PrivateMembersClassWithAttributes(string privateString, string internalString, string readonlyString)
  5629. {
  5630. _privateString = privateString;
  5631. _readonlyString = readonlyString;
  5632. _internalString = internalString;
  5633. }
  5634. public PrivateMembersClassWithAttributes()
  5635. {
  5636. _readonlyString = "default!";
  5637. }
  5638. [JsonProperty]
  5639. private string _privateString;
  5640. [JsonProperty]
  5641. private readonly string _readonlyString;
  5642. [JsonProperty]
  5643. internal string _internalString;
  5644. public string UseValue()
  5645. {
  5646. return _readonlyString;
  5647. }
  5648. }
  5649. [Test]
  5650. public void PrivateMembersClassWithAttributesTest()
  5651. {
  5652. PrivateMembersClassWithAttributes c1 = new PrivateMembersClassWithAttributes("privateString!", "internalString!", "readonlyString!");
  5653. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  5654. StringAssert.AreEqual(@"{
  5655. ""_privateString"": ""privateString!"",
  5656. ""_readonlyString"": ""readonlyString!"",
  5657. ""_internalString"": ""internalString!""
  5658. }", json);
  5659. PrivateMembersClassWithAttributes c2 = JsonConvert.DeserializeObject<PrivateMembersClassWithAttributes>(json);
  5660. Assert.AreEqual("readonlyString!", c2.UseValue());
  5661. }
  5662. public partial class BusRun
  5663. {
  5664. public IEnumerable<Nullable<DateTime>> Departures { get; set; }
  5665. public Boolean WheelchairAccessible { get; set; }
  5666. }
  5667. [Test]
  5668. public void DeserializeGenericEnumerableProperty()
  5669. {
  5670. BusRun r = JsonConvert.DeserializeObject<BusRun>("{\"Departures\":[\"\\/Date(1309874148734-0400)\\/\",\"\\/Date(1309874148739-0400)\\/\",null],\"WheelchairAccessible\":true}");
  5671. Assert.AreEqual(typeof(List<DateTime?>), r.Departures.GetType());
  5672. Assert.AreEqual(3, r.Departures.Count());
  5673. Assert.IsNotNull(r.Departures.ElementAt(0));
  5674. Assert.IsNotNull(r.Departures.ElementAt(1));
  5675. Assert.IsNull(r.Departures.ElementAt(2));
  5676. }
  5677. #if !(NET20)
  5678. [DataContract]
  5679. public class BaseType
  5680. {
  5681. [DataMember]
  5682. public string zebra;
  5683. }
  5684. [DataContract]
  5685. public class DerivedType : BaseType
  5686. {
  5687. [DataMember(Order = 0)]
  5688. public string bird;
  5689. [DataMember(Order = 1)]
  5690. public string parrot;
  5691. [DataMember]
  5692. public string dog;
  5693. [DataMember(Order = 3)]
  5694. public string antelope;
  5695. [DataMember]
  5696. public string cat;
  5697. [JsonProperty(Order = 1)]
  5698. public string albatross;
  5699. [JsonProperty(Order = -2)]
  5700. public string dinosaur;
  5701. }
  5702. [Test]
  5703. public void JsonPropertyDataMemberOrder()
  5704. {
  5705. DerivedType d = new DerivedType();
  5706. string json = JsonConvert.SerializeObject(d, Formatting.Indented);
  5707. StringAssert.AreEqual(@"{
  5708. ""dinosaur"": null,
  5709. ""dog"": null,
  5710. ""cat"": null,
  5711. ""zebra"": null,
  5712. ""bird"": null,
  5713. ""parrot"": null,
  5714. ""albatross"": null,
  5715. ""antelope"": null
  5716. }", json);
  5717. }
  5718. #endif
  5719. public class ClassWithException
  5720. {
  5721. public IList<Exception> Exceptions { get; set; }
  5722. public ClassWithException()
  5723. {
  5724. Exceptions = new List<Exception>();
  5725. }
  5726. }
  5727. #if !(PORTABLE || DNXCORE50 || PORTABLE40)
  5728. [Test]
  5729. public void SerializeException1()
  5730. {
  5731. ClassWithException classWithException = new ClassWithException();
  5732. try
  5733. {
  5734. throw new Exception("Test Exception");
  5735. }
  5736. catch (Exception ex)
  5737. {
  5738. classWithException.Exceptions.Add(ex);
  5739. }
  5740. string sex = JsonConvert.SerializeObject(classWithException);
  5741. ClassWithException dex = JsonConvert.DeserializeObject<ClassWithException>(sex);
  5742. Assert.AreEqual(dex.Exceptions[0].ToString(), dex.Exceptions[0].ToString());
  5743. sex = JsonConvert.SerializeObject(classWithException, Formatting.Indented);
  5744. dex = JsonConvert.DeserializeObject<ClassWithException>(sex); // this fails!
  5745. Assert.AreEqual(dex.Exceptions[0].ToString(), dex.Exceptions[0].ToString());
  5746. }
  5747. #endif
  5748. [Test]
  5749. public void UriGuidTimeSpanTestClassEmptyTest()
  5750. {
  5751. UriGuidTimeSpanTestClass c1 = new UriGuidTimeSpanTestClass();
  5752. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  5753. StringAssert.AreEqual(@"{
  5754. ""Guid"": ""00000000-0000-0000-0000-000000000000"",
  5755. ""NullableGuid"": null,
  5756. ""TimeSpan"": ""00:00:00"",
  5757. ""NullableTimeSpan"": null,
  5758. ""Uri"": null
  5759. }", json);
  5760. UriGuidTimeSpanTestClass c2 = JsonConvert.DeserializeObject<UriGuidTimeSpanTestClass>(json);
  5761. Assert.AreEqual(c1.Guid, c2.Guid);
  5762. Assert.AreEqual(c1.NullableGuid, c2.NullableGuid);
  5763. Assert.AreEqual(c1.TimeSpan, c2.TimeSpan);
  5764. Assert.AreEqual(c1.NullableTimeSpan, c2.NullableTimeSpan);
  5765. Assert.AreEqual(c1.Uri, c2.Uri);
  5766. }
  5767. [Test]
  5768. public void UriGuidTimeSpanTestClassValuesTest()
  5769. {
  5770. UriGuidTimeSpanTestClass c1 = new UriGuidTimeSpanTestClass
  5771. {
  5772. Guid = new Guid("1924129C-F7E0-40F3-9607-9939C531395A"),
  5773. NullableGuid = new Guid("9E9F3ADF-E017-4F72-91E0-617EBE85967D"),
  5774. TimeSpan = TimeSpan.FromDays(1),
  5775. NullableTimeSpan = TimeSpan.FromHours(1),
  5776. Uri = new Uri("http://testuri.com")
  5777. };
  5778. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  5779. StringAssert.AreEqual(@"{
  5780. ""Guid"": ""1924129c-f7e0-40f3-9607-9939c531395a"",
  5781. ""NullableGuid"": ""9e9f3adf-e017-4f72-91e0-617ebe85967d"",
  5782. ""TimeSpan"": ""1.00:00:00"",
  5783. ""NullableTimeSpan"": ""01:00:00"",
  5784. ""Uri"": ""http://testuri.com""
  5785. }", json);
  5786. UriGuidTimeSpanTestClass c2 = JsonConvert.DeserializeObject<UriGuidTimeSpanTestClass>(json);
  5787. Assert.AreEqual(c1.Guid, c2.Guid);
  5788. Assert.AreEqual(c1.NullableGuid, c2.NullableGuid);
  5789. Assert.AreEqual(c1.TimeSpan, c2.TimeSpan);
  5790. Assert.AreEqual(c1.NullableTimeSpan, c2.NullableTimeSpan);
  5791. Assert.AreEqual(c1.Uri, c2.Uri);
  5792. }
  5793. [Test]
  5794. public void UsingJsonTextWriter()
  5795. {
  5796. // The property of the object has to be a number for the cast exception to occure
  5797. object o = new { p = 1 };
  5798. var json = JObject.FromObject(o);
  5799. using (var sw = new StringWriter())
  5800. using (var jw = new JsonTextWriter(sw))
  5801. {
  5802. jw.WriteToken(json.CreateReader());
  5803. jw.Flush();
  5804. string result = sw.ToString();
  5805. Assert.AreEqual(@"{""p"":1}", result);
  5806. }
  5807. }
  5808. [Test]
  5809. public void SerializeUriWithQuotes()
  5810. {
  5811. string input = "http://test.com/%22foo+bar%22";
  5812. Uri uri = new Uri(input);
  5813. string json = JsonConvert.SerializeObject(uri);
  5814. Uri output = JsonConvert.DeserializeObject<Uri>(json);
  5815. Assert.AreEqual(uri, output);
  5816. }
  5817. [Test]
  5818. public void SerializeUriWithSlashes()
  5819. {
  5820. string input = @"http://tes/?a=b\\c&d=e\";
  5821. Uri uri = new Uri(input);
  5822. string json = JsonConvert.SerializeObject(uri);
  5823. Uri output = JsonConvert.DeserializeObject<Uri>(json);
  5824. Assert.AreEqual(uri, output);
  5825. }
  5826. [Test]
  5827. public void DeserializeByteArrayWithTypeNameHandling()
  5828. {
  5829. TestObject test = new TestObject("Test", new byte[] { 72, 63, 62, 71, 92, 55 });
  5830. JsonSerializer serializer = new JsonSerializer();
  5831. serializer.TypeNameHandling = TypeNameHandling.All;
  5832. byte[] objectBytes;
  5833. using (MemoryStream stream = new MemoryStream())
  5834. using (JsonWriter jsonWriter = new JsonTextWriter(new StreamWriter(stream)))
  5835. {
  5836. serializer.Serialize(jsonWriter, test);
  5837. jsonWriter.Flush();
  5838. objectBytes = stream.ToArray();
  5839. }
  5840. using (MemoryStream stream = new MemoryStream(objectBytes))
  5841. using (JsonReader jsonReader = new JsonTextReader(new StreamReader(stream)))
  5842. {
  5843. // Get exception here
  5844. TestObject newObject = (TestObject)serializer.Deserialize(jsonReader);
  5845. Assert.AreEqual("Test", newObject.Name);
  5846. CollectionAssert.AreEquivalent(new byte[] { 72, 63, 62, 71, 92, 55 }, newObject.Data);
  5847. }
  5848. }
  5849. public class ReflectionContractResolver : DefaultContractResolver
  5850. {
  5851. protected override IValueProvider CreateMemberValueProvider(MemberInfo member)
  5852. {
  5853. return new ReflectionValueProvider(member);
  5854. }
  5855. }
  5856. [Test]
  5857. public void SerializeStaticDefault()
  5858. {
  5859. DefaultContractResolver contractResolver = new DefaultContractResolver();
  5860. StaticTestClass c = new StaticTestClass
  5861. {
  5862. x = int.MaxValue
  5863. };
  5864. StaticTestClass.y = 2;
  5865. StaticTestClass.z = 3;
  5866. string json = JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings
  5867. {
  5868. ContractResolver = contractResolver
  5869. });
  5870. StringAssert.AreEqual(@"{
  5871. ""x"": 2147483647,
  5872. ""y"": 2,
  5873. ""z"": 3
  5874. }", json);
  5875. StaticTestClass c2 = JsonConvert.DeserializeObject<StaticTestClass>(@"{
  5876. ""x"": -1,
  5877. ""y"": -2,
  5878. ""z"": -3
  5879. }",
  5880. new JsonSerializerSettings
  5881. {
  5882. ContractResolver = contractResolver
  5883. });
  5884. Assert.AreEqual(-1, c2.x);
  5885. Assert.AreEqual(-2, StaticTestClass.y);
  5886. Assert.AreEqual(-3, StaticTestClass.z);
  5887. }
  5888. [Test]
  5889. public void SerializeStaticReflection()
  5890. {
  5891. ReflectionContractResolver contractResolver = new ReflectionContractResolver();
  5892. StaticTestClass c = new StaticTestClass
  5893. {
  5894. x = int.MaxValue
  5895. };
  5896. StaticTestClass.y = 2;
  5897. StaticTestClass.z = 3;
  5898. string json = JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings
  5899. {
  5900. ContractResolver = contractResolver
  5901. });
  5902. StringAssert.AreEqual(@"{
  5903. ""x"": 2147483647,
  5904. ""y"": 2,
  5905. ""z"": 3
  5906. }", json);
  5907. StaticTestClass c2 = JsonConvert.DeserializeObject<StaticTestClass>(@"{
  5908. ""x"": -1,
  5909. ""y"": -2,
  5910. ""z"": -3
  5911. }",
  5912. new JsonSerializerSettings
  5913. {
  5914. ContractResolver = contractResolver
  5915. });
  5916. Assert.AreEqual(-1, c2.x);
  5917. Assert.AreEqual(-2, StaticTestClass.y);
  5918. Assert.AreEqual(-3, StaticTestClass.z);
  5919. }
  5920. #if !(NET20 || DNXCORE50)
  5921. [Test]
  5922. public void DeserializeDecimalsWithCulture()
  5923. {
  5924. CultureInfo initialCulture = Thread.CurrentThread.CurrentCulture;
  5925. try
  5926. {
  5927. CultureInfo testCulture = CultureInfo.CreateSpecificCulture("nb-NO");
  5928. Thread.CurrentThread.CurrentCulture = testCulture;
  5929. Thread.CurrentThread.CurrentUICulture = testCulture;
  5930. string json = @"{ 'Quantity': '1.5', 'OptionalQuantity': '2.2' }";
  5931. DecimalTestClass c = JsonConvert.DeserializeObject<DecimalTestClass>(json);
  5932. Assert.AreEqual(1.5m, c.Quantity);
  5933. Assert.AreEqual(2.2d, c.OptionalQuantity);
  5934. }
  5935. finally
  5936. {
  5937. Thread.CurrentThread.CurrentCulture = initialCulture;
  5938. Thread.CurrentThread.CurrentUICulture = initialCulture;
  5939. }
  5940. }
  5941. #endif
  5942. [Test]
  5943. public void ReadForTypeHackFixDecimal()
  5944. {
  5945. IList<decimal> d1 = new List<decimal> { 1.1m };
  5946. string json = JsonConvert.SerializeObject(d1);
  5947. IList<decimal> d2 = JsonConvert.DeserializeObject<IList<decimal>>(json);
  5948. Assert.AreEqual(d1.Count, d2.Count);
  5949. Assert.AreEqual(d1[0], d2[0]);
  5950. }
  5951. [Test]
  5952. public void ReadForTypeHackFixDateTimeOffset()
  5953. {
  5954. IList<DateTimeOffset?> d1 = new List<DateTimeOffset?> { null };
  5955. string json = JsonConvert.SerializeObject(d1);
  5956. IList<DateTimeOffset?> d2 = JsonConvert.DeserializeObject<IList<DateTimeOffset?>>(json);
  5957. Assert.AreEqual(d1.Count, d2.Count);
  5958. Assert.AreEqual(d1[0], d2[0]);
  5959. }
  5960. [Test]
  5961. public void ReadForTypeHackFixByteArray()
  5962. {
  5963. IList<byte[]> d1 = new List<byte[]> { null };
  5964. string json = JsonConvert.SerializeObject(d1);
  5965. IList<byte[]> d2 = JsonConvert.DeserializeObject<IList<byte[]>>(json);
  5966. Assert.AreEqual(d1.Count, d2.Count);
  5967. Assert.AreEqual(d1[0], d2[0]);
  5968. }
  5969. internal class HasByteArray
  5970. {
  5971. public byte[] EncryptedPassword { get; set; }
  5972. }
  5973. [Test]
  5974. public void DeserializeByteArrayWithTypeName()
  5975. {
  5976. string json = @"{
  5977. ""$type"": ""Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+HasByteArray, Newtonsoft.Json.Tests"",
  5978. ""EncryptedPassword"": {
  5979. ""$type"": ""System.Byte[], mscorlib"",
  5980. ""$value"": ""cGFzc3dvcmQ=""
  5981. }
  5982. }";
  5983. HasByteArray value = JsonConvert.DeserializeObject<HasByteArray>(json, new JsonSerializerSettings
  5984. {
  5985. TypeNameHandling = TypeNameHandling.Objects
  5986. });
  5987. CollectionAssert.AreEquivalent(Convert.FromBase64String("cGFzc3dvcmQ="), value.EncryptedPassword);
  5988. }
  5989. [Test]
  5990. public void DeserializeByteArrayWithTypeName_BadAdditionalContent()
  5991. {
  5992. string json = @"{
  5993. ""$type"": ""Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+HasByteArray, Newtonsoft.Json.Tests"",
  5994. ""EncryptedPassword"": {
  5995. ""$type"": ""System.Byte[], mscorlib"",
  5996. ""$value"": ""cGFzc3dvcmQ="",
  5997. ""$value"": ""cGFzc3dvcmQ=""
  5998. }
  5999. }";
  6000. ExceptionAssert.Throws<JsonReaderException>(() =>
  6001. {
  6002. JsonConvert.DeserializeObject<HasByteArray>(json, new JsonSerializerSettings
  6003. {
  6004. TypeNameHandling = TypeNameHandling.Objects
  6005. });
  6006. }, "Error reading bytes. Unexpected token: PropertyName. Path 'EncryptedPassword.$value', line 6, position 13.");
  6007. }
  6008. [Test]
  6009. public void DeserializeByteArrayWithTypeName_ExtraProperty()
  6010. {
  6011. string json = @"{
  6012. ""$type"": ""Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+HasByteArray, Newtonsoft.Json.Tests"",
  6013. ""EncryptedPassword"": {
  6014. ""$type"": ""System.Byte[], mscorlib"",
  6015. ""$value"": ""cGFzc3dvcmQ=""
  6016. },
  6017. ""Pie"": null
  6018. }";
  6019. HasByteArray value = JsonConvert.DeserializeObject<HasByteArray>(json, new JsonSerializerSettings
  6020. {
  6021. TypeNameHandling = TypeNameHandling.Objects
  6022. });
  6023. Assert.IsNotNull(value.EncryptedPassword);
  6024. CollectionAssert.AreEquivalent(Convert.FromBase64String("cGFzc3dvcmQ="), value.EncryptedPassword);
  6025. }
  6026. [Test]
  6027. public void SerializeInheritanceHierarchyWithDuplicateProperty()
  6028. {
  6029. Bb b = new Bb();
  6030. b.no = true;
  6031. Aa a = b;
  6032. a.no = int.MaxValue;
  6033. string json = JsonConvert.SerializeObject(b);
  6034. Assert.AreEqual(@"{""no"":true}", json);
  6035. Bb b2 = JsonConvert.DeserializeObject<Bb>(json);
  6036. Assert.AreEqual(true, b2.no);
  6037. }
  6038. [Test]
  6039. public void DeserializeNullInt()
  6040. {
  6041. string json = @"[
  6042. 1,
  6043. 2,
  6044. 3,
  6045. null
  6046. ]";
  6047. ExceptionAssert.Throws<JsonSerializationException>(() =>
  6048. {
  6049. List<int> numbers = JsonConvert.DeserializeObject<List<int>>(json);
  6050. }, "Error converting value {null} to type 'System.Int32'. Path '[3]', line 5, position 6.");
  6051. }
  6052. #if !(PORTABLE)
  6053. public class ConvertableIntTestClass
  6054. {
  6055. public ConvertibleInt Integer { get; set; }
  6056. public ConvertibleInt? NullableInteger1 { get; set; }
  6057. public ConvertibleInt? NullableInteger2 { get; set; }
  6058. }
  6059. [Test]
  6060. public void SerializeIConvertible()
  6061. {
  6062. ConvertableIntTestClass c = new ConvertableIntTestClass
  6063. {
  6064. Integer = new ConvertibleInt(1),
  6065. NullableInteger1 = new ConvertibleInt(2),
  6066. NullableInteger2 = null
  6067. };
  6068. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  6069. StringAssert.AreEqual(@"{
  6070. ""Integer"": 1,
  6071. ""NullableInteger1"": 2,
  6072. ""NullableInteger2"": null
  6073. }", json);
  6074. }
  6075. [Test]
  6076. public void DeserializeIConvertible()
  6077. {
  6078. string json = @"{
  6079. ""Integer"": 1,
  6080. ""NullableInteger1"": 2,
  6081. ""NullableInteger2"": null
  6082. }";
  6083. ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<ConvertableIntTestClass>(json), "Error converting value 1 to type 'Newtonsoft.Json.Tests.ConvertibleInt'. Path 'Integer', line 2, position 14.");
  6084. }
  6085. #endif
  6086. [Test]
  6087. public void SerializeNullableWidgetStruct()
  6088. {
  6089. Widget widget = new Widget { Id = new WidgetId { Value = "id" } };
  6090. string json = JsonConvert.SerializeObject(widget);
  6091. Assert.AreEqual(@"{""Id"":{""Value"":""id""}}", json);
  6092. }
  6093. [Test]
  6094. public void DeserializeNullableWidgetStruct()
  6095. {
  6096. string json = @"{""Id"":{""Value"":""id""}}";
  6097. Widget w = JsonConvert.DeserializeObject<Widget>(json);
  6098. Assert.AreEqual(new WidgetId { Value = "id" }, w.Id);
  6099. Assert.AreEqual(new WidgetId { Value = "id" }, w.Id.Value);
  6100. Assert.AreEqual("id", w.Id.Value.Value);
  6101. }
  6102. [Test]
  6103. public void DeserializeBoolInt()
  6104. {
  6105. ExceptionAssert.Throws<JsonReaderException>(() =>
  6106. {
  6107. string json = @"{
  6108. ""PreProperty"": true,
  6109. ""PostProperty"": ""-1""
  6110. }";
  6111. JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
  6112. }, "Unexpected character encountered while parsing value: t. Path 'PreProperty', line 2, position 18.");
  6113. }
  6114. [Test]
  6115. public void DeserializeUnexpectedEndInt()
  6116. {
  6117. ExceptionAssert.Throws<JsonException>(() =>
  6118. {
  6119. string json = @"{
  6120. ""PreProperty"": ";
  6121. JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
  6122. });
  6123. }
  6124. [Test]
  6125. public void DeserializeNullableGuid()
  6126. {
  6127. string json = @"{""Id"":null}";
  6128. var c = JsonConvert.DeserializeObject<NullableGuid>(json);
  6129. Assert.AreEqual(null, c.Id);
  6130. json = @"{""Id"":""d8220a4b-75b1-4b7a-8112-b7bdae956a45""}";
  6131. c = JsonConvert.DeserializeObject<NullableGuid>(json);
  6132. Assert.AreEqual(new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"), c.Id);
  6133. }
  6134. [Test]
  6135. public void SerializeNullableGuidCustomWriterOverridesNullableGuid()
  6136. {
  6137. NullableGuid ng = new NullableGuid {Id = Guid.Empty};
  6138. NullableGuidCountingJsonTextWriter writer = new NullableGuidCountingJsonTextWriter(new StreamWriter(Stream.Null));
  6139. JsonSerializer serializer = JsonSerializer.Create();
  6140. serializer.Serialize(writer, ng);
  6141. Assert.AreEqual(1, writer.NullableGuidCount);
  6142. MemoryTraceWriter traceWriter = new MemoryTraceWriter();
  6143. serializer.TraceWriter = traceWriter;
  6144. serializer.Serialize(writer, ng);
  6145. Assert.AreEqual(2, writer.NullableGuidCount);
  6146. }
  6147. private class NullableGuidCountingJsonTextWriter : JsonTextWriter
  6148. {
  6149. public NullableGuidCountingJsonTextWriter(TextWriter textWriter)
  6150. : base(textWriter)
  6151. {
  6152. }
  6153. public int NullableGuidCount { get; private set; }
  6154. public override void WriteValue(Guid? value)
  6155. {
  6156. base.WriteValue(value);
  6157. ++NullableGuidCount;
  6158. }
  6159. }
  6160. [Test]
  6161. public void DeserializeGuid()
  6162. {
  6163. Item expected = new Item()
  6164. {
  6165. SourceTypeID = new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"),
  6166. BrokerID = new Guid("951663c4-924e-4c86-a57a-7ed737501dbd"),
  6167. Latitude = 33.657145,
  6168. Longitude = -117.766684,
  6169. TimeStamp = new DateTime(2000, 3, 1, 23, 59, 59, DateTimeKind.Utc),
  6170. Payload = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
  6171. };
  6172. string jsonString = JsonConvert.SerializeObject(expected, Formatting.Indented);
  6173. StringAssert.AreEqual(@"{
  6174. ""SourceTypeID"": ""d8220a4b-75b1-4b7a-8112-b7bdae956a45"",
  6175. ""BrokerID"": ""951663c4-924e-4c86-a57a-7ed737501dbd"",
  6176. ""Latitude"": 33.657145,
  6177. ""Longitude"": -117.766684,
  6178. ""TimeStamp"": ""2000-03-01T23:59:59Z"",
  6179. ""Payload"": {
  6180. ""$type"": """ + ReflectionUtils.GetTypeName(typeof(byte[]), 0, DefaultSerializationBinder.Instance) + @""",
  6181. ""$value"": ""AAECAwQFBgcICQ==""
  6182. }
  6183. }", jsonString);
  6184. Item actual = JsonConvert.DeserializeObject<Item>(jsonString);
  6185. Assert.AreEqual(new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"), actual.SourceTypeID);
  6186. Assert.AreEqual(new Guid("951663c4-924e-4c86-a57a-7ed737501dbd"), actual.BrokerID);
  6187. byte[] bytes = (byte[])actual.Payload;
  6188. CollectionAssert.AreEquivalent((new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }).ToList(), bytes.ToList());
  6189. }
  6190. [Test]
  6191. public void DeserializeObjectDictionary()
  6192. {
  6193. var serializer = JsonSerializer.Create(new JsonSerializerSettings());
  6194. var dict = serializer.Deserialize<Dictionary<string, string>>(new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}")));
  6195. Assert.AreEqual("", dict["k1"]);
  6196. Assert.AreEqual("v2", dict["k2"]);
  6197. }
  6198. [Test]
  6199. public void DeserializeNullableEnum()
  6200. {
  6201. string json = JsonConvert.SerializeObject(new WithEnums
  6202. {
  6203. Id = 7,
  6204. NullableEnum = null
  6205. });
  6206. Assert.AreEqual(@"{""Id"":7,""NullableEnum"":null}", json);
  6207. WithEnums e = JsonConvert.DeserializeObject<WithEnums>(json);
  6208. Assert.AreEqual(null, e.NullableEnum);
  6209. json = JsonConvert.SerializeObject(new WithEnums
  6210. {
  6211. Id = 7,
  6212. NullableEnum = MyEnum.Value2
  6213. });
  6214. Assert.AreEqual(@"{""Id"":7,""NullableEnum"":1}", json);
  6215. e = JsonConvert.DeserializeObject<WithEnums>(json);
  6216. Assert.AreEqual(MyEnum.Value2, e.NullableEnum);
  6217. }
  6218. [Test]
  6219. public void NullableStructWithConverter()
  6220. {
  6221. string json = JsonConvert.SerializeObject(new Widget1 { Id = new WidgetId1 { Value = 1234 } });
  6222. Assert.AreEqual(@"{""Id"":""1234""}", json);
  6223. Widget1 w = JsonConvert.DeserializeObject<Widget1>(@"{""Id"":""1234""}");
  6224. Assert.AreEqual(new WidgetId1 { Value = 1234 }, w.Id);
  6225. }
  6226. [Test]
  6227. public void SerializeDictionaryStringStringAndStringObject()
  6228. {
  6229. var serializer = JsonSerializer.Create(new JsonSerializerSettings());
  6230. var dict = serializer.Deserialize<Dictionary<string, string>>(new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}")));
  6231. var reader = new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}"));
  6232. var dict2 = serializer.Deserialize<Dictionary<string, object>>(reader);
  6233. Assert.AreEqual(dict["k1"], dict2["k1"]);
  6234. }
  6235. [Test]
  6236. public void DeserializeEmptyStrings()
  6237. {
  6238. object v = JsonConvert.DeserializeObject<double?>("");
  6239. Assert.IsNull(v);
  6240. v = JsonConvert.DeserializeObject<char?>("");
  6241. Assert.IsNull(v);
  6242. v = JsonConvert.DeserializeObject<int?>("");
  6243. Assert.IsNull(v);
  6244. v = JsonConvert.DeserializeObject<decimal?>("");
  6245. Assert.IsNull(v);
  6246. v = JsonConvert.DeserializeObject<DateTime?>("");
  6247. Assert.IsNull(v);
  6248. v = JsonConvert.DeserializeObject<DateTimeOffset?>("");
  6249. Assert.IsNull(v);
  6250. v = JsonConvert.DeserializeObject<byte[]>("");
  6251. Assert.IsNull(v);
  6252. }
  6253. public class Sdfsdf
  6254. {
  6255. public double Id { get; set; }
  6256. }
  6257. [Test]
  6258. public void DeserializeDoubleFromEmptyString()
  6259. {
  6260. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<double>(""); }, "No JSON content found and type 'System.Double' is not nullable. Path '', line 0, position 0.");
  6261. }
  6262. [Test]
  6263. public void DeserializeEnumFromEmptyString()
  6264. {
  6265. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<StringComparison>(""); }, "No JSON content found and type 'System.StringComparison' is not nullable. Path '', line 0, position 0.");
  6266. }
  6267. [Test]
  6268. public void DeserializeInt32FromEmptyString()
  6269. {
  6270. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<int>(""); }, "No JSON content found and type 'System.Int32' is not nullable. Path '', line 0, position 0.");
  6271. }
  6272. [Test]
  6273. public void DeserializeByteArrayFromEmptyString()
  6274. {
  6275. byte[] b = JsonConvert.DeserializeObject<byte[]>("");
  6276. Assert.IsNull(b);
  6277. }
  6278. [Test]
  6279. public void DeserializeDoubleFromNullString()
  6280. {
  6281. ExceptionAssert.Throws<ArgumentNullException>(
  6282. () => { JsonConvert.DeserializeObject<double>(null); },
  6283. new[]
  6284. {
  6285. "Value cannot be null." + Environment.NewLine + "Parameter name: value",
  6286. "Argument cannot be null." + Environment.NewLine + "Parameter name: value" // mono
  6287. });
  6288. }
  6289. [Test]
  6290. public void DeserializeFromNullString()
  6291. {
  6292. ExceptionAssert.Throws<ArgumentNullException>(
  6293. () => { JsonConvert.DeserializeObject(null); },
  6294. new[]
  6295. {
  6296. "Value cannot be null." + Environment.NewLine + "Parameter name: value",
  6297. "Argument cannot be null." + Environment.NewLine + "Parameter name: value" // mono
  6298. });
  6299. }
  6300. [Test]
  6301. public void DeserializeIsoDatesWithIsoConverter()
  6302. {
  6303. string jsonIsoText =
  6304. @"{""Value"":""2012-02-25T19:55:50.6095676+13:00""}";
  6305. DateTimeWrapper c = JsonConvert.DeserializeObject<DateTimeWrapper>(jsonIsoText, new IsoDateTimeConverter());
  6306. Assert.AreEqual(DateTimeKind.Local, c.Value.Kind);
  6307. }
  6308. #if !NET20
  6309. [Test]
  6310. public void DeserializeUTC()
  6311. {
  6312. DateTimeTestClass c =
  6313. JsonConvert.DeserializeObject<DateTimeTestClass>(
  6314. @"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12Z"",""PostField"":""Post""}",
  6315. new JsonSerializerSettings
  6316. {
  6317. DateTimeZoneHandling = DateTimeZoneHandling.Local
  6318. });
  6319. Assert.AreEqual(new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime(), c.DateTimeField);
  6320. Assert.AreEqual(new DateTimeOffset(2008, 12, 12, 12, 12, 12, 0, TimeSpan.Zero), c.DateTimeOffsetField);
  6321. Assert.AreEqual("Pre", c.PreField);
  6322. Assert.AreEqual("Post", c.PostField);
  6323. DateTimeTestClass c2 =
  6324. JsonConvert.DeserializeObject<DateTimeTestClass>(
  6325. @"{""PreField"":""Pre"",""DateTimeField"":""2008-01-01T01:01:01Z"",""DateTimeOffsetField"":""2008-01-01T01:01:01Z"",""PostField"":""Post""}",
  6326. new JsonSerializerSettings
  6327. {
  6328. DateTimeZoneHandling = DateTimeZoneHandling.Local
  6329. });
  6330. Assert.AreEqual(new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc).ToLocalTime(), c2.DateTimeField);
  6331. Assert.AreEqual(new DateTimeOffset(2008, 1, 1, 1, 1, 1, 0, TimeSpan.Zero), c2.DateTimeOffsetField);
  6332. Assert.AreEqual("Pre", c2.PreField);
  6333. Assert.AreEqual("Post", c2.PostField);
  6334. }
  6335. [Test]
  6336. public void NullableDeserializeUTC()
  6337. {
  6338. NullableDateTimeTestClass c =
  6339. JsonConvert.DeserializeObject<NullableDateTimeTestClass>(
  6340. @"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12Z"",""PostField"":""Post""}",
  6341. new JsonSerializerSettings
  6342. {
  6343. DateTimeZoneHandling = DateTimeZoneHandling.Local
  6344. });
  6345. Assert.AreEqual(new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime(), c.DateTimeField);
  6346. Assert.AreEqual(new DateTimeOffset(2008, 12, 12, 12, 12, 12, 0, TimeSpan.Zero), c.DateTimeOffsetField);
  6347. Assert.AreEqual("Pre", c.PreField);
  6348. Assert.AreEqual("Post", c.PostField);
  6349. NullableDateTimeTestClass c2 =
  6350. JsonConvert.DeserializeObject<NullableDateTimeTestClass>(
  6351. @"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}");
  6352. Assert.AreEqual(null, c2.DateTimeField);
  6353. Assert.AreEqual(null, c2.DateTimeOffsetField);
  6354. Assert.AreEqual("Pre", c2.PreField);
  6355. Assert.AreEqual("Post", c2.PostField);
  6356. }
  6357. [Test]
  6358. public void PrivateConstructor()
  6359. {
  6360. var person = PersonWithPrivateConstructor.CreatePerson();
  6361. person.Name = "John Doe";
  6362. person.Age = 25;
  6363. var serializedPerson = JsonConvert.SerializeObject(person);
  6364. var roundtrippedPerson = JsonConvert.DeserializeObject<PersonWithPrivateConstructor>(serializedPerson);
  6365. Assert.AreEqual(person.Name, roundtrippedPerson.Name);
  6366. }
  6367. #endif
  6368. #if !(DNXCORE50)
  6369. [Test]
  6370. public void MetroBlogPost()
  6371. {
  6372. Product product = new Product()
  6373. {
  6374. Name = "Apple",
  6375. ExpiryDate = new DateTime(2012, 4, 1),
  6376. Price = 3.99M,
  6377. Sizes = new[] { "Small", "Medium", "Large" }
  6378. };
  6379. string json = JsonConvert.SerializeObject(product);
  6380. //{
  6381. // "Name": "Apple",
  6382. // "ExpiryDate": "2012-04-01T00:00:00",
  6383. // "Price": 3.99,
  6384. // "Sizes": [ "Small", "Medium", "Large" ]
  6385. //}
  6386. string metroJson = JsonConvert.SerializeObject(product, new JsonSerializerSettings
  6387. {
  6388. ContractResolver = new MetroPropertyNameResolver(),
  6389. Converters = { new MetroStringConverter() },
  6390. Formatting = Formatting.Indented
  6391. });
  6392. StringAssert.AreEqual(@"{
  6393. "":::NAME:::"": "":::APPLE:::"",
  6394. "":::EXPIRYDATE:::"": ""2012-04-01T00:00:00"",
  6395. "":::PRICE:::"": 3.99,
  6396. "":::SIZES:::"": [
  6397. "":::SMALL:::"",
  6398. "":::MEDIUM:::"",
  6399. "":::LARGE:::""
  6400. ]
  6401. }", metroJson);
  6402. //{
  6403. // ":::NAME:::": ":::APPLE:::",
  6404. // ":::EXPIRYDATE:::": "2012-04-01T00:00:00",
  6405. // ":::PRICE:::": 3.99,
  6406. // ":::SIZES:::": [ ":::SMALL:::", ":::MEDIUM:::", ":::LARGE:::" ]
  6407. //}
  6408. Color[] colors = new[] { Color.Blue, Color.Red, Color.Yellow, Color.Green, Color.Black, Color.Brown };
  6409. string json2 = JsonConvert.SerializeObject(colors, new JsonSerializerSettings
  6410. {
  6411. ContractResolver = new MetroPropertyNameResolver(),
  6412. Converters = { new MetroStringConverter(), new MetroColorConverter() },
  6413. Formatting = Formatting.Indented
  6414. });
  6415. StringAssert.AreEqual(@"[
  6416. "":::GRAY:::"",
  6417. "":::GRAY:::"",
  6418. "":::GRAY:::"",
  6419. "":::GRAY:::"",
  6420. "":::BLACK:::"",
  6421. "":::GRAY:::""
  6422. ]", json2);
  6423. }
  6424. public class MetroColorConverter : JsonConverter
  6425. {
  6426. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  6427. {
  6428. Color color = (Color)value;
  6429. Color fixedColor = (color == Color.White || color == Color.Black) ? color : Color.Gray;
  6430. writer.WriteValue(":::" + fixedColor.ToKnownColor().ToString().ToUpper() + ":::");
  6431. }
  6432. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  6433. {
  6434. return Enum.Parse(typeof(Color), reader.Value.ToString());
  6435. }
  6436. public override bool CanConvert(Type objectType)
  6437. {
  6438. return objectType == typeof(Color);
  6439. }
  6440. }
  6441. #endif
  6442. public class MultipleItemsClass
  6443. {
  6444. public string Name { get; set; }
  6445. }
  6446. [Test]
  6447. public void MultipleItems()
  6448. {
  6449. IList<MultipleItemsClass> values = new List<MultipleItemsClass>();
  6450. JsonTextReader reader = new JsonTextReader(new StringReader(@"{ ""name"": ""bar"" }{ ""name"": ""baz"" }"));
  6451. reader.SupportMultipleContent = true;
  6452. while (true)
  6453. {
  6454. if (!reader.Read())
  6455. {
  6456. break;
  6457. }
  6458. JsonSerializer serializer = new JsonSerializer();
  6459. MultipleItemsClass foo = serializer.Deserialize<MultipleItemsClass>(reader);
  6460. values.Add(foo);
  6461. }
  6462. Assert.AreEqual(2, values.Count);
  6463. Assert.AreEqual("bar", values[0].Name);
  6464. Assert.AreEqual("baz", values[1].Name);
  6465. }
  6466. private class FooBar
  6467. {
  6468. public DateTimeOffset Foo { get; set; }
  6469. }
  6470. #pragma warning disable 618
  6471. [Test]
  6472. public void TokenFromBson()
  6473. {
  6474. MemoryStream ms = new MemoryStream();
  6475. BsonWriter writer = new BsonWriter(ms);
  6476. writer.WriteStartArray();
  6477. writer.WriteValue("2000-01-02T03:04:05+06:00");
  6478. writer.WriteEndArray();
  6479. byte[] data = ms.ToArray();
  6480. BsonReader reader = new BsonReader(new MemoryStream(data))
  6481. {
  6482. ReadRootValueAsArray = true
  6483. };
  6484. JArray a = (JArray)JArray.ReadFrom(reader);
  6485. JValue v = (JValue)a[0];
  6486. Assert.AreEqual(typeof(string), v.Value.GetType());
  6487. StringAssert.AreEqual(@"[
  6488. ""2000-01-02T03:04:05+06:00""
  6489. ]", a.ToString());
  6490. }
  6491. #pragma warning restore 618
  6492. [Test]
  6493. public void ObjectRequiredDeserializeMissing()
  6494. {
  6495. string json = "{}";
  6496. IList<string> errors = new List<string>();
  6497. EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
  6498. {
  6499. errors.Add(e.ErrorContext.Error.Message);
  6500. e.ErrorContext.Handled = true;
  6501. };
  6502. var o = JsonConvert.DeserializeObject<RequiredObject>(json, new JsonSerializerSettings
  6503. {
  6504. Error = error
  6505. });
  6506. Assert.IsNotNull(o);
  6507. Assert.AreEqual(4, errors.Count);
  6508. Assert.IsTrue(errors[0].StartsWith("Required property 'NonAttributeProperty' not found in JSON. Path ''"));
  6509. Assert.IsTrue(errors[1].StartsWith("Required property 'UnsetProperty' not found in JSON. Path ''"));
  6510. Assert.IsTrue(errors[2].StartsWith("Required property 'AllowNullProperty' not found in JSON. Path ''"));
  6511. Assert.IsTrue(errors[3].StartsWith("Required property 'AlwaysProperty' not found in JSON. Path ''"));
  6512. }
  6513. [Test]
  6514. public void ObjectRequiredDeserializeNull()
  6515. {
  6516. string json = "{'NonAttributeProperty':null,'UnsetProperty':null,'AllowNullProperty':null,'AlwaysProperty':null}";
  6517. IList<string> errors = new List<string>();
  6518. EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
  6519. {
  6520. errors.Add(e.ErrorContext.Error.Message);
  6521. e.ErrorContext.Handled = true;
  6522. };
  6523. var o = JsonConvert.DeserializeObject<RequiredObject>(json, new JsonSerializerSettings
  6524. {
  6525. Error = error
  6526. });
  6527. Assert.IsNotNull(o);
  6528. Assert.AreEqual(3, errors.Count);
  6529. Assert.IsTrue(errors[0].StartsWith("Required property 'NonAttributeProperty' expects a value but got null. Path ''"));
  6530. Assert.IsTrue(errors[1].StartsWith("Required property 'UnsetProperty' expects a value but got null. Path ''"));
  6531. Assert.IsTrue(errors[2].StartsWith("Required property 'AlwaysProperty' expects a value but got null. Path ''"));
  6532. }
  6533. [Test]
  6534. public void ObjectRequiredSerialize()
  6535. {
  6536. IList<string> errors = new List<string>();
  6537. EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
  6538. {
  6539. errors.Add(e.ErrorContext.Error.Message);
  6540. e.ErrorContext.Handled = true;
  6541. };
  6542. string json = JsonConvert.SerializeObject(new RequiredObject(), new JsonSerializerSettings
  6543. {
  6544. Error = error,
  6545. Formatting = Formatting.Indented
  6546. });
  6547. StringAssert.AreEqual(@"{
  6548. ""DefaultProperty"": null,
  6549. ""AllowNullProperty"": null
  6550. }", json);
  6551. Assert.AreEqual(3, errors.Count);
  6552. Assert.AreEqual("Cannot write a null value for property 'NonAttributeProperty'. Property requires a value. Path ''.", errors[0]);
  6553. Assert.AreEqual("Cannot write a null value for property 'UnsetProperty'. Property requires a value. Path ''.", errors[1]);
  6554. Assert.AreEqual("Cannot write a null value for property 'AlwaysProperty'. Property requires a value. Path ''.", errors[2]);
  6555. }
  6556. [Test]
  6557. public void DeserializeCollectionItemConverter()
  6558. {
  6559. PropertyItemConverter c = new PropertyItemConverter
  6560. {
  6561. Data =
  6562. new[]
  6563. {
  6564. "one",
  6565. "two",
  6566. "three"
  6567. }
  6568. };
  6569. var c2 = JsonConvert.DeserializeObject<PropertyItemConverter>("{'Data':['::ONE::','::TWO::']}");
  6570. Assert.IsNotNull(c2);
  6571. Assert.AreEqual(2, c2.Data.Count);
  6572. Assert.AreEqual("one", c2.Data[0]);
  6573. Assert.AreEqual("two", c2.Data[1]);
  6574. }
  6575. [Test]
  6576. public void SerializeCollectionItemConverter()
  6577. {
  6578. PropertyItemConverter c = new PropertyItemConverter
  6579. {
  6580. Data = new[]
  6581. {
  6582. "one",
  6583. "two",
  6584. "three"
  6585. }
  6586. };
  6587. string json = JsonConvert.SerializeObject(c);
  6588. Assert.AreEqual(@"{""Data"":["":::ONE:::"","":::TWO:::"","":::THREE:::""]}", json);
  6589. }
  6590. #if !NET20
  6591. [Test]
  6592. public void DateTimeDictionaryKey_DateTimeOffset_Iso()
  6593. {
  6594. IDictionary<DateTimeOffset, int> dic1 = new Dictionary<DateTimeOffset, int>
  6595. {
  6596. { new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero), 1 },
  6597. { new DateTimeOffset(2013, 12, 12, 12, 12, 12, TimeSpan.Zero), 2 }
  6598. };
  6599. string json = JsonConvert.SerializeObject(dic1, Formatting.Indented);
  6600. StringAssert.AreEqual(@"{
  6601. ""2000-12-12T12:12:12+00:00"": 1,
  6602. ""2013-12-12T12:12:12+00:00"": 2
  6603. }", json);
  6604. IDictionary<DateTimeOffset, int> dic2 = JsonConvert.DeserializeObject<IDictionary<DateTimeOffset, int>>(json);
  6605. Assert.AreEqual(2, dic2.Count);
  6606. Assert.AreEqual(1, dic2[new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero)]);
  6607. Assert.AreEqual(2, dic2[new DateTimeOffset(2013, 12, 12, 12, 12, 12, TimeSpan.Zero)]);
  6608. }
  6609. [Test]
  6610. public void DateTimeDictionaryKey_DateTimeOffset_MS()
  6611. {
  6612. IDictionary<DateTimeOffset?, int> dic1 = new Dictionary<DateTimeOffset?, int>
  6613. {
  6614. { new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero), 1 },
  6615. { new DateTimeOffset(2013, 12, 12, 12, 12, 12, TimeSpan.Zero), 2 }
  6616. };
  6617. string json = JsonConvert.SerializeObject(dic1, Formatting.Indented, new JsonSerializerSettings
  6618. {
  6619. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  6620. });
  6621. StringAssert.AreEqual(@"{
  6622. ""\/Date(976623132000+0000)\/"": 1,
  6623. ""\/Date(1386850332000+0000)\/"": 2
  6624. }", json);
  6625. IDictionary<DateTimeOffset?, int> dic2 = JsonConvert.DeserializeObject<IDictionary<DateTimeOffset?, int>>(json);
  6626. Assert.AreEqual(2, dic2.Count);
  6627. Assert.AreEqual(1, dic2[new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero)]);
  6628. Assert.AreEqual(2, dic2[new DateTimeOffset(2013, 12, 12, 12, 12, 12, TimeSpan.Zero)]);
  6629. }
  6630. #endif
  6631. [Test]
  6632. public void DateTimeDictionaryKey_DateTime_Iso()
  6633. {
  6634. IDictionary<DateTime, int> dic1 = new Dictionary<DateTime, int>
  6635. {
  6636. { new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc), 1 },
  6637. { new DateTime(2013, 12, 12, 12, 12, 12, DateTimeKind.Utc), 2 }
  6638. };
  6639. string json = JsonConvert.SerializeObject(dic1, Formatting.Indented);
  6640. StringAssert.AreEqual(@"{
  6641. ""2000-12-12T12:12:12Z"": 1,
  6642. ""2013-12-12T12:12:12Z"": 2
  6643. }", json);
  6644. IDictionary<DateTime, int> dic2 = JsonConvert.DeserializeObject<IDictionary<DateTime, int>>(json);
  6645. Assert.AreEqual(2, dic2.Count);
  6646. Assert.AreEqual(1, dic2[new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)]);
  6647. Assert.AreEqual(2, dic2[new DateTime(2013, 12, 12, 12, 12, 12, DateTimeKind.Utc)]);
  6648. }
  6649. [Test]
  6650. public void DateTimeDictionaryKey_DateTime_Iso_Local()
  6651. {
  6652. IDictionary<DateTime, int> dic1 = new Dictionary<DateTime, int>
  6653. {
  6654. { new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc), 1 },
  6655. { new DateTime(2013, 12, 12, 12, 12, 12, DateTimeKind.Utc), 2 }
  6656. };
  6657. string json = JsonConvert.SerializeObject(dic1, Formatting.Indented, new JsonSerializerSettings
  6658. {
  6659. DateTimeZoneHandling = DateTimeZoneHandling.Local
  6660. });
  6661. JObject o = JObject.Parse(json);
  6662. Assert.IsFalse(o.Properties().ElementAt(0).Name.Contains("Z"));
  6663. Assert.IsFalse(o.Properties().ElementAt(1).Name.Contains("Z"));
  6664. IDictionary<DateTime, int> dic2 = JsonConvert.DeserializeObject<IDictionary<DateTime, int>>(json, new JsonSerializerSettings
  6665. {
  6666. DateTimeZoneHandling = DateTimeZoneHandling.Utc
  6667. });
  6668. Assert.AreEqual(2, dic2.Count);
  6669. Assert.AreEqual(1, dic2[new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)]);
  6670. Assert.AreEqual(2, dic2[new DateTime(2013, 12, 12, 12, 12, 12, DateTimeKind.Utc)]);
  6671. }
  6672. [Test]
  6673. public void DateTimeDictionaryKey_DateTime_MS()
  6674. {
  6675. IDictionary<DateTime, int> dic1 = new Dictionary<DateTime, int>
  6676. {
  6677. { new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc), 1 },
  6678. { new DateTime(2013, 12, 12, 12, 12, 12, DateTimeKind.Utc), 2 }
  6679. };
  6680. string json = JsonConvert.SerializeObject(dic1, Formatting.Indented, new JsonSerializerSettings
  6681. {
  6682. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  6683. });
  6684. StringAssert.AreEqual(@"{
  6685. ""\/Date(976623132000)\/"": 1,
  6686. ""\/Date(1386850332000)\/"": 2
  6687. }", json);
  6688. IDictionary<DateTime, int> dic2 = JsonConvert.DeserializeObject<IDictionary<DateTime, int>>(json);
  6689. Assert.AreEqual(2, dic2.Count);
  6690. Assert.AreEqual(1, dic2[new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)]);
  6691. Assert.AreEqual(2, dic2[new DateTime(2013, 12, 12, 12, 12, 12, DateTimeKind.Utc)]);
  6692. }
  6693. [Test]
  6694. public void DeserializeEmptyJsonString()
  6695. {
  6696. string s = (string)new JsonSerializer().Deserialize(new JsonTextReader(new StringReader("''")));
  6697. Assert.AreEqual("", s);
  6698. }
  6699. #if !(PORTABLE || DNXCORE50 || PORTABLE40)
  6700. [Test]
  6701. public void SerializeAndDeserializeWithAttributes()
  6702. {
  6703. var testObj = new PersonSerializable() { Name = "John Doe", Age = 28 };
  6704. var objDeserialized = SerializeAndDeserialize<PersonSerializable>(testObj);
  6705. Assert.AreEqual(testObj.Name, objDeserialized.Name);
  6706. Assert.AreEqual(0, objDeserialized.Age);
  6707. }
  6708. private T SerializeAndDeserialize<T>(T obj)
  6709. where T : class
  6710. {
  6711. var json = Serialize(obj);
  6712. return Deserialize<T>(json);
  6713. }
  6714. private string Serialize<T>(T obj)
  6715. where T : class
  6716. {
  6717. var stringWriter = new StringWriter();
  6718. var serializer = new JsonSerializer();
  6719. serializer.ContractResolver = new DefaultContractResolver
  6720. {
  6721. IgnoreSerializableAttribute = false
  6722. };
  6723. serializer.Serialize(stringWriter, obj);
  6724. return stringWriter.ToString();
  6725. }
  6726. private T Deserialize<T>(string json)
  6727. where T : class
  6728. {
  6729. var jsonReader = new JsonTextReader(new StringReader(json));
  6730. var serializer = new JsonSerializer();
  6731. serializer.ContractResolver = new DefaultContractResolver
  6732. {
  6733. IgnoreSerializableAttribute = false
  6734. };
  6735. return serializer.Deserialize(jsonReader, typeof(T)) as T;
  6736. }
  6737. #endif
  6738. [Test]
  6739. public void PropertyItemConverter()
  6740. {
  6741. Event1 e = new Event1
  6742. {
  6743. EventName = "Blackadder III",
  6744. Venue = "Gryphon Theatre",
  6745. Performances = new List<DateTime>
  6746. {
  6747. DateTimeUtils.ConvertJavaScriptTicksToDateTime(1336458600000),
  6748. DateTimeUtils.ConvertJavaScriptTicksToDateTime(1336545000000),
  6749. DateTimeUtils.ConvertJavaScriptTicksToDateTime(1336636800000)
  6750. }
  6751. };
  6752. string json = JsonConvert.SerializeObject(e, Formatting.Indented);
  6753. //{
  6754. // "EventName": "Blackadder III",
  6755. // "Venue": "Gryphon Theatre",
  6756. // "Performances": [
  6757. // new Date(1336458600000),
  6758. // new Date(1336545000000),
  6759. // new Date(1336636800000)
  6760. // ]
  6761. //}
  6762. StringAssert.AreEqual(@"{
  6763. ""EventName"": ""Blackadder III"",
  6764. ""Venue"": ""Gryphon Theatre"",
  6765. ""Performances"": [
  6766. new Date(
  6767. 1336458600000
  6768. ),
  6769. new Date(
  6770. 1336545000000
  6771. ),
  6772. new Date(
  6773. 1336636800000
  6774. )
  6775. ]
  6776. }", json);
  6777. }
  6778. #if !(NET20 || NET35)
  6779. public class IgnoreDataMemberTestClass
  6780. {
  6781. [IgnoreDataMember]
  6782. public int Ignored { get; set; }
  6783. }
  6784. [Test]
  6785. public void IgnoreDataMemberTest()
  6786. {
  6787. string json = JsonConvert.SerializeObject(new IgnoreDataMemberTestClass() { Ignored = int.MaxValue }, Formatting.Indented);
  6788. Assert.AreEqual(@"{}", json);
  6789. }
  6790. #endif
  6791. #if !(NET20 || NET35)
  6792. [Test]
  6793. public void SerializeDataContractSerializationAttributes()
  6794. {
  6795. DataContractSerializationAttributesClass dataContract = new DataContractSerializationAttributesClass
  6796. {
  6797. NoAttribute = "Value!",
  6798. IgnoreDataMemberAttribute = "Value!",
  6799. DataMemberAttribute = "Value!",
  6800. IgnoreDataMemberAndDataMemberAttribute = "Value!"
  6801. };
  6802. //MemoryStream ms = new MemoryStream();
  6803. //DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DataContractSerializationAttributesClass));
  6804. //serializer.WriteObject(ms, dataContract);
  6805. //Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
  6806. string json = JsonConvert.SerializeObject(dataContract, Formatting.Indented);
  6807. StringAssert.AreEqual(@"{
  6808. ""DataMemberAttribute"": ""Value!"",
  6809. ""IgnoreDataMemberAndDataMemberAttribute"": ""Value!""
  6810. }", json);
  6811. PocoDataContractSerializationAttributesClass poco = new PocoDataContractSerializationAttributesClass
  6812. {
  6813. NoAttribute = "Value!",
  6814. IgnoreDataMemberAttribute = "Value!",
  6815. DataMemberAttribute = "Value!",
  6816. IgnoreDataMemberAndDataMemberAttribute = "Value!"
  6817. };
  6818. json = JsonConvert.SerializeObject(poco, Formatting.Indented);
  6819. StringAssert.AreEqual(@"{
  6820. ""NoAttribute"": ""Value!"",
  6821. ""DataMemberAttribute"": ""Value!""
  6822. }", json);
  6823. }
  6824. #endif
  6825. [Test]
  6826. public void CheckAdditionalContent()
  6827. {
  6828. string json = "{one:1}{}";
  6829. JsonSerializerSettings settings = new JsonSerializerSettings();
  6830. JsonSerializer s = JsonSerializer.Create(settings);
  6831. IDictionary<string, int> o = s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json)));
  6832. Assert.IsNotNull(o);
  6833. Assert.AreEqual(1, o["one"]);
  6834. settings.CheckAdditionalContent = true;
  6835. s = JsonSerializer.Create(settings);
  6836. ExceptionAssert.Throws<JsonReaderException>(() => { s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json))); }, "Additional text encountered after finished reading JSON content: {. Path '', line 1, position 7.");
  6837. }
  6838. [Test]
  6839. public void CheckAdditionalContentJustComment()
  6840. {
  6841. string json = "{one:1} // This is just a comment";
  6842. JsonSerializerSettings settings = new JsonSerializerSettings {CheckAdditionalContent = true};
  6843. JsonSerializer s = JsonSerializer.Create(settings);
  6844. IDictionary<string, int> o = s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json)));
  6845. Assert.IsNotNull(o);
  6846. Assert.AreEqual(1, o["one"]);
  6847. }
  6848. [Test]
  6849. public void CheckAdditionalContentJustMultipleComments()
  6850. {
  6851. string json = @"{one:1} // This is just a comment
  6852. /* This is just a comment
  6853. over multiple
  6854. lines.*/
  6855. // This is just another comment.";
  6856. JsonSerializerSettings settings = new JsonSerializerSettings {CheckAdditionalContent = true};
  6857. JsonSerializer s = JsonSerializer.Create(settings);
  6858. IDictionary<string, int> o = s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json)));
  6859. Assert.IsNotNull(o);
  6860. Assert.AreEqual(1, o["one"]);
  6861. }
  6862. [Test]
  6863. public void CheckAdditionalContentCommentsThenAnotherObject()
  6864. {
  6865. string json = @"{one:1} // This is just a comment
  6866. /* This is just a comment
  6867. over multiple
  6868. lines.*/
  6869. // This is just another comment. But here comes an empty object.
  6870. {}";
  6871. JsonSerializerSettings settings = new JsonSerializerSettings { CheckAdditionalContent = true };
  6872. JsonSerializer s = JsonSerializer.Create(settings);
  6873. ExceptionAssert.Throws<JsonReaderException>(() => { s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json))); }, "Additional text encountered after finished reading JSON content: {. Path '', line 7, position 0.");
  6874. }
  6875. #if !(PORTABLE || DNXCORE50 || PORTABLE40)
  6876. [Test]
  6877. public void DeserializeException()
  6878. {
  6879. string json = @"{ ""ClassName"" : ""System.InvalidOperationException"",
  6880. ""Data"" : null,
  6881. ""ExceptionMethod"" : ""8\nLogin\nAppBiz, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null\nMyApp.LoginBiz\nMyApp.User Login()"",
  6882. ""HResult"" : -2146233079,
  6883. ""HelpURL"" : null,
  6884. ""InnerException"" : { ""ClassName"" : ""System.Exception"",
  6885. ""Data"" : null,
  6886. ""ExceptionMethod"" : null,
  6887. ""HResult"" : -2146233088,
  6888. ""HelpURL"" : null,
  6889. ""InnerException"" : null,
  6890. ""Message"" : ""Inner exception..."",
  6891. ""RemoteStackIndex"" : 0,
  6892. ""RemoteStackTraceString"" : null,
  6893. ""Source"" : null,
  6894. ""StackTraceString"" : null,
  6895. ""WatsonBuckets"" : null
  6896. },
  6897. ""Message"" : ""Outter exception..."",
  6898. ""RemoteStackIndex"" : 0,
  6899. ""RemoteStackTraceString"" : null,
  6900. ""Source"" : ""AppBiz"",
  6901. ""StackTraceString"" : "" at MyApp.LoginBiz.Login() in C:\\MyApp\\LoginBiz.cs:line 44\r\n at MyApp.LoginSvc.Login() in C:\\MyApp\\LoginSvc.cs:line 71\r\n at SyncInvokeLogin(Object , Object[] , Object[] )\r\n at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)\r\n at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)"",
  6902. ""WatsonBuckets"" : null
  6903. }";
  6904. InvalidOperationException exception = JsonConvert.DeserializeObject<InvalidOperationException>(json);
  6905. Assert.IsNotNull(exception);
  6906. CustomAssert.IsInstanceOfType(typeof(InvalidOperationException), exception);
  6907. Assert.AreEqual("Outter exception...", exception.Message);
  6908. }
  6909. #endif
  6910. [Test]
  6911. public void AdditionalContentAfterFinish()
  6912. {
  6913. ExceptionAssert.Throws<JsonException>(() =>
  6914. {
  6915. string json = "[{},1]";
  6916. JsonSerializer serializer = new JsonSerializer();
  6917. serializer.CheckAdditionalContent = true;
  6918. var reader = new JsonTextReader(new StringReader(json));
  6919. reader.Read();
  6920. reader.Read();
  6921. serializer.Deserialize(reader, typeof(MyType));
  6922. }, "Additional text found in JSON string after finishing deserializing object. Path '[1]', line 1, position 5.");
  6923. }
  6924. [Test]
  6925. public void AdditionalContentAfterFinishCheckNotRequested()
  6926. {
  6927. string json = @"{ ""MyProperty"":{""Key"":""Value""}} A bunch of junk at the end of the json";
  6928. JsonSerializer serializer = new JsonSerializer();
  6929. var reader = new JsonTextReader(new StringReader(json));
  6930. MyType mt = (MyType)serializer.Deserialize(reader, typeof(MyType));
  6931. Assert.AreEqual(1, mt.MyProperty.Count);
  6932. }
  6933. [Test]
  6934. public void AdditionalContentAfterCommentsCheckNotRequested()
  6935. {
  6936. string json = @"{ ""MyProperty"":{""Key"":""Value""}} /*this is a comment */
  6937. // this is also a comment
  6938. This is just junk, though.";
  6939. JsonSerializer serializer = new JsonSerializer();
  6940. var reader = new JsonTextReader(new StringReader(json));
  6941. MyType mt = (MyType)serializer.Deserialize(reader, typeof(MyType));
  6942. Assert.AreEqual(1, mt.MyProperty.Count);
  6943. }
  6944. [Test]
  6945. public void AdditionalContentAfterComments()
  6946. {
  6947. string json = @"[{ ""MyProperty"":{""Key"":""Value""}} /*this is a comment */
  6948. // this is also a comment
  6949. ,{}";
  6950. JsonSerializer serializer = new JsonSerializer();
  6951. serializer.CheckAdditionalContent = true;
  6952. var reader = new JsonTextReader(new StringReader(json));
  6953. reader.Read();
  6954. reader.Read();
  6955. ExceptionAssert.Throws<JsonSerializationException>(() => serializer.Deserialize(reader, typeof(MyType)),
  6956. "Additional text found in JSON string after finishing deserializing object. Path '[1]', line 3, position 2.");
  6957. }
  6958. [Test]
  6959. public void DeserializeRelativeUri()
  6960. {
  6961. IList<Uri> uris = JsonConvert.DeserializeObject<IList<Uri>>(@"[""http://localhost/path?query#hash""]");
  6962. Assert.AreEqual(1, uris.Count);
  6963. Assert.AreEqual(new Uri("http://localhost/path?query#hash"), uris[0]);
  6964. Uri uri = JsonConvert.DeserializeObject<Uri>(@"""http://localhost/path?query#hash""");
  6965. Assert.IsNotNull(uri);
  6966. Uri i1 = new Uri("http://localhost/path?query#hash", UriKind.RelativeOrAbsolute);
  6967. Uri i2 = new Uri("http://localhost/path?query#hash");
  6968. Assert.AreEqual(i1, i2);
  6969. uri = JsonConvert.DeserializeObject<Uri>(@"""/path?query#hash""");
  6970. Assert.IsNotNull(uri);
  6971. Assert.AreEqual(new Uri("/path?query#hash", UriKind.RelativeOrAbsolute), uri);
  6972. }
  6973. public class MyConverter : JsonConverter
  6974. {
  6975. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  6976. {
  6977. writer.WriteValue("X");
  6978. }
  6979. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  6980. {
  6981. return "X";
  6982. }
  6983. public override bool CanConvert(Type objectType)
  6984. {
  6985. return true;
  6986. }
  6987. }
  6988. public class MyType
  6989. {
  6990. [JsonProperty(ItemConverterType = typeof(MyConverter))]
  6991. public Dictionary<string, object> MyProperty { get; set; }
  6992. }
  6993. [Test]
  6994. public void DeserializeDictionaryItemConverter()
  6995. {
  6996. var actual = JsonConvert.DeserializeObject<MyType>(@"{ ""MyProperty"":{""Key"":""Y""}}");
  6997. Assert.AreEqual("X", actual.MyProperty["Key"]);
  6998. }
  6999. [Test]
  7000. public void DeserializeCaseInsensitiveKeyValuePairConverter()
  7001. {
  7002. KeyValuePair<int, string> result =
  7003. JsonConvert.DeserializeObject<KeyValuePair<int, string>>(
  7004. "{key: 123, \"VALUE\": \"test value\"}"
  7005. );
  7006. Assert.AreEqual(123, result.Key);
  7007. Assert.AreEqual("test value", result.Value);
  7008. }
  7009. [Test]
  7010. public void SerializeKeyValuePairConverterWithCamelCase()
  7011. {
  7012. string json =
  7013. JsonConvert.SerializeObject(new KeyValuePair<int, string>(123, "test value"), Formatting.Indented, new JsonSerializerSettings
  7014. {
  7015. ContractResolver = new CamelCasePropertyNamesContractResolver()
  7016. });
  7017. StringAssert.AreEqual(@"{
  7018. ""key"": 123,
  7019. ""value"": ""test value""
  7020. }", json);
  7021. }
  7022. [JsonObject(MemberSerialization.Fields)]
  7023. public class MyTuple<T1>
  7024. {
  7025. private readonly T1 m_Item1;
  7026. public MyTuple(T1 item1)
  7027. {
  7028. m_Item1 = item1;
  7029. }
  7030. public T1 Item1
  7031. {
  7032. get { return m_Item1; }
  7033. }
  7034. }
  7035. [JsonObject(MemberSerialization.Fields)]
  7036. public class MyTuplePartial<T1>
  7037. {
  7038. private readonly T1 m_Item1;
  7039. public MyTuplePartial(T1 item1)
  7040. {
  7041. m_Item1 = item1;
  7042. }
  7043. public T1 Item1
  7044. {
  7045. get { return m_Item1; }
  7046. }
  7047. }
  7048. [Test]
  7049. public void SerializeFloatingPointHandling()
  7050. {
  7051. string json;
  7052. IList<double> d = new List<double> { 1.1, double.NaN, double.PositiveInfinity };
  7053. json = JsonConvert.SerializeObject(d);
  7054. // [1.1,"NaN","Infinity"]
  7055. json = JsonConvert.SerializeObject(d, new JsonSerializerSettings { FloatFormatHandling = FloatFormatHandling.Symbol });
  7056. // [1.1,NaN,Infinity]
  7057. json = JsonConvert.SerializeObject(d, new JsonSerializerSettings { FloatFormatHandling = FloatFormatHandling.DefaultValue });
  7058. // [1.1,0.0,0.0]
  7059. Assert.AreEqual("[1.1,0.0,0.0]", json);
  7060. }
  7061. #if !(NET20 || NET35 || NET40 || PORTABLE40)
  7062. #if !PORTABLE || NETSTANDARD1_1
  7063. [Test]
  7064. public void DeserializeReadOnlyListWithBigInteger()
  7065. {
  7066. string json = @"[
  7067. 9000000000000000000000000000000000000000000000000
  7068. ]";
  7069. var l = JsonConvert.DeserializeObject<IReadOnlyList<BigInteger>>(json);
  7070. BigInteger nineQuindecillion = l[0];
  7071. // 9000000000000000000000000000000000000000000000000
  7072. Assert.AreEqual(BigInteger.Parse("9000000000000000000000000000000000000000000000000"), nineQuindecillion);
  7073. }
  7074. #endif
  7075. [Test]
  7076. public void DeserializeReadOnlyListWithInt()
  7077. {
  7078. string json = @"[
  7079. 900
  7080. ]";
  7081. var l = JsonConvert.DeserializeObject<IReadOnlyList<int>>(json);
  7082. int i = l[0];
  7083. // 900
  7084. Assert.AreEqual(900, i);
  7085. }
  7086. [Test]
  7087. public void DeserializeReadOnlyListWithNullableType()
  7088. {
  7089. string json = @"[
  7090. 1,
  7091. null
  7092. ]";
  7093. var l = JsonConvert.DeserializeObject<IReadOnlyList<int?>>(json);
  7094. Assert.AreEqual(1, l[0]);
  7095. Assert.AreEqual(null, l[1]);
  7096. }
  7097. #endif
  7098. [Test]
  7099. public void SerializeCustomTupleWithSerializableAttribute()
  7100. {
  7101. var tuple = new MyTuple<int>(500);
  7102. var json = JsonConvert.SerializeObject(tuple);
  7103. Assert.AreEqual(@"{""m_Item1"":500}", json);
  7104. MyTuple<int> obj = null;
  7105. Action doStuff = () => { obj = JsonConvert.DeserializeObject<MyTuple<int>>(json); };
  7106. #if !(PORTABLE || DNXCORE50 || PORTABLE40)
  7107. doStuff();
  7108. Assert.AreEqual(500, obj.Item1);
  7109. #else
  7110. ExceptionAssert.Throws<JsonSerializationException>(
  7111. doStuff,
  7112. "Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+MyTuple`1[System.Int32]. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'm_Item1', line 1, position 11.");
  7113. #endif
  7114. }
  7115. #if DEBUG
  7116. [Test]
  7117. public void SerializeCustomTupleWithSerializableAttributeInPartialTrust()
  7118. {
  7119. try
  7120. {
  7121. JsonTypeReflector.SetFullyTrusted(false);
  7122. var tuple = new MyTuplePartial<int>(500);
  7123. var json = JsonConvert.SerializeObject(tuple);
  7124. Assert.AreEqual(@"{""m_Item1"":500}", json);
  7125. ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<MyTuplePartial<int>>(json), "Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+MyTuplePartial`1[System.Int32]. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'm_Item1', line 1, position 11.");
  7126. }
  7127. finally
  7128. {
  7129. JsonTypeReflector.SetFullyTrusted(true);
  7130. }
  7131. }
  7132. #endif
  7133. #if !(PORTABLE || NET35 || NET20 || PORTABLE40 || DNXCORE50)
  7134. [Test]
  7135. public void SerializeTupleWithSerializableAttribute()
  7136. {
  7137. var tuple = Tuple.Create(500);
  7138. var json = JsonConvert.SerializeObject(tuple, new JsonSerializerSettings
  7139. {
  7140. ContractResolver = new SerializableContractResolver()
  7141. });
  7142. Assert.AreEqual(@"{""m_Item1"":500}", json);
  7143. var obj = JsonConvert.DeserializeObject<Tuple<int>>(json, new JsonSerializerSettings
  7144. {
  7145. ContractResolver = new SerializableContractResolver()
  7146. });
  7147. Assert.AreEqual(500, obj.Item1);
  7148. }
  7149. public class SerializableContractResolver : DefaultContractResolver
  7150. {
  7151. public SerializableContractResolver()
  7152. {
  7153. IgnoreSerializableAttribute = false;
  7154. }
  7155. }
  7156. #endif
  7157. #if !NET20
  7158. [Test]
  7159. public void RoundtripOfDateTimeOffset()
  7160. {
  7161. var content = @"{""startDateTime"":""2012-07-19T14:30:00+09:30""}";
  7162. var jsonSerializerSettings = new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateParseHandling = DateParseHandling.DateTimeOffset, DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind };
  7163. var obj = (JObject)JsonConvert.DeserializeObject(content, jsonSerializerSettings);
  7164. var dateTimeOffset = (DateTimeOffset)((JValue)obj["startDateTime"]).Value;
  7165. Assert.AreEqual(TimeSpan.FromHours(9.5), dateTimeOffset.Offset);
  7166. Assert.AreEqual("07/19/2012 14:30:00 +09:30", dateTimeOffset.ToString(CultureInfo.InvariantCulture));
  7167. }
  7168. public class NullableFloats
  7169. {
  7170. public object Object { get; set; }
  7171. public float Float { get; set; }
  7172. public double Double { get; set; }
  7173. public float? NullableFloat { get; set; }
  7174. public double? NullableDouble { get; set; }
  7175. public object ObjectNull { get; set; }
  7176. }
  7177. [Test]
  7178. public void NullableFloatingPoint()
  7179. {
  7180. NullableFloats floats = new NullableFloats
  7181. {
  7182. Object = double.NaN,
  7183. ObjectNull = null,
  7184. Float = float.NaN,
  7185. NullableDouble = double.NaN,
  7186. NullableFloat = null
  7187. };
  7188. string json = JsonConvert.SerializeObject(floats, Formatting.Indented, new JsonSerializerSettings
  7189. {
  7190. FloatFormatHandling = FloatFormatHandling.DefaultValue
  7191. });
  7192. StringAssert.AreEqual(@"{
  7193. ""Object"": 0.0,
  7194. ""Float"": 0.0,
  7195. ""Double"": 0.0,
  7196. ""NullableFloat"": null,
  7197. ""NullableDouble"": null,
  7198. ""ObjectNull"": null
  7199. }", json);
  7200. }
  7201. [Test]
  7202. public void DateFormatString()
  7203. {
  7204. CultureInfo culture = new CultureInfo("en-NZ");
  7205. culture.DateTimeFormat.AMDesignator = "a.m.";
  7206. culture.DateTimeFormat.PMDesignator = "p.m.";
  7207. IList<object> dates = new List<object>
  7208. {
  7209. new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc),
  7210. new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1))
  7211. };
  7212. string json = JsonConvert.SerializeObject(dates, Formatting.Indented, new JsonSerializerSettings
  7213. {
  7214. DateFormatString = "yyyy tt",
  7215. Culture = culture
  7216. });
  7217. StringAssert.AreEqual(@"[
  7218. ""2000 p.m."",
  7219. ""2000 p.m.""
  7220. ]", json);
  7221. }
  7222. [Test]
  7223. public void DateFormatStringForInternetExplorer()
  7224. {
  7225. IList<object> dates = new List<object>
  7226. {
  7227. new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc),
  7228. new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1))
  7229. };
  7230. string json = JsonConvert.SerializeObject(dates, Formatting.Indented, new JsonSerializerSettings
  7231. {
  7232. DateFormatString = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK"
  7233. });
  7234. StringAssert.AreEqual(@"[
  7235. ""2000-12-12T12:12:12.000Z"",
  7236. ""2000-12-12T12:12:12.000+01:00""
  7237. ]", json);
  7238. }
  7239. [Test]
  7240. public void JsonSerializerDateFormatString()
  7241. {
  7242. CultureInfo culture = new CultureInfo("en-NZ");
  7243. culture.DateTimeFormat.AMDesignator = "a.m.";
  7244. culture.DateTimeFormat.PMDesignator = "p.m.";
  7245. IList<object> dates = new List<object>
  7246. {
  7247. new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc),
  7248. new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1))
  7249. };
  7250. StringWriter sw = new StringWriter();
  7251. JsonTextWriter jsonWriter = new JsonTextWriter(sw);
  7252. JsonSerializer serializer = JsonSerializer.Create(new JsonSerializerSettings
  7253. {
  7254. DateFormatString = "yyyy tt",
  7255. Culture = culture,
  7256. Formatting = Formatting.Indented
  7257. });
  7258. serializer.Serialize(jsonWriter, dates);
  7259. Assert.IsNull(jsonWriter.DateFormatString);
  7260. Assert.AreEqual(CultureInfo.InvariantCulture, jsonWriter.Culture);
  7261. Assert.AreEqual(Formatting.None, jsonWriter.Formatting);
  7262. string json = sw.ToString();
  7263. StringAssert.AreEqual(@"[
  7264. ""2000 p.m."",
  7265. ""2000 p.m.""
  7266. ]", json);
  7267. }
  7268. #if !(NET20 || NET35)
  7269. [Test]
  7270. public void SerializeDeserializeTuple()
  7271. {
  7272. Tuple<int, int> tuple = Tuple.Create(500, 20);
  7273. string json = JsonConvert.SerializeObject(tuple);
  7274. Assert.AreEqual(@"{""Item1"":500,""Item2"":20}", json);
  7275. Tuple<int, int> tuple2 = JsonConvert.DeserializeObject<Tuple<int, int>>(json);
  7276. Assert.AreEqual(500, tuple2.Item1);
  7277. Assert.AreEqual(20, tuple2.Item2);
  7278. }
  7279. #endif
  7280. public class MessageWithIsoDate
  7281. {
  7282. public String IsoDate { get; set; }
  7283. }
  7284. [Test]
  7285. public void JsonSerializerStringEscapeHandling()
  7286. {
  7287. StringWriter sw = new StringWriter();
  7288. JsonTextWriter jsonWriter = new JsonTextWriter(sw);
  7289. JsonSerializer serializer = JsonSerializer.Create(new JsonSerializerSettings
  7290. {
  7291. StringEscapeHandling = StringEscapeHandling.EscapeHtml,
  7292. Formatting = Formatting.Indented
  7293. });
  7294. serializer.Serialize(jsonWriter, new { html = "<html></html>" });
  7295. Assert.AreEqual(StringEscapeHandling.Default, jsonWriter.StringEscapeHandling);
  7296. string json = sw.ToString();
  7297. StringAssert.AreEqual(@"{
  7298. ""html"": ""\u003chtml\u003e\u003c/html\u003e""
  7299. }", json);
  7300. }
  7301. public class NoConstructorReadOnlyCollection<T> : ReadOnlyCollection<T>
  7302. {
  7303. public NoConstructorReadOnlyCollection() : base(new List<T>())
  7304. {
  7305. }
  7306. }
  7307. [Test]
  7308. public void NoConstructorReadOnlyCollectionTest()
  7309. {
  7310. ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<NoConstructorReadOnlyCollection<int>>("[1]"), "Cannot deserialize readonly or fixed size list: Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+NoConstructorReadOnlyCollection`1[System.Int32]. Path '', line 1, position 1.");
  7311. }
  7312. #if !(NET40 || NET35 || NET20 || PORTABLE40)
  7313. public class NoConstructorReadOnlyDictionary<TKey, TValue> : ReadOnlyDictionary<TKey, TValue>
  7314. {
  7315. public NoConstructorReadOnlyDictionary()
  7316. : base(new Dictionary<TKey, TValue>())
  7317. {
  7318. }
  7319. }
  7320. [Test]
  7321. public void NoConstructorReadOnlyDictionaryTest()
  7322. {
  7323. ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<NoConstructorReadOnlyDictionary<int, int>>("{'1':1}"), "Cannot deserialize readonly or fixed size dictionary: Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+NoConstructorReadOnlyDictionary`2[System.Int32,System.Int32]. Path '1', line 1, position 5.");
  7324. }
  7325. #endif
  7326. #if !(PORTABLE || NET35 || NET20 || PORTABLE40) || NETSTANDARD1_1
  7327. [Test]
  7328. public void ReadTooLargeInteger()
  7329. {
  7330. string json = @"[999999999999999999999999999999999999999999999999]";
  7331. IList<BigInteger> l = JsonConvert.DeserializeObject<IList<BigInteger>>(json);
  7332. Assert.AreEqual(BigInteger.Parse("999999999999999999999999999999999999999999999999"), l[0]);
  7333. ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<IList<long>>(json), "Error converting value 999999999999999999999999999999999999999999999999 to type 'System.Int64'. Path '[0]', line 1, position 49.");
  7334. }
  7335. #endif
  7336. #if !(DNXCORE50)
  7337. [Serializable]
  7338. #endif
  7339. [DataContract]
  7340. public struct Pair<TFirst, TSecond>
  7341. {
  7342. public Pair(TFirst first, TSecond second)
  7343. : this()
  7344. {
  7345. this.First = first;
  7346. this.Second = second;
  7347. }
  7348. [DataMember]
  7349. public TFirst First { get; set; }
  7350. [DataMember]
  7351. public TSecond Second { get; set; }
  7352. }
  7353. [Test]
  7354. public void SerializeStructWithSerializableAndDataContract()
  7355. {
  7356. Pair<string, int> p = new Pair<string, int>("One", 2);
  7357. string json = JsonConvert.SerializeObject(p);
  7358. Assert.AreEqual(@"{""First"":""One"",""Second"":2}", json);
  7359. #if !(PORTABLE || DNXCORE50 || PORTABLE40)
  7360. DefaultContractResolver r = new DefaultContractResolver();
  7361. r.IgnoreSerializableAttribute = false;
  7362. json = JsonConvert.SerializeObject(p, new JsonSerializerSettings
  7363. {
  7364. ContractResolver = r
  7365. });
  7366. Assert.AreEqual(@"{""First"":""One"",""Second"":2}", json);
  7367. #endif
  7368. }
  7369. [Test]
  7370. public void ReadStringFloatingPointSymbols()
  7371. {
  7372. string json = @"[
  7373. ""NaN"",
  7374. ""Infinity"",
  7375. ""-Infinity""
  7376. ]";
  7377. IList<float> floats = JsonConvert.DeserializeObject<IList<float>>(json);
  7378. Assert.AreEqual(float.NaN, floats[0]);
  7379. Assert.AreEqual(float.PositiveInfinity, floats[1]);
  7380. Assert.AreEqual(float.NegativeInfinity, floats[2]);
  7381. IList<double> doubles = JsonConvert.DeserializeObject<IList<double>>(json);
  7382. Assert.AreEqual(float.NaN, doubles[0]);
  7383. Assert.AreEqual(float.PositiveInfinity, doubles[1]);
  7384. Assert.AreEqual(float.NegativeInfinity, doubles[2]);
  7385. }
  7386. [Test]
  7387. public void DefaultDateStringFormatVsUnsetDateStringFormat()
  7388. {
  7389. IDictionary<string, object> dates = new Dictionary<string, object>
  7390. {
  7391. { "DateTime-Unspecified", new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Unspecified) },
  7392. { "DateTime-Utc", new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc) },
  7393. { "DateTime-Local", new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Local) },
  7394. { "DateTimeOffset-Zero", new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero) },
  7395. { "DateTimeOffset-Plus1", new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1)) },
  7396. { "DateTimeOffset-Plus15", new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1.5)) }
  7397. };
  7398. string expected = JsonConvert.SerializeObject(dates, Formatting.Indented);
  7399. string actual = JsonConvert.SerializeObject(dates, Formatting.Indented, new JsonSerializerSettings
  7400. {
  7401. DateFormatString = JsonSerializerSettings.DefaultDateFormatString
  7402. });
  7403. Assert.AreEqual(expected, actual);
  7404. }
  7405. #endif
  7406. #if !NET20
  7407. public class NullableTestClass
  7408. {
  7409. public bool? MyNullableBool { get; set; }
  7410. public int? MyNullableInteger { get; set; }
  7411. public DateTime? MyNullableDateTime { get; set; }
  7412. public DateTimeOffset? MyNullableDateTimeOffset { get; set; }
  7413. public Decimal? MyNullableDecimal { get; set; }
  7414. }
  7415. [Test]
  7416. public void TestStringToNullableDeserialization()
  7417. {
  7418. string json = @"{
  7419. ""MyNullableBool"": """",
  7420. ""MyNullableInteger"": """",
  7421. ""MyNullableDateTime"": """",
  7422. ""MyNullableDateTimeOffset"": """",
  7423. ""MyNullableDecimal"": """"
  7424. }";
  7425. NullableTestClass c2 = JsonConvert.DeserializeObject<NullableTestClass>(json);
  7426. Assert.IsNull(c2.MyNullableBool);
  7427. Assert.IsNull(c2.MyNullableInteger);
  7428. Assert.IsNull(c2.MyNullableDateTime);
  7429. Assert.IsNull(c2.MyNullableDateTimeOffset);
  7430. Assert.IsNull(c2.MyNullableDecimal);
  7431. }
  7432. #endif
  7433. #if !(NET20 || NET35)
  7434. [Test]
  7435. public void HashSetInterface()
  7436. {
  7437. ISet<string> s1 = new HashSet<string>(new[] { "1", "two", "III" });
  7438. string json = JsonConvert.SerializeObject(s1);
  7439. ISet<string> s2 = JsonConvert.DeserializeObject<ISet<string>>(json);
  7440. Assert.AreEqual(s1.Count, s2.Count);
  7441. foreach (string s in s1)
  7442. {
  7443. Assert.IsTrue(s2.Contains(s));
  7444. }
  7445. }
  7446. #endif
  7447. [Test]
  7448. public void DeserializeDecimal()
  7449. {
  7450. JsonTextReader reader = new JsonTextReader(new StringReader("1234567890.123456"));
  7451. var settings = new JsonSerializerSettings();
  7452. var serialiser = JsonSerializer.Create(settings);
  7453. decimal? d = serialiser.Deserialize<decimal?>(reader);
  7454. Assert.AreEqual(1234567890.123456m, d);
  7455. }
  7456. #if !(PORTABLE || DNXCORE50 || PORTABLE40)
  7457. [Test]
  7458. public void DontSerializeStaticFields()
  7459. {
  7460. string json =
  7461. JsonConvert.SerializeObject(new AnswerFilterModel(), Formatting.Indented, new JsonSerializerSettings
  7462. {
  7463. ContractResolver = new DefaultContractResolver
  7464. {
  7465. IgnoreSerializableAttribute = false
  7466. }
  7467. });
  7468. StringAssert.AreEqual(@"{
  7469. ""<Active>k__BackingField"": false,
  7470. ""<Ja>k__BackingField"": false,
  7471. ""<Handlungsbedarf>k__BackingField"": false,
  7472. ""<Beratungsbedarf>k__BackingField"": false,
  7473. ""<Unzutreffend>k__BackingField"": false,
  7474. ""<Unbeantwortet>k__BackingField"": false
  7475. }", json);
  7476. }
  7477. #endif
  7478. #if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
  7479. [Test]
  7480. public void SerializeBigInteger()
  7481. {
  7482. BigInteger i = BigInteger.Parse("123456789999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990");
  7483. string json = JsonConvert.SerializeObject(new[] { i }, Formatting.Indented);
  7484. StringAssert.AreEqual(@"[
  7485. 123456789999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990
  7486. ]", json);
  7487. }
  7488. #endif
  7489. public class FooConstructor
  7490. {
  7491. [JsonProperty(PropertyName = "something_else")]
  7492. public readonly string Bar;
  7493. public FooConstructor(string bar)
  7494. {
  7495. if (bar == null)
  7496. {
  7497. throw new ArgumentNullException(nameof(bar));
  7498. }
  7499. Bar = bar;
  7500. }
  7501. }
  7502. [Test]
  7503. public void DeserializeWithConstructor()
  7504. {
  7505. const string json = @"{""something_else"":""my value""}";
  7506. var foo = JsonConvert.DeserializeObject<FooConstructor>(json);
  7507. Assert.AreEqual("my value", foo.Bar);
  7508. }
  7509. [Test]
  7510. public void SerializeCustomReferenceResolver()
  7511. {
  7512. PersonReference john = new PersonReference
  7513. {
  7514. Id = new Guid("0B64FFDF-D155-44AD-9689-58D9ADB137F3"),
  7515. Name = "John Smith"
  7516. };
  7517. PersonReference jane = new PersonReference
  7518. {
  7519. Id = new Guid("AE3C399C-058D-431D-91B0-A36C266441B9"),
  7520. Name = "Jane Smith"
  7521. };
  7522. john.Spouse = jane;
  7523. jane.Spouse = john;
  7524. IList<PersonReference> people = new List<PersonReference>
  7525. {
  7526. john,
  7527. jane
  7528. };
  7529. string json = JsonConvert.SerializeObject(people, new JsonSerializerSettings
  7530. {
  7531. #pragma warning disable 618
  7532. ReferenceResolver = new IdReferenceResolver(),
  7533. #pragma warning restore 618
  7534. PreserveReferencesHandling = PreserveReferencesHandling.Objects,
  7535. Formatting = Formatting.Indented
  7536. });
  7537. StringAssert.AreEqual(@"[
  7538. {
  7539. ""$id"": ""0b64ffdf-d155-44ad-9689-58d9adb137f3"",
  7540. ""Name"": ""John Smith"",
  7541. ""Spouse"": {
  7542. ""$id"": ""ae3c399c-058d-431d-91b0-a36c266441b9"",
  7543. ""Name"": ""Jane Smith"",
  7544. ""Spouse"": {
  7545. ""$ref"": ""0b64ffdf-d155-44ad-9689-58d9adb137f3""
  7546. }
  7547. }
  7548. },
  7549. {
  7550. ""$ref"": ""ae3c399c-058d-431d-91b0-a36c266441b9""
  7551. }
  7552. ]", json);
  7553. }
  7554. [Test]
  7555. public void NullReferenceResolver()
  7556. {
  7557. PersonReference john = new PersonReference
  7558. {
  7559. Id = new Guid("0B64FFDF-D155-44AD-9689-58D9ADB137F3"),
  7560. Name = "John Smith"
  7561. };
  7562. PersonReference jane = new PersonReference
  7563. {
  7564. Id = new Guid("AE3C399C-058D-431D-91B0-A36C266441B9"),
  7565. Name = "Jane Smith"
  7566. };
  7567. john.Spouse = jane;
  7568. jane.Spouse = john;
  7569. IList<PersonReference> people = new List<PersonReference>
  7570. {
  7571. john,
  7572. jane
  7573. };
  7574. string json = JsonConvert.SerializeObject(people, new JsonSerializerSettings
  7575. {
  7576. #pragma warning disable 618
  7577. ReferenceResolver = null,
  7578. #pragma warning restore 618
  7579. PreserveReferencesHandling = PreserveReferencesHandling.Objects,
  7580. Formatting = Formatting.Indented
  7581. });
  7582. StringAssert.AreEqual(@"[
  7583. {
  7584. ""$id"": ""1"",
  7585. ""Name"": ""John Smith"",
  7586. ""Spouse"": {
  7587. ""$id"": ""2"",
  7588. ""Name"": ""Jane Smith"",
  7589. ""Spouse"": {
  7590. ""$ref"": ""1""
  7591. }
  7592. }
  7593. },
  7594. {
  7595. ""$ref"": ""2""
  7596. }
  7597. ]", json);
  7598. }
  7599. #if !(PORTABLE || PORTABLE40 || DNXCORE50)
  7600. [Test]
  7601. public void SerializeDictionaryWithStructKey()
  7602. {
  7603. string json = JsonConvert.SerializeObject(
  7604. new Dictionary<Size, Size> { { new Size(1, 2), new Size(3, 4) } }
  7605. );
  7606. Assert.AreEqual(@"{""1, 2"":""3, 4""}", json);
  7607. Dictionary<Size, Size> d = JsonConvert.DeserializeObject<Dictionary<Size, Size>>(json);
  7608. Assert.AreEqual(new Size(1, 2), d.Keys.First());
  7609. Assert.AreEqual(new Size(3, 4), d.Values.First());
  7610. }
  7611. #endif
  7612. #if !(PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD1_0 || NETSTANDARD1_1
  7613. [Test]
  7614. public void SerializeDictionaryWithStructKey_Custom()
  7615. {
  7616. string json = JsonConvert.SerializeObject(
  7617. new Dictionary<TypeConverterSize, TypeConverterSize> { { new TypeConverterSize(1, 2), new TypeConverterSize(3, 4) } }
  7618. );
  7619. Assert.AreEqual(@"{""1, 2"":""3, 4""}", json);
  7620. Dictionary<TypeConverterSize, TypeConverterSize> d = JsonConvert.DeserializeObject<Dictionary<TypeConverterSize, TypeConverterSize>>(json);
  7621. Assert.AreEqual(new TypeConverterSize(1, 2), d.Keys.First());
  7622. Assert.AreEqual(new TypeConverterSize(3, 4), d.Values.First());
  7623. }
  7624. [TypeConverter(typeof(TypeConverterSizeConverter))]
  7625. public struct TypeConverterSize
  7626. {
  7627. public static readonly TypeConverterSize Empty;
  7628. private int _width;
  7629. private int _height;
  7630. public TypeConverterSize(int width, int height)
  7631. {
  7632. _width = width;
  7633. _height = height;
  7634. }
  7635. public int Width
  7636. {
  7637. get { return _width; }
  7638. set { _width = value; }
  7639. }
  7640. public int Height
  7641. {
  7642. get { return _height; }
  7643. set { _height = value; }
  7644. }
  7645. }
  7646. public class TypeConverterSizeConverter : TypeConverter
  7647. {
  7648. public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
  7649. {
  7650. return ((sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType));
  7651. }
  7652. public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
  7653. {
  7654. return base.CanConvertTo(context, destinationType);
  7655. }
  7656. public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
  7657. {
  7658. string str = value as string;
  7659. if (str == null)
  7660. {
  7661. return base.ConvertFrom(context, culture, value);
  7662. }
  7663. string str2 = str.Trim();
  7664. if (str2.Length == 0)
  7665. {
  7666. return null;
  7667. }
  7668. if (culture == null)
  7669. {
  7670. culture = CultureInfo.CurrentCulture;
  7671. }
  7672. string[] strArray = str2.Split(',');
  7673. int[] numArray = new int[strArray.Length];
  7674. TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
  7675. for (int i = 0; i < numArray.Length; i++)
  7676. {
  7677. numArray[i] = (int)converter.ConvertFromString(context, culture, strArray[i]);
  7678. }
  7679. if (numArray.Length == 2)
  7680. {
  7681. return new TypeConverterSize(numArray[0], numArray[1]);
  7682. }
  7683. throw new ArgumentException("Bad format.");
  7684. }
  7685. public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
  7686. {
  7687. if (destinationType == null)
  7688. {
  7689. throw new ArgumentNullException("destinationType");
  7690. }
  7691. if (value is TypeConverterSize)
  7692. {
  7693. if (destinationType == typeof(string))
  7694. {
  7695. TypeConverterSize size = (TypeConverterSize)value;
  7696. if (culture == null)
  7697. {
  7698. culture = CultureInfo.CurrentCulture;
  7699. }
  7700. TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
  7701. string[] strArray = new string[2];
  7702. int num = 0;
  7703. strArray[num++] = converter.ConvertToString(context, culture, size.Width);
  7704. strArray[num++] = converter.ConvertToString(context, culture, size.Height);
  7705. return string.Join(", ", strArray);
  7706. }
  7707. }
  7708. return base.ConvertTo(context, culture, value, destinationType);
  7709. }
  7710. }
  7711. #endif
  7712. [Test]
  7713. public void DeserializeCustomReferenceResolver()
  7714. {
  7715. string json = @"[
  7716. {
  7717. ""$id"": ""0b64ffdf-d155-44ad-9689-58d9adb137f3"",
  7718. ""Name"": ""John Smith"",
  7719. ""Spouse"": {
  7720. ""$id"": ""ae3c399c-058d-431d-91b0-a36c266441b9"",
  7721. ""Name"": ""Jane Smith"",
  7722. ""Spouse"": {
  7723. ""$ref"": ""0b64ffdf-d155-44ad-9689-58d9adb137f3""
  7724. }
  7725. }
  7726. },
  7727. {
  7728. ""$ref"": ""ae3c399c-058d-431d-91b0-a36c266441b9""
  7729. }
  7730. ]";
  7731. IList<PersonReference> people = JsonConvert.DeserializeObject<IList<PersonReference>>(json, new JsonSerializerSettings
  7732. {
  7733. #pragma warning disable 618
  7734. ReferenceResolver = new IdReferenceResolver(),
  7735. #pragma warning restore 618
  7736. PreserveReferencesHandling = PreserveReferencesHandling.Objects,
  7737. Formatting = Formatting.Indented
  7738. });
  7739. Assert.AreEqual(2, people.Count);
  7740. PersonReference john = people[0];
  7741. PersonReference jane = people[1];
  7742. Assert.AreEqual(john, jane.Spouse);
  7743. Assert.AreEqual(jane, john.Spouse);
  7744. }
  7745. [Test]
  7746. public void DeserializeCustomReferenceResolver_ViaProvider()
  7747. {
  7748. string json = @"[
  7749. {
  7750. ""$id"": ""0b64ffdf-d155-44ad-9689-58d9adb137f3"",
  7751. ""Name"": ""John Smith"",
  7752. ""Spouse"": {
  7753. ""$id"": ""ae3c399c-058d-431d-91b0-a36c266441b9"",
  7754. ""Name"": ""Jane Smith"",
  7755. ""Spouse"": {
  7756. ""$ref"": ""0b64ffdf-d155-44ad-9689-58d9adb137f3""
  7757. }
  7758. }
  7759. },
  7760. {
  7761. ""$ref"": ""ae3c399c-058d-431d-91b0-a36c266441b9""
  7762. }
  7763. ]";
  7764. IList<PersonReference> people = JsonConvert.DeserializeObject<IList<PersonReference>>(json, new JsonSerializerSettings
  7765. {
  7766. ReferenceResolverProvider = () => new IdReferenceResolver(),
  7767. PreserveReferencesHandling = PreserveReferencesHandling.Objects,
  7768. Formatting = Formatting.Indented
  7769. });
  7770. Assert.AreEqual(2, people.Count);
  7771. PersonReference john = people[0];
  7772. PersonReference jane = people[1];
  7773. Assert.AreEqual(john, jane.Spouse);
  7774. Assert.AreEqual(jane, john.Spouse);
  7775. }
  7776. #if !(NET35 || NET20 || PORTABLE || PORTABLE40)
  7777. [Test]
  7778. public void TypeConverterOnInterface()
  7779. {
  7780. var consoleWriter = new ConsoleWriter();
  7781. // If dynamic type handling is enabled, case 1 and 3 work fine
  7782. var options = new JsonSerializerSettings
  7783. {
  7784. Converters = new JsonConverterCollection { new TypeConverterJsonConverter() },
  7785. //TypeNameHandling = TypeNameHandling.All
  7786. };
  7787. //
  7788. // Case 1: Serialize the concrete value and restore it from the interface
  7789. // Therefore we need dynamic handling of type information if the type is not serialized with the type converter directly
  7790. //
  7791. var text1 = JsonConvert.SerializeObject(consoleWriter, Formatting.Indented, options);
  7792. Assert.AreEqual(@"""Console Writer""", text1);
  7793. var restoredWriter = JsonConvert.DeserializeObject<IMyInterface>(text1, options);
  7794. Assert.AreEqual("ConsoleWriter", restoredWriter.PrintTest());
  7795. //
  7796. // Case 2: Serialize a dictionary where the interface is the key
  7797. // The key is always serialized with its ToString() method and therefore needs a mechanism to be restored from that (using the type converter)
  7798. //
  7799. var dict2 = new Dictionary<IMyInterface, string>();
  7800. dict2.Add(consoleWriter, "Console");
  7801. var text2 = JsonConvert.SerializeObject(dict2, Formatting.Indented, options);
  7802. StringAssert.AreEqual(@"{
  7803. ""Console Writer"": ""Console""
  7804. }", text2);
  7805. var restoredObject = JsonConvert.DeserializeObject<Dictionary<IMyInterface, string>>(text2, options);
  7806. Assert.AreEqual("ConsoleWriter", restoredObject.First().Key.PrintTest());
  7807. //
  7808. // Case 3 Serialize a dictionary where the interface is the value
  7809. // The key is always serialized with its ToString() method and therefore needs a mechanism to be restored from that (using the type converter)
  7810. //
  7811. var dict3 = new Dictionary<string, IMyInterface>();
  7812. dict3.Add("Console", consoleWriter);
  7813. var text3 = JsonConvert.SerializeObject(dict3, Formatting.Indented, options);
  7814. StringAssert.AreEqual(@"{
  7815. ""Console"": ""Console Writer""
  7816. }", text3);
  7817. var restoredDict2 = JsonConvert.DeserializeObject<Dictionary<string, IMyInterface>>(text3, options);
  7818. Assert.AreEqual("ConsoleWriter", restoredDict2.First().Value.PrintTest());
  7819. }
  7820. #endif
  7821. [Test]
  7822. public void Main()
  7823. {
  7824. ParticipantEntity product = new ParticipantEntity();
  7825. product.Properties = new Dictionary<string, string> { { "s", "d" } };
  7826. string json = JsonConvert.SerializeObject(product);
  7827. Assert.AreEqual(@"{""pa_info"":{""s"":""d""}}", json);
  7828. ParticipantEntity deserializedProduct = JsonConvert.DeserializeObject<ParticipantEntity>(json);
  7829. }
  7830. #if !(PORTABLE)
  7831. public class ConvertibleId : IConvertible
  7832. {
  7833. public int Value;
  7834. TypeCode IConvertible.GetTypeCode()
  7835. {
  7836. return TypeCode.Object;
  7837. }
  7838. object IConvertible.ToType(Type conversionType, IFormatProvider provider)
  7839. {
  7840. if (conversionType == typeof(object))
  7841. {
  7842. return this;
  7843. }
  7844. if (conversionType == typeof(int))
  7845. {
  7846. return (int)Value;
  7847. }
  7848. if (conversionType == typeof(long))
  7849. {
  7850. return (long)Value;
  7851. }
  7852. if (conversionType == typeof(string))
  7853. {
  7854. return Value.ToString(CultureInfo.InvariantCulture);
  7855. }
  7856. throw new InvalidCastException();
  7857. }
  7858. bool IConvertible.ToBoolean(IFormatProvider provider)
  7859. {
  7860. throw new InvalidCastException();
  7861. }
  7862. byte IConvertible.ToByte(IFormatProvider provider)
  7863. {
  7864. throw new InvalidCastException();
  7865. }
  7866. char IConvertible.ToChar(IFormatProvider provider)
  7867. {
  7868. throw new InvalidCastException();
  7869. }
  7870. DateTime IConvertible.ToDateTime(IFormatProvider provider)
  7871. {
  7872. throw new InvalidCastException();
  7873. }
  7874. decimal IConvertible.ToDecimal(IFormatProvider provider)
  7875. {
  7876. throw new InvalidCastException();
  7877. }
  7878. double IConvertible.ToDouble(IFormatProvider provider)
  7879. {
  7880. throw new InvalidCastException();
  7881. }
  7882. short IConvertible.ToInt16(IFormatProvider provider)
  7883. {
  7884. return (short)Value;
  7885. }
  7886. int IConvertible.ToInt32(IFormatProvider provider)
  7887. {
  7888. return Value;
  7889. }
  7890. long IConvertible.ToInt64(IFormatProvider provider)
  7891. {
  7892. return (long)Value;
  7893. }
  7894. sbyte IConvertible.ToSByte(IFormatProvider provider)
  7895. {
  7896. throw new InvalidCastException();
  7897. }
  7898. float IConvertible.ToSingle(IFormatProvider provider)
  7899. {
  7900. throw new InvalidCastException();
  7901. }
  7902. string IConvertible.ToString(IFormatProvider provider)
  7903. {
  7904. throw new InvalidCastException();
  7905. }
  7906. ushort IConvertible.ToUInt16(IFormatProvider provider)
  7907. {
  7908. throw new InvalidCastException();
  7909. }
  7910. uint IConvertible.ToUInt32(IFormatProvider provider)
  7911. {
  7912. throw new InvalidCastException();
  7913. }
  7914. ulong IConvertible.ToUInt64(IFormatProvider provider)
  7915. {
  7916. throw new InvalidCastException();
  7917. }
  7918. }
  7919. public class TestClassConvertable
  7920. {
  7921. public ConvertibleId Id;
  7922. public int X;
  7923. }
  7924. [Test]
  7925. public void ConvertibleIdTest()
  7926. {
  7927. var c = new TestClassConvertable { Id = new ConvertibleId { Value = 1 }, X = 2 };
  7928. var s = JsonConvert.SerializeObject(c, Formatting.Indented);
  7929. StringAssert.AreEqual(@"{
  7930. ""Id"": ""1"",
  7931. ""X"": 2
  7932. }", s);
  7933. }
  7934. #endif
  7935. [Test]
  7936. public void DuplicatePropertiesInNestedObject()
  7937. {
  7938. string content = @"{""result"":{""time"":1408188592,""time"":1408188593},""error"":null,""id"":""1""}";
  7939. JObject o = JsonConvert.DeserializeObject<JObject>(content);
  7940. int time = (int)o["result"]["time"];
  7941. Assert.AreEqual(1408188593, time);
  7942. }
  7943. [Test]
  7944. public void RoundtripUriOriginalString()
  7945. {
  7946. string originalUri = "https://test.com?m=a%2bb";
  7947. Uri uriWithPlus = new Uri(originalUri);
  7948. string jsonWithPlus = JsonConvert.SerializeObject(uriWithPlus);
  7949. Uri uriWithPlus2 = JsonConvert.DeserializeObject<Uri>(jsonWithPlus);
  7950. Assert.AreEqual(originalUri, uriWithPlus2.OriginalString);
  7951. }
  7952. [Test]
  7953. public void DateFormatStringWithDateTime()
  7954. {
  7955. DateTime dt = new DateTime(2000, 12, 22);
  7956. string dateFormatString = "yyyy'-pie-'MMM'-'dddd'-'dd";
  7957. JsonSerializerSettings settings = new JsonSerializerSettings
  7958. {
  7959. DateFormatString = dateFormatString
  7960. };
  7961. string json = JsonConvert.SerializeObject(dt, settings);
  7962. Assert.AreEqual(@"""2000-pie-Dec-Friday-22""", json);
  7963. DateTime dt1 = JsonConvert.DeserializeObject<DateTime>(json, settings);
  7964. Assert.AreEqual(dt, dt1);
  7965. JsonTextReader reader = new JsonTextReader(new StringReader(json))
  7966. {
  7967. DateFormatString = dateFormatString
  7968. };
  7969. JValue v = (JValue)JToken.ReadFrom(reader);
  7970. Assert.AreEqual(JTokenType.Date, v.Type);
  7971. Assert.AreEqual(typeof(DateTime), v.Value.GetType());
  7972. Assert.AreEqual(dt, (DateTime)v.Value);
  7973. reader = new JsonTextReader(new StringReader(@"""abc"""))
  7974. {
  7975. DateFormatString = dateFormatString
  7976. };
  7977. v = (JValue)JToken.ReadFrom(reader);
  7978. Assert.AreEqual(JTokenType.String, v.Type);
  7979. Assert.AreEqual(typeof(string), v.Value.GetType());
  7980. Assert.AreEqual("abc", v.Value);
  7981. }
  7982. [Test]
  7983. public void DateFormatStringWithDateTimeAndCulture()
  7984. {
  7985. CultureInfo culture = new CultureInfo("tr-TR");
  7986. DateTime dt = new DateTime(2000, 12, 22);
  7987. string dateFormatString = "yyyy'-pie-'MMM'-'dddd'-'dd";
  7988. JsonSerializerSettings settings = new JsonSerializerSettings
  7989. {
  7990. DateFormatString = dateFormatString,
  7991. Culture = culture
  7992. };
  7993. string json = JsonConvert.SerializeObject(dt, settings);
  7994. Assert.AreEqual(@"""2000-pie-Ara-Cuma-22""", json);
  7995. DateTime dt1 = JsonConvert.DeserializeObject<DateTime>(json, settings);
  7996. Assert.AreEqual(dt, dt1);
  7997. JsonTextReader reader = new JsonTextReader(new StringReader(json))
  7998. {
  7999. DateFormatString = dateFormatString,
  8000. Culture = culture
  8001. };
  8002. JValue v = (JValue)JToken.ReadFrom(reader);
  8003. Assert.AreEqual(JTokenType.Date, v.Type);
  8004. Assert.AreEqual(typeof(DateTime), v.Value.GetType());
  8005. Assert.AreEqual(dt, (DateTime)v.Value);
  8006. reader = new JsonTextReader(new StringReader(@"""2000-pie-Dec-Friday-22"""))
  8007. {
  8008. DateFormatString = dateFormatString,
  8009. Culture = culture
  8010. };
  8011. v = (JValue)JToken.ReadFrom(reader);
  8012. Assert.AreEqual(JTokenType.String, v.Type);
  8013. Assert.AreEqual(typeof(string), v.Value.GetType());
  8014. Assert.AreEqual("2000-pie-Dec-Friday-22", v.Value);
  8015. }
  8016. [Test]
  8017. public void DateFormatStringWithDictionaryKey_DateTime()
  8018. {
  8019. DateTime dt = new DateTime(2000, 12, 22);
  8020. string dateFormatString = "yyyy'-pie-'MMM'-'dddd'-'dd";
  8021. JsonSerializerSettings settings = new JsonSerializerSettings
  8022. {
  8023. DateFormatString = dateFormatString,
  8024. Formatting = Formatting.Indented
  8025. };
  8026. string json = JsonConvert.SerializeObject(new Dictionary<DateTime, string>
  8027. {
  8028. { dt, "123" }
  8029. }, settings);
  8030. StringAssert.AreEqual(@"{
  8031. ""2000-pie-Dec-Friday-22"": ""123""
  8032. }", json);
  8033. Dictionary<DateTime, string> d = JsonConvert.DeserializeObject<Dictionary<DateTime, string>>(json, settings);
  8034. Assert.AreEqual(dt, d.Keys.ElementAt(0));
  8035. }
  8036. [Test]
  8037. public void DateFormatStringWithDictionaryKey_DateTime_ReadAhead()
  8038. {
  8039. DateTime dt = new DateTime(2000, 12, 22);
  8040. string dateFormatString = "yyyy'-pie-'MMM'-'dddd'-'dd";
  8041. JsonSerializerSettings settings = new JsonSerializerSettings
  8042. {
  8043. DateFormatString = dateFormatString,
  8044. MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead,
  8045. Formatting = Formatting.Indented
  8046. };
  8047. string json = JsonConvert.SerializeObject(new Dictionary<DateTime, string>
  8048. {
  8049. { dt, "123" }
  8050. }, settings);
  8051. StringAssert.AreEqual(@"{
  8052. ""2000-pie-Dec-Friday-22"": ""123""
  8053. }", json);
  8054. Dictionary<DateTime, string> d = JsonConvert.DeserializeObject<Dictionary<DateTime, string>>(json, settings);
  8055. Assert.AreEqual(dt, d.Keys.ElementAt(0));
  8056. }
  8057. #if !NET20
  8058. [Test]
  8059. public void DateFormatStringWithDictionaryKey_DateTimeOffset()
  8060. {
  8061. DateTimeOffset dt = new DateTimeOffset(2000, 12, 22, 0, 0, 0, TimeSpan.Zero);
  8062. string dateFormatString = "yyyy'-pie-'MMM'-'dddd'-'dd'!'K";
  8063. JsonSerializerSettings settings = new JsonSerializerSettings
  8064. {
  8065. DateFormatString = dateFormatString,
  8066. Formatting = Formatting.Indented
  8067. };
  8068. string json = JsonConvert.SerializeObject(new Dictionary<DateTimeOffset, string>
  8069. {
  8070. { dt, "123" }
  8071. }, settings);
  8072. StringAssert.AreEqual(@"{
  8073. ""2000-pie-Dec-Friday-22!+00:00"": ""123""
  8074. }", json);
  8075. Dictionary<DateTimeOffset, string> d = JsonConvert.DeserializeObject<Dictionary<DateTimeOffset, string>>(json, settings);
  8076. Assert.AreEqual(dt, d.Keys.ElementAt(0));
  8077. }
  8078. [Test]
  8079. public void DateFormatStringWithDictionaryKey_DateTimeOffset_ReadAhead()
  8080. {
  8081. DateTimeOffset dt = new DateTimeOffset(2000, 12, 22, 0, 0, 0, TimeSpan.Zero);
  8082. string dateFormatString = "yyyy'-pie-'MMM'-'dddd'-'dd'!'K";
  8083. JsonSerializerSettings settings = new JsonSerializerSettings
  8084. {
  8085. DateFormatString = dateFormatString,
  8086. MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead,
  8087. Formatting = Formatting.Indented
  8088. };
  8089. string json = JsonConvert.SerializeObject(new Dictionary<DateTimeOffset, string>
  8090. {
  8091. { dt, "123" }
  8092. }, settings);
  8093. StringAssert.AreEqual(@"{
  8094. ""2000-pie-Dec-Friday-22!+00:00"": ""123""
  8095. }", json);
  8096. Dictionary<DateTimeOffset, string> d = JsonConvert.DeserializeObject<Dictionary<DateTimeOffset, string>>(json, settings);
  8097. Assert.AreEqual(dt, d.Keys.ElementAt(0));
  8098. }
  8099. [Test]
  8100. public void DateFormatStringWithDateTimeOffset()
  8101. {
  8102. DateTimeOffset dt = new DateTimeOffset(new DateTime(2000, 12, 22));
  8103. string dateFormatString = "yyyy'-pie-'MMM'-'dddd'-'dd";
  8104. JsonSerializerSettings settings = new JsonSerializerSettings
  8105. {
  8106. DateFormatString = dateFormatString
  8107. };
  8108. string json = JsonConvert.SerializeObject(dt, settings);
  8109. Assert.AreEqual(@"""2000-pie-Dec-Friday-22""", json);
  8110. DateTimeOffset dt1 = JsonConvert.DeserializeObject<DateTimeOffset>(json, settings);
  8111. Assert.AreEqual(dt, dt1);
  8112. JsonTextReader reader = new JsonTextReader(new StringReader(json))
  8113. {
  8114. DateFormatString = dateFormatString,
  8115. DateParseHandling = DateParseHandling.DateTimeOffset
  8116. };
  8117. JValue v = (JValue)JToken.ReadFrom(reader);
  8118. Assert.AreEqual(JTokenType.Date, v.Type);
  8119. Assert.AreEqual(typeof(DateTimeOffset), v.Value.GetType());
  8120. Assert.AreEqual(dt, (DateTimeOffset)v.Value);
  8121. }
  8122. [DataContract]
  8123. public class ConstantTestClass
  8124. {
  8125. [DataMember]
  8126. public const char MY_CONSTANT = '.';
  8127. }
  8128. [Test]
  8129. public void DeserializeConstantProperty()
  8130. {
  8131. ConstantTestClass c1 = new ConstantTestClass();
  8132. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  8133. StringAssert.AreEqual(@"{
  8134. ""MY_CONSTANT"": "".""
  8135. }", json);
  8136. JsonConvert.DeserializeObject<ConstantTestClass>(json);
  8137. }
  8138. #endif
  8139. [Test]
  8140. public void SerializeObjectWithEvent()
  8141. {
  8142. MyObservableObject o = new MyObservableObject
  8143. {
  8144. TestString = "Test string"
  8145. };
  8146. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  8147. StringAssert.AreEqual(@"{
  8148. ""PropertyChanged"": null,
  8149. ""TestString"": ""Test string""
  8150. }", json);
  8151. MyObservableObject o2 = JsonConvert.DeserializeObject<MyObservableObject>(json);
  8152. Assert.AreEqual("Test string", o2.TestString);
  8153. }
  8154. public class MyObservableObject : ObservableObject
  8155. {
  8156. public new string PropertyChanged;
  8157. public string TestString { get; set; }
  8158. }
  8159. public class ObservableObject : INotifyPropertyChanged
  8160. {
  8161. public event PropertyChangedEventHandler PropertyChanged;
  8162. protected PropertyChangedEventHandler PropertyChangedHandler
  8163. {
  8164. get { return PropertyChanged; }
  8165. }
  8166. }
  8167. [Test]
  8168. public void ParameterizedConstructorWithBasePrivateProperties()
  8169. {
  8170. var original = new DerivedConstructorType("Base", "Derived");
  8171. var serializerSettings = new JsonSerializerSettings();
  8172. var jsonCopy = JsonConvert.SerializeObject(original, serializerSettings);
  8173. var clonedObject = JsonConvert.DeserializeObject<DerivedConstructorType>(jsonCopy, serializerSettings);
  8174. Assert.AreEqual("Base", clonedObject.BaseProperty);
  8175. Assert.AreEqual("Derived", clonedObject.DerivedProperty);
  8176. }
  8177. public class DerivedConstructorType : BaseConstructorType
  8178. {
  8179. public DerivedConstructorType(string baseProperty, string derivedProperty)
  8180. : base(baseProperty)
  8181. {
  8182. DerivedProperty = derivedProperty;
  8183. }
  8184. [JsonProperty]
  8185. public string DerivedProperty { get; private set; }
  8186. }
  8187. public class BaseConstructorType
  8188. {
  8189. [JsonProperty]
  8190. public string BaseProperty { get; private set; }
  8191. public BaseConstructorType(string baseProperty)
  8192. {
  8193. BaseProperty = baseProperty;
  8194. }
  8195. }
  8196. public class ErroringJsonConverter : JsonConverter
  8197. {
  8198. public ErroringJsonConverter(string s)
  8199. {
  8200. }
  8201. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  8202. {
  8203. throw new NotImplementedException();
  8204. }
  8205. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  8206. {
  8207. throw new NotImplementedException();
  8208. }
  8209. public override bool CanConvert(Type objectType)
  8210. {
  8211. throw new NotImplementedException();
  8212. }
  8213. }
  8214. [JsonConverter(typeof(ErroringJsonConverter))]
  8215. public class ErroringTestClass
  8216. {
  8217. }
  8218. [Test]
  8219. public void ErrorCreatingJsonConverter()
  8220. {
  8221. ExceptionAssert.Throws<JsonException>(() => JsonConvert.SerializeObject(new ErroringTestClass()), "Error creating 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ErroringJsonConverter'.");
  8222. }
  8223. [Test]
  8224. public void DeserializeInvalidOctalRootError()
  8225. {
  8226. ExceptionAssert.Throws<JsonReaderException>(() => JsonConvert.DeserializeObject<string>("020474068"), "Input string '020474068' is not a valid number. Path '', line 1, position 9.");
  8227. }
  8228. [Test]
  8229. public void DeserializedDerivedWithPrivate()
  8230. {
  8231. string json = @"{
  8232. ""DerivedProperty"": ""derived"",
  8233. ""BaseProperty"": ""base""
  8234. }";
  8235. var d = JsonConvert.DeserializeObject<DerivedWithPrivate>(json);
  8236. Assert.AreEqual("base", d.BaseProperty);
  8237. Assert.AreEqual("derived", d.DerivedProperty);
  8238. }
  8239. #if !(NET20 || NET35 || PORTABLE || PORTABLE40)
  8240. [Test]
  8241. public void DeserializeNullableUnsignedLong()
  8242. {
  8243. NullableLongTestClass instance = new NullableLongTestClass
  8244. {
  8245. Value = ulong.MaxValue
  8246. };
  8247. string output = JsonConvert.SerializeObject(instance);
  8248. NullableLongTestClass result = JsonConvert.DeserializeObject<NullableLongTestClass>(output);
  8249. Assert.AreEqual(ulong.MaxValue, result.Value);
  8250. }
  8251. public class NullableLongTestClass
  8252. {
  8253. public ulong? Value { get; set; }
  8254. }
  8255. #endif
  8256. #if !(DNXCORE50)
  8257. [Test]
  8258. public void MailMessageConverterTest()
  8259. {
  8260. const string JsonMessage = @"{
  8261. ""From"": {
  8262. ""Address"": ""askywalker@theEmpire.gov"",
  8263. ""DisplayName"": ""Darth Vader""
  8264. },
  8265. ""Sender"": null,
  8266. ""ReplyTo"": null,
  8267. ""ReplyToList"": [],
  8268. ""To"": [
  8269. {
  8270. ""Address"": ""lskywalker@theRebellion.org"",
  8271. ""DisplayName"": ""Luke Skywalker""
  8272. }
  8273. ],
  8274. ""Bcc"": [],
  8275. ""CC"": [
  8276. {
  8277. ""Address"": ""lorgana@alderaan.gov"",
  8278. ""DisplayName"": ""Princess Leia""
  8279. }
  8280. ],
  8281. ""Priority"": 0,
  8282. ""DeliveryNotificationOptions"": 0,
  8283. ""Subject"": ""Family tree"",
  8284. ""SubjectEncoding"": null,
  8285. ""Headers"": [],
  8286. ""HeadersEncoding"": null,
  8287. ""Body"": ""<strong>I am your father!</strong>"",
  8288. ""BodyEncoding"": ""US-ASCII"",
  8289. ""BodyTransferEncoding"": -1,
  8290. ""IsBodyHtml"": true,
  8291. ""Attachments"": [
  8292. {
  8293. ""FileName"": ""skywalker family tree.jpg"",
  8294. ""ContentBase64"": ""AQIDBAU=""
  8295. }
  8296. ],
  8297. ""AlternateViews"": []
  8298. }";
  8299. ExceptionAssert.Throws<JsonSerializationException>(() =>
  8300. {
  8301. JsonConvert.DeserializeObject<System.Net.Mail.MailMessage>(
  8302. JsonMessage,
  8303. new MailAddressReadConverter(),
  8304. new AttachmentReadConverter(),
  8305. new EncodingReadConverter());
  8306. },
  8307. "Cannot populate list type System.Net.Mime.HeaderCollection. Path 'Headers', line 26, position 14.");
  8308. }
  8309. public class MailAddressReadConverter : JsonConverter
  8310. {
  8311. public override bool CanConvert(Type objectType)
  8312. {
  8313. return objectType == typeof(System.Net.Mail.MailAddress);
  8314. }
  8315. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  8316. {
  8317. var messageJObject = serializer.Deserialize<JObject>(reader);
  8318. if (messageJObject == null)
  8319. {
  8320. return null;
  8321. }
  8322. var address = messageJObject.GetValue("Address", StringComparison.OrdinalIgnoreCase).ToObject<string>();
  8323. JToken displayNameToken;
  8324. string displayName;
  8325. if (messageJObject.TryGetValue("DisplayName", StringComparison.OrdinalIgnoreCase, out displayNameToken)
  8326. && !string.IsNullOrEmpty(displayName = displayNameToken.ToObject<string>()))
  8327. {
  8328. return new System.Net.Mail.MailAddress(address, displayName);
  8329. }
  8330. return new System.Net.Mail.MailAddress(address);
  8331. }
  8332. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  8333. {
  8334. throw new NotImplementedException();
  8335. }
  8336. }
  8337. public class AttachmentReadConverter : JsonConverter
  8338. {
  8339. public override bool CanConvert(Type objectType)
  8340. {
  8341. return objectType == typeof(System.Net.Mail.Attachment);
  8342. }
  8343. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  8344. {
  8345. var info = serializer.Deserialize<AttachmentInfo>(reader);
  8346. var attachment = info != null
  8347. ? new System.Net.Mail.Attachment(new MemoryStream(Convert.FromBase64String(info.ContentBase64)), "application/octet-stream")
  8348. {
  8349. ContentDisposition = { FileName = info.FileName }
  8350. }
  8351. : null;
  8352. return attachment;
  8353. }
  8354. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  8355. {
  8356. throw new NotImplementedException();
  8357. }
  8358. private class AttachmentInfo
  8359. {
  8360. [JsonProperty(Required = Required.Always)]
  8361. public string FileName { get; set; }
  8362. [JsonProperty(Required = Required.Always)]
  8363. public string ContentBase64 { get; set; }
  8364. }
  8365. }
  8366. public class EncodingReadConverter : JsonConverter
  8367. {
  8368. public override bool CanConvert(Type objectType)
  8369. {
  8370. return typeof(Encoding).IsAssignableFrom(objectType);
  8371. }
  8372. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  8373. {
  8374. var encodingName = serializer.Deserialize<string>(reader);
  8375. if (encodingName == null)
  8376. {
  8377. return null;
  8378. }
  8379. return Encoding.GetEncoding(encodingName);
  8380. }
  8381. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  8382. {
  8383. throw new NotImplementedException();
  8384. }
  8385. }
  8386. #endif
  8387. [Test]
  8388. public void ParametrizedConstructor_IncompleteJson()
  8389. {
  8390. string s = @"{""text"":""s"",""cursorPosition"":189,""dataSource"":""json_northwind"",";
  8391. ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<CompletionDataRequest>(s), "Unexpected end when deserializing object. Path 'dataSource', line 1, position 63.");
  8392. }
  8393. [Test]
  8394. public void ChildClassWithProtectedOverridePlusJsonProperty_Serialize()
  8395. {
  8396. JsonObjectContract c = (JsonObjectContract)DefaultContractResolver.Instance.ResolveContract(typeof(ChildClassWithProtectedOverridePlusJsonProperty));
  8397. Assert.AreEqual(1, c.Properties.Count);
  8398. var propertyValue = "test";
  8399. var testJson = @"{ 'MyProperty' : '" + propertyValue + "' }";
  8400. var testObject = JsonConvert.DeserializeObject<ChildClassWithProtectedOverridePlusJsonProperty>(testJson);
  8401. Assert.AreEqual(propertyValue, testObject.GetPropertyValue(), "MyProperty should be populated");
  8402. }
  8403. }
  8404. public class BaseClassWithProtectedVirtual
  8405. {
  8406. protected virtual string MyProperty { get; set; }
  8407. }
  8408. public class ChildClassWithProtectedOverridePlusJsonProperty : BaseClassWithProtectedVirtual
  8409. {
  8410. [JsonProperty]
  8411. protected override string MyProperty { get; set; }
  8412. public string GetPropertyValue()
  8413. {
  8414. return MyProperty;
  8415. }
  8416. }
  8417. public class DerivedWithPrivate : BaseWithPrivate
  8418. {
  8419. [JsonProperty]
  8420. public string DerivedProperty { get; private set; }
  8421. }
  8422. public class BaseWithPrivate
  8423. {
  8424. [JsonProperty]
  8425. public string BaseProperty { get; private set; }
  8426. }
  8427. public abstract class Test<T>
  8428. {
  8429. public abstract T Value { get; set; }
  8430. }
  8431. [JsonObject(MemberSerialization.OptIn)]
  8432. public class DecimalTest : Test<decimal>
  8433. {
  8434. protected DecimalTest()
  8435. {
  8436. }
  8437. public DecimalTest(decimal val)
  8438. {
  8439. Value = val;
  8440. }
  8441. [JsonProperty]
  8442. public override decimal Value { get; set; }
  8443. }
  8444. public class NonPublicConstructorWithJsonConstructor
  8445. {
  8446. public string Value { get; private set; }
  8447. public string Constructor { get; private set; }
  8448. [JsonConstructor]
  8449. private NonPublicConstructorWithJsonConstructor()
  8450. {
  8451. Constructor = "NonPublic";
  8452. }
  8453. public NonPublicConstructorWithJsonConstructor(string value)
  8454. {
  8455. Value = value;
  8456. Constructor = "Public Parameterized";
  8457. }
  8458. }
  8459. public abstract class AbstractTestClass
  8460. {
  8461. public string Value { get; set; }
  8462. }
  8463. public class AbstractImplementationTestClass : AbstractTestClass
  8464. {
  8465. }
  8466. public abstract class AbstractListTestClass<T> : List<T>
  8467. {
  8468. }
  8469. public class AbstractImplementationListTestClass<T> : AbstractListTestClass<T>
  8470. {
  8471. }
  8472. public abstract class AbstractDictionaryTestClass<TKey, TValue> : Dictionary<TKey, TValue>
  8473. {
  8474. }
  8475. public class AbstractImplementationDictionaryTestClass<TKey, TValue> : AbstractDictionaryTestClass<TKey, TValue>
  8476. {
  8477. }
  8478. public class PublicConstructorOverridenByJsonConstructor
  8479. {
  8480. public string Value { get; private set; }
  8481. public string Constructor { get; private set; }
  8482. public PublicConstructorOverridenByJsonConstructor()
  8483. {
  8484. Constructor = "NonPublic";
  8485. }
  8486. [JsonConstructor]
  8487. public PublicConstructorOverridenByJsonConstructor(string value)
  8488. {
  8489. Value = value;
  8490. Constructor = "Public Parameterized";
  8491. }
  8492. }
  8493. public class MultipleParametrizedConstructorsJsonConstructor
  8494. {
  8495. public string Value { get; private set; }
  8496. public int Age { get; private set; }
  8497. public string Constructor { get; private set; }
  8498. public MultipleParametrizedConstructorsJsonConstructor(string value)
  8499. {
  8500. Value = value;
  8501. Constructor = "Public Parameterized 1";
  8502. }
  8503. [JsonConstructor]
  8504. public MultipleParametrizedConstructorsJsonConstructor(string value, int age)
  8505. {
  8506. Value = value;
  8507. Age = age;
  8508. Constructor = "Public Parameterized 2";
  8509. }
  8510. }
  8511. public class EnumerableClass
  8512. {
  8513. public IEnumerable<string> Enumerable { get; set; }
  8514. }
  8515. [JsonObject(MemberSerialization.OptIn)]
  8516. public class ItemBase
  8517. {
  8518. [JsonProperty]
  8519. public string Name { get; set; }
  8520. }
  8521. public class ComplexItem : ItemBase
  8522. {
  8523. public Stream Source { get; set; }
  8524. }
  8525. public class DeserializeStringConvert
  8526. {
  8527. public string Name { get; set; }
  8528. public int Age { get; set; }
  8529. public double Height { get; set; }
  8530. public decimal Price { get; set; }
  8531. }
  8532. [JsonObject(MemberSerialization.OptIn)]
  8533. public class StaticTestClass
  8534. {
  8535. [JsonProperty]
  8536. public int x = 1;
  8537. [JsonProperty]
  8538. public static int y = 2;
  8539. [JsonProperty]
  8540. public static int z { get; set; }
  8541. static StaticTestClass()
  8542. {
  8543. z = 3;
  8544. }
  8545. }
  8546. public class CompletionDataRequest
  8547. {
  8548. public CompletionDataRequest(string text, int cursorPosition, string dataSource, string project)
  8549. {
  8550. Text = text;
  8551. CursorPosition = cursorPosition;
  8552. DataSource = dataSource;
  8553. Project = project;
  8554. }
  8555. public string Text { get; }
  8556. public int CursorPosition { get; }
  8557. public string DataSource { get; }
  8558. public string Project { get; }
  8559. }
  8560. }