PageRenderTime 55ms CodeModel.GetById 19ms RepoModel.GetById 0ms 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

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

  1. #region License
  2. // Copyright (c) 2007 James Newton-King
  3. //
  4. // Permission is hereby granted, free of charge, to any person
  5. // obtaining a copy of this software and associated documentation
  6. // files (the "Software"), to deal in the Software without
  7. // restriction, including without limitation the rights to use,
  8. // copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the
  10. // Software is furnished to do so, subject to the following
  11. // conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  18. // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  20. // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21. // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23. // OTHER DEALINGS IN THE SOFTWARE.
  24. #endregion
  25. using System;
  26. using System.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. As

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