PageRenderTime 69ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 2ms

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

https://bitbucket.org/wfpcoslv/maps-examples
C# | 10368 lines | 9722 code | 597 blank | 49 comment | 60 complexity | 3fd95a109c7d8841fa6117e8efa01ff7 MD5 | raw file
Possible License(s): GPL-2.0

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

  1. #region License
  2. // Copyright (c) 2007 James Newton-King
  3. //
  4. // Permission is hereby granted, free of charge, to any person
  5. // obtaining a copy of this software and associated documentation
  6. // files (the "Software"), to deal in the Software without
  7. // restriction, including without limitation the rights to use,
  8. // copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the
  10. // Software is furnished to do so, subject to the following
  11. // conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  18. // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  20. // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21. // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23. // OTHER DEALINGS IN THE SOFTWARE.
  24. #endregion
  25. using System;
  26. using System.ComponentModel;
  27. #if !(NET35 || NET20)
  28. using System.Collections.Concurrent;
  29. #endif
  30. using System.Collections.Generic;
  31. #if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3
  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 class ListSourceTest : IListSource
  97. {
  98. private string str;
  99. public string strprop
  100. {
  101. get { return str; }
  102. set { str = value; }
  103. }
  104. [JsonIgnore]
  105. public bool ContainsListCollection
  106. {
  107. get { return false; }
  108. }
  109. public IList GetList()
  110. {
  111. return new List<string>();
  112. }
  113. }
  114. [Test]
  115. public void ListSourceSerialize()
  116. {
  117. ListSourceTest c = new ListSourceTest();
  118. c.strprop = "test";
  119. string json = JsonConvert.SerializeObject(c);
  120. Assert.AreEqual(@"{""strprop"":""test""}", json);
  121. ListSourceTest c2 = JsonConvert.DeserializeObject<ListSourceTest>(json);
  122. Assert.AreEqual("test", c2.strprop);
  123. }
  124. public struct ImmutableStruct
  125. {
  126. public ImmutableStruct(string value)
  127. {
  128. Value = value;
  129. Value2 = 0;
  130. }
  131. public string Value { get; }
  132. public int Value2 { get; set; }
  133. }
  134. [Test]
  135. public void DeserializeImmutableStruct()
  136. {
  137. var result = JsonConvert.DeserializeObject<ImmutableStruct>("{ \"Value\": \"working\", \"Value2\": 2 }");
  138. Assert.AreEqual("working", result.Value);
  139. Assert.AreEqual(2, result.Value2);
  140. }
  141. public struct AlmostImmutableStruct
  142. {
  143. public AlmostImmutableStruct(string value, int value2)
  144. {
  145. Value = value;
  146. Value2 = value2;
  147. }
  148. public string Value { get; }
  149. public int Value2 { get; set; }
  150. }
  151. [Test]
  152. public void DeserializeAlmostImmutableStruct()
  153. {
  154. var result = JsonConvert.DeserializeObject<AlmostImmutableStruct>("{ \"Value\": \"working\", \"Value2\": 2 }");
  155. Assert.AreEqual(null, result.Value);
  156. Assert.AreEqual(2, result.Value2);
  157. }
  158. public class ErroringClass
  159. {
  160. public DateTime Tags { get; set; }
  161. }
  162. [Test]
  163. public void DontCloseInputOnDeserializeError()
  164. {
  165. using (var s = System.IO.File.OpenRead(ResolvePath("large.json")))
  166. {
  167. try
  168. {
  169. using (JsonTextReader reader = new JsonTextReader(new StreamReader(s)))
  170. {
  171. reader.SupportMultipleContent = true;
  172. reader.CloseInput = false;
  173. // read into array
  174. reader.Read();
  175. var ser = new JsonSerializer();
  176. ser.CheckAdditionalContent = false;
  177. ser.Deserialize<IList<ErroringClass>>(reader);
  178. }
  179. Assert.Fail();
  180. }
  181. catch (Exception)
  182. {
  183. Assert.IsTrue(s.Position > 0);
  184. s.Seek(0, SeekOrigin.Begin);
  185. Assert.AreEqual(0, s.Position);
  186. }
  187. }
  188. }
  189. public interface ISubclassBase
  190. {
  191. int ID { get; set; }
  192. string Name { get; set; }
  193. bool P1 { get; }
  194. }
  195. public interface ISubclass : ISubclassBase
  196. {
  197. new bool P1 { get; set; }
  198. int P2 { get; set; }
  199. }
  200. public interface IMainClass
  201. {
  202. int ID { get; set; }
  203. string Name { get; set; }
  204. ISubclass Subclass { get; set; }
  205. }
  206. public class Subclass : ISubclass
  207. {
  208. public int ID { get; set; }
  209. public string Name { get; set; }
  210. public bool P1 { get; set; }
  211. public int P2 { get; set; }
  212. }
  213. public class MainClass : IMainClass
  214. {
  215. public int ID { get; set; }
  216. public string Name { get; set; }
  217. public ISubclass Subclass { get; set; }
  218. }
  219. public class MyFactory
  220. {
  221. public static ISubclass InstantiateSubclass()
  222. {
  223. return new Subclass
  224. {
  225. ID = 123,
  226. Name = "ABC",
  227. P1 = true,
  228. P2 = 44
  229. };
  230. }
  231. public static IMainClass InstantiateManiClass()
  232. {
  233. return new MainClass
  234. {
  235. ID = 567,
  236. Name = "XYZ",
  237. Subclass = InstantiateSubclass()
  238. };
  239. }
  240. }
  241. [Test]
  242. public void SerializeInterfaceWithHiddenProperties()
  243. {
  244. var mySubclass = MyFactory.InstantiateSubclass();
  245. var myMainClass = MyFactory.InstantiateManiClass();
  246. //Class implementing interface with hidden members - flat object.
  247. var strJsonSubclass = JsonConvert.SerializeObject(mySubclass, Formatting.Indented);
  248. StringAssert.AreEqual(@"{
  249. ""ID"": 123,
  250. ""Name"": ""ABC"",
  251. ""P1"": true,
  252. ""P2"": 44
  253. }", strJsonSubclass);
  254. //Class implementing interface with hidden members - member of another class.
  255. var strJsonMainClass = JsonConvert.SerializeObject(myMainClass, Formatting.Indented);
  256. StringAssert.AreEqual(@"{
  257. ""ID"": 567,
  258. ""Name"": ""XYZ"",
  259. ""Subclass"": {
  260. ""ID"": 123,
  261. ""Name"": ""ABC"",
  262. ""P1"": true,
  263. ""P2"": 44
  264. }
  265. }", strJsonMainClass);
  266. }
  267. [Test]
  268. public void DeserializeGenericIEnumerableWithImplicitConversion()
  269. {
  270. string deserialized = @"{
  271. ""Enumerable"": [ ""abc"", ""def"" ]
  272. }";
  273. var enumerableClass = JsonConvert.DeserializeObject<GenericIEnumerableWithImplicitConversion>(deserialized);
  274. var enumerableObject = enumerableClass.Enumerable.ToArray();
  275. Assert.AreEqual(2, enumerableObject.Length);
  276. Assert.AreEqual("abc", enumerableObject[0].Value);
  277. Assert.AreEqual("def", enumerableObject[1].Value);
  278. }
  279. public class GenericIEnumerableWithImplicitConversion
  280. {
  281. public IEnumerable<ClassWithImplicitOperator> Enumerable { get; set; }
  282. }
  283. public class ClassWithImplicitOperator
  284. {
  285. public string Value { get; set; }
  286. public static implicit operator ClassWithImplicitOperator(string value)
  287. {
  288. return new ClassWithImplicitOperator() { Value = value };
  289. }
  290. }
  291. #if !(PORTABLE || PORTABLE40 || NET20 || NET35)
  292. [Test]
  293. public void LargeIntegerAsString()
  294. {
  295. var largeBrokenNumber = JsonConvert.DeserializeObject<Foo64>("{\"Blah\": 43443333222211111117 }");
  296. Assert.AreEqual("43443333222211111117", largeBrokenNumber.Blah);
  297. var largeOddWorkingNumber = JsonConvert.DeserializeObject<Foo64>("{\"Blah\": 53443333222211111117 }");
  298. Assert.AreEqual("53443333222211111117", largeOddWorkingNumber.Blah);
  299. }
  300. public class Foo64
  301. {
  302. public string Blah { get; set; }
  303. }
  304. #endif
  305. #if !NET20
  306. [Test]
  307. public void DeserializeMSDateTimeOffset()
  308. {
  309. DateTimeOffset d = JsonConvert.DeserializeObject<DateTimeOffset>(@"""/Date(1418924498000+0800)/""");
  310. long initialTicks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(d.DateTime, d.Offset);
  311. Assert.AreEqual(1418924498000, initialTicks);
  312. Assert.AreEqual(8, d.Offset.Hours);
  313. }
  314. #endif
  315. [Test]
  316. public void DeserializeBoolean_Null()
  317. {
  318. ExceptionAssert.Throws<JsonSerializationException>(
  319. () => JsonConvert.DeserializeObject<IList<bool>>(@"[null]"),
  320. "Error converting value {null} to type 'System.Boolean'. Path '[0]', line 1, position 5.");
  321. }
  322. [Test]
  323. public void DeserializeBoolean_DateTime()
  324. {
  325. ExceptionAssert.Throws<JsonReaderException>(
  326. () => JsonConvert.DeserializeObject<IList<bool>>(@"['2000-12-20T10:55:55Z']"),
  327. "Could not convert string to boolean: 2000-12-20T10:55:55Z. Path '[0]', line 1, position 23.");
  328. }
  329. [Test]
  330. public void DeserializeBoolean_BadString()
  331. {
  332. ExceptionAssert.Throws<JsonReaderException>(
  333. () => JsonConvert.DeserializeObject<IList<bool>>(@"['pie']"),
  334. @"Could not convert string to boolean: pie. Path '[0]', line 1, position 6.");
  335. }
  336. [Test]
  337. public void DeserializeBoolean_EmptyString()
  338. {
  339. ExceptionAssert.Throws<JsonSerializationException>(
  340. () => JsonConvert.DeserializeObject<IList<bool>>(@"['']"),
  341. @"Error converting value {null} to type 'System.Boolean'. Path '[0]', line 1, position 3.");
  342. }
  343. #if !(PORTABLE || PORTABLE40 || NET35 || NET20)
  344. [Test]
  345. public void DeserializeBooleans()
  346. {
  347. IList<bool> l = JsonConvert.DeserializeObject<IList<bool>>(@"[
  348. 1,
  349. 0,
  350. 1.1,
  351. 0.0,
  352. 0.000000000001,
  353. 9999999999,
  354. -9999999999,
  355. 9999999999999999999999999999999999999999999999999999999999999999999999,
  356. -9999999999999999999999999999999999999999999999999999999999999999999999,
  357. 'true',
  358. 'TRUE',
  359. 'false',
  360. 'FALSE'
  361. ]");
  362. int i = 0;
  363. Assert.AreEqual(true, l[i++]);
  364. Assert.AreEqual(false, l[i++]);
  365. Assert.AreEqual(true, l[i++]);
  366. Assert.AreEqual(false, l[i++]);
  367. Assert.AreEqual(true, l[i++]);
  368. Assert.AreEqual(true, l[i++]);
  369. Assert.AreEqual(true, l[i++]);
  370. Assert.AreEqual(true, l[i++]);
  371. Assert.AreEqual(true, l[i++]);
  372. Assert.AreEqual(true, l[i++]);
  373. Assert.AreEqual(true, l[i++]);
  374. Assert.AreEqual(false, l[i++]);
  375. Assert.AreEqual(false, l[i++]);
  376. }
  377. [Test]
  378. public void DeserializeNullableBooleans()
  379. {
  380. IList<bool?> l = JsonConvert.DeserializeObject<IList<bool?>>(@"[
  381. 1,
  382. 0,
  383. 1.1,
  384. 0.0,
  385. 0.000000000001,
  386. 9999999999,
  387. -9999999999,
  388. 9999999999999999999999999999999999999999999999999999999999999999999999,
  389. -9999999999999999999999999999999999999999999999999999999999999999999999,
  390. 'true',
  391. 'TRUE',
  392. 'false',
  393. 'FALSE',
  394. '',
  395. null
  396. ]");
  397. int i = 0;
  398. Assert.AreEqual(true, l[i++]);
  399. Assert.AreEqual(false, l[i++]);
  400. Assert.AreEqual(true, l[i++]);
  401. Assert.AreEqual(false, l[i++]);
  402. Assert.AreEqual(true, l[i++]);
  403. Assert.AreEqual(true, l[i++]);
  404. Assert.AreEqual(true, l[i++]);
  405. Assert.AreEqual(true, l[i++]);
  406. Assert.AreEqual(true, l[i++]);
  407. Assert.AreEqual(true, l[i++]);
  408. Assert.AreEqual(true, l[i++]);
  409. Assert.AreEqual(false, l[i++]);
  410. Assert.AreEqual(false, l[i++]);
  411. Assert.AreEqual(null, l[i++]);
  412. Assert.AreEqual(null, l[i++]);
  413. }
  414. #endif
  415. [Test]
  416. public void CaseInsensitiveRequiredPropertyConstructorCreation()
  417. {
  418. FooRequired foo1 = new FooRequired(new[] { "A", "B", "C" });
  419. string json = JsonConvert.SerializeObject(foo1);
  420. StringAssert.AreEqual(@"{""Bars"":[""A"",""B"",""C""]}", json);
  421. FooRequired foo2 = JsonConvert.DeserializeObject<FooRequired>(json);
  422. Assert.AreEqual(foo1.Bars.Count, foo2.Bars.Count);
  423. Assert.AreEqual(foo1.Bars[0], foo2.Bars[0]);
  424. Assert.AreEqual(foo1.Bars[1], foo2.Bars[1]);
  425. Assert.AreEqual(foo1.Bars[2], foo2.Bars[2]);
  426. }
  427. public class FooRequired
  428. {
  429. [JsonProperty(Required = Required.Always)]
  430. public List<string> Bars { get; private set; }
  431. public FooRequired(IEnumerable<string> bars)
  432. {
  433. Bars = new List<string>();
  434. if (bars != null)
  435. {
  436. Bars.AddRange(bars);
  437. }
  438. }
  439. }
  440. [Test]
  441. public void CoercedEmptyStringWithRequired()
  442. {
  443. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Binding>("{requiredProperty:''}"); }, "Required property 'RequiredProperty' expects a value but got null. Path '', line 1, position 21.");
  444. }
  445. [Test]
  446. public void CoercedEmptyStringWithRequired_DisallowNull()
  447. {
  448. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Binding_DisallowNull>("{requiredProperty:''}"); }, "Required property 'RequiredProperty' expects a non-null value. Path '', line 1, position 21.");
  449. }
  450. [Test]
  451. public void DisallowNull_NoValue()
  452. {
  453. Binding_DisallowNull o = JsonConvert.DeserializeObject<Binding_DisallowNull>("{}");
  454. Assert.IsNull(o.RequiredProperty);
  455. }
  456. [Test]
  457. public void CoercedEmptyStringWithRequiredConstructor()
  458. {
  459. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<FooRequired>("{Bars:''}"); }, "Required property 'Bars' expects a value but got null. Path '', line 1, position 9.");
  460. }
  461. public class IgnoredProperty
  462. {
  463. [JsonIgnore]
  464. [JsonProperty(Required = Required.Always)]
  465. public string StringProp1 { get; set; }
  466. [JsonIgnore]
  467. public string StringProp2 { get; set; }
  468. }
  469. [Test]
  470. public void NoErrorWhenValueDoesNotMatchIgnoredProperty()
  471. {
  472. IgnoredProperty p = JsonConvert.DeserializeObject<IgnoredProperty>("{'StringProp1':[1,2,3],'StringProp2':{}}");
  473. Assert.IsNull(p.StringProp1);
  474. Assert.IsNull(p.StringProp2);
  475. }
  476. public class Binding
  477. {
  478. [JsonProperty(Required = Required.Always)]
  479. public Binding RequiredProperty { get; set; }
  480. }
  481. public class Binding_DisallowNull
  482. {
  483. [JsonProperty(Required = Required.DisallowNull)]
  484. public Binding RequiredProperty { get; set; }
  485. }
  486. [Test]
  487. public void Serialize_Required_DisallowedNull()
  488. {
  489. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.SerializeObject(new Binding_DisallowNull()); }, "Cannot write a null value for property 'RequiredProperty'. Property requires a non-null value. Path ''.");
  490. }
  491. [Test]
  492. public void Serialize_Required_DisallowedNull_NullValueHandlingIgnore()
  493. {
  494. string json = JsonConvert.SerializeObject(new Binding_DisallowNull(), new JsonSerializerSettings
  495. {
  496. NullValueHandling = NullValueHandling.Ignore
  497. });
  498. Assert.AreEqual("{}", json);
  499. }
  500. [JsonObject(ItemRequired = Required.DisallowNull)]
  501. public class DictionaryWithNoNull
  502. {
  503. public string Name { get; set; }
  504. }
  505. [Test]
  506. public void Serialize_ItemRequired_DisallowedNull()
  507. {
  508. ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.SerializeObject(new DictionaryWithNoNull()); }, "Cannot write a null value for property 'Name'. Property requires a non-null value. Path ''.");
  509. }
  510. public class DictionaryKeyContractResolver : DefaultContractResolver
  511. {
  512. protected override string ResolveDictionaryKey(string dictionaryKey)
  513. {
  514. return dictionaryKey;
  515. }
  516. protected override string ResolvePropertyName(string propertyName)
  517. {
  518. #if DNXCORE50
  519. return propertyName.ToUpperInvariant();
  520. #else
  521. return propertyName.ToUpper(CultureInfo.InvariantCulture);
  522. #endif
  523. }
  524. }
  525. [Test]
  526. public void DictionaryKeyContractResolverTest()
  527. {
  528. var person = new
  529. {
  530. Name = "James",
  531. Age = 1,
  532. RoleNames = new Dictionary<string, bool>
  533. {
  534. { "IsAdmin", true },
  535. { "IsModerator", false }
  536. }
  537. };
  538. string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
  539. {
  540. ContractResolver = new DictionaryKeyContractResolver()
  541. });
  542. Assert.AreEqual(@"{
  543. ""NAME"": ""James"",
  544. ""AGE"": 1,
  545. ""ROLENAMES"": {
  546. ""IsAdmin"": true,
  547. ""IsModerator"": false
  548. }
  549. }", json);
  550. }
  551. [Test]
  552. public void IncompleteContainers()
  553. {
  554. ExceptionAssert.Throws<JsonSerializationException>(
  555. () => JsonConvert.DeserializeObject<IList<object>>("[1,"),
  556. "Unexpected end when deserializing array. Path '[0]', line 1, position 3.");
  557. ExceptionAssert.Throws<JsonSerializationException>(
  558. () => JsonConvert.DeserializeObject<IList<int>>("[1,"),
  559. "Unexpected end when deserializing array. Path '[0]', line 1, position 3.");
  560. ExceptionAssert.Throws<JsonSerializationException>(
  561. () => JsonConvert.DeserializeObject<IList<int>>("[1"),
  562. "Unexpected end when deserializing array. Path '[0]', line 1, position 2.");
  563. ExceptionAssert.Throws<JsonSerializationException>(
  564. () => JsonConvert.DeserializeObject<IDictionary<string, int>>("{'key':1,"),
  565. "Unexpected end when deserializing object. Path 'key', line 1, position 9.");
  566. ExceptionAssert.Throws<JsonSerializationException>(
  567. () => JsonConvert.DeserializeObject<IDictionary<string, int>>("{'key':1"),
  568. "Unexpected end when deserializing object. Path 'key', line 1, position 8.");
  569. ExceptionAssert.Throws<JsonSerializationException>(
  570. () => JsonConvert.DeserializeObject<IncompleteTestClass>("{'key':1,"),
  571. "Unexpected end when deserializing object. Path 'key', line 1, position 9.");
  572. ExceptionAssert.Throws<JsonSerializationException>(
  573. () => JsonConvert.DeserializeObject<IncompleteTestClass>("{'key':1"),
  574. "Unexpected end when deserializing object. Path 'key', line 1, position 8.");
  575. }
  576. public class IncompleteTestClass
  577. {
  578. public int Key { get; set; }
  579. }
  580. #if !NET20
  581. public enum EnumA
  582. {
  583. [EnumMember(Value = "value_a")]
  584. ValueA
  585. }
  586. [Test]
  587. public void DeserializeEnumsByName()
  588. {
  589. var e1 = JsonConvert.DeserializeObject<EnumA>("'ValueA'");
  590. Assert.AreEqual(EnumA.ValueA, e1);
  591. var e2 = JsonConvert.DeserializeObject<EnumA>("'value_a'", new StringEnumConverter());
  592. Assert.AreEqual(EnumA.ValueA, e2);
  593. }
  594. #endif
  595. public class RequiredPropertyTestClass
  596. {
  597. [JsonRequired]
  598. internal string Name { get; set; }
  599. }
  600. [Test]
  601. public void RequiredPropertyTest()
  602. {
  603. RequiredPropertyTestClass c1 = new RequiredPropertyTestClass();
  604. ExceptionAssert.Throws<JsonSerializationException>(
  605. () => JsonConvert.SerializeObject(c1),
  606. "Cannot write a null value for property 'Name'. Property requires a value. Path ''.");
  607. RequiredPropertyTestClass c2 = new RequiredPropertyTestClass
  608. {
  609. Name = "Name!"
  610. };
  611. string json = JsonConvert.SerializeObject(c2);
  612. Assert.AreEqual(@"{""Name"":""Name!""}", json);
  613. ExceptionAssert.Throws<JsonSerializationException>(
  614. () => JsonConvert.DeserializeObject<RequiredPropertyTestClass>(@"{}"),
  615. "Required property 'Name' not found in JSON. Path '', line 1, position 2.");
  616. ExceptionAssert.Throws<JsonSerializationException>(
  617. () => JsonConvert.DeserializeObject<RequiredPropertyTestClass>(@"{""Name"":null}"),
  618. "Required property 'Name' expects a value but got null. Path '', line 1, position 13.");
  619. RequiredPropertyTestClass c3 = JsonConvert.DeserializeObject<RequiredPropertyTestClass>(@"{""Name"":""Name!""}");
  620. Assert.AreEqual("Name!", c3.Name);
  621. }
  622. public class RequiredPropertyConstructorTestClass
  623. {
  624. public RequiredPropertyConstructorTestClass(string name)
  625. {
  626. Name = name;
  627. }
  628. [JsonRequired]
  629. internal string Name { get; set; }
  630. }
  631. [Test]
  632. public void RequiredPropertyConstructorTest()
  633. {
  634. RequiredPropertyConstructorTestClass c1 = new RequiredPropertyConstructorTestClass(null);
  635. ExceptionAssert.Throws<JsonSerializationException>(
  636. () => JsonConvert.SerializeObject(c1),
  637. "Cannot write a null value for property 'Name'. Property requires a value. Path ''.");
  638. RequiredPropertyConstructorTestClass c2 = new RequiredPropertyConstructorTestClass("Name!");
  639. string json = JsonConvert.SerializeObject(c2);
  640. Assert.AreEqual(@"{""Name"":""Name!""}", json);
  641. ExceptionAssert.Throws<JsonSerializationException>(
  642. () => JsonConvert.DeserializeObject<RequiredPropertyConstructorTestClass>(@"{}"),
  643. "Required property 'Name' not found in JSON. Path '', line 1, position 2.");
  644. RequiredPropertyConstructorTestClass c3 = JsonConvert.DeserializeObject<RequiredPropertyConstructorTestClass>(@"{""Name"":""Name!""}");
  645. Assert.AreEqual("Name!", c3.Name);
  646. }
  647. public class IgnoredPropertiesTestClass
  648. {
  649. [JsonIgnore]
  650. public Version IgnoredProperty { get; set; }
  651. [JsonIgnore]
  652. public List<Version> IgnoredList { get; set; }
  653. [JsonIgnore]
  654. public Dictionary<string, Version> IgnoredDictionary { get; set; }
  655. [JsonProperty(Required = Required.Always)]
  656. public string Name { get; set; }
  657. }
  658. public class IgnoredPropertiesContractResolver : DefaultContractResolver
  659. {
  660. public override JsonContract ResolveContract(Type type)
  661. {
  662. if (type == typeof(Version))
  663. {
  664. throw new Exception("Error!");
  665. }
  666. return base.ResolveContract(type);
  667. }
  668. }
  669. [Test]
  670. public void NeverResolveIgnoredPropertyTypes()
  671. {
  672. Version v = new Version(1, 2, 3, 4);
  673. IgnoredPropertiesTestClass c1 = new IgnoredPropertiesTestClass
  674. {
  675. IgnoredProperty = v,
  676. IgnoredList = new List<Version>
  677. {
  678. v
  679. },
  680. IgnoredDictionary = new Dictionary<string, Version>
  681. {
  682. { "Value", v }
  683. },
  684. Name = "Name!"
  685. };
  686. string json = JsonConvert.SerializeObject(c1, Formatting.Indented, new JsonSerializerSettings
  687. {
  688. ContractResolver = new IgnoredPropertiesContractResolver()
  689. });
  690. Assert.AreEqual(@"{
  691. ""Name"": ""Name!""
  692. }", json);
  693. string deserializeJson = @"{
  694. ""IgnoredList"": [
  695. {
  696. ""Major"": 1,
  697. ""Minor"": 2,
  698. ""Build"": 3,
  699. ""Revision"": 4,
  700. ""MajorRevision"": 0,
  701. ""MinorRevision"": 4
  702. }
  703. ],
  704. ""IgnoredDictionary"": {
  705. ""Value"": {
  706. ""Major"": 1,
  707. ""Minor"": 2,
  708. ""Build"": 3,
  709. ""Revision"": 4,
  710. ""MajorRevision"": 0,
  711. ""MinorRevision"": 4
  712. }
  713. },
  714. ""Name"": ""Name!""
  715. }";
  716. IgnoredPropertiesTestClass c2 = JsonConvert.DeserializeObject<IgnoredPropertiesTestClass>(deserializeJson, new JsonSerializerSettings
  717. {
  718. ContractResolver = new IgnoredPropertiesContractResolver()
  719. });
  720. Assert.AreEqual("Name!", c2.Name);
  721. }
  722. #if !(NET20 || NET35 || PORTABLE40)
  723. [Test]
  724. public void SerializeValueTuple()
  725. {
  726. ValueTuple<int, int, string> t = ValueTuple.Create(1, 2, "string");
  727. string json = JsonConvert.SerializeObject(t, Formatting.Indented);
  728. StringAssert.AreEqual(@"{
  729. ""Item1"": 1,
  730. ""Item2"": 2,
  731. ""Item3"": ""string""
  732. }", json);
  733. ValueTuple<int, int, string> t2 = JsonConvert.DeserializeObject<ValueTuple<int, int, string>>(json);
  734. Assert.AreEqual(1, t2.Item1);
  735. Assert.AreEqual(2, t2.Item2);
  736. Assert.AreEqual("string", t2.Item3);
  737. }
  738. #endif
  739. [Test]
  740. public void DeserializeStructWithConstructorAttribute()
  741. {
  742. ImmutableStructWithConstructorAttribute result = JsonConvert.DeserializeObject<ImmutableStructWithConstructorAttribute>("{ \"Value\": \"working\" }");
  743. Assert.AreEqual("working", result.Value);
  744. }
  745. public struct ImmutableStructWithConstructorAttribute
  746. {
  747. [JsonConstructor]
  748. public ImmutableStructWithConstructorAttribute(string value)
  749. {
  750. Value = value;
  751. }
  752. public string Value { get; }
  753. }
  754. #if !(DNXCORE50 || NET20)
  755. [MetadataType(typeof(CustomerValidation))]
  756. public partial class CustomerWithMetadataType
  757. {
  758. public System.Guid UpdatedBy_Id { get; set; }
  759. public class CustomerValidation
  760. {
  761. [JsonIgnore]
  762. public System.Guid UpdatedBy_Id { get; set; }
  763. }
  764. }
  765. [Test]
  766. public void SerializeMetadataType()
  767. {
  768. CustomerWithMetadataType c = new CustomerWithMetadataType()
  769. {
  770. UpdatedBy_Id = Guid.NewGuid()
  771. };
  772. string json = JsonConvert.SerializeObject(c);
  773. Assert.AreEqual("{}", json);
  774. CustomerWithMetadataType c2 = JsonConvert.DeserializeObject<CustomerWithMetadataType>("{'UpdatedBy_Id':'F6E0666D-13C7-4745-B486-800812C8F6DE'}");
  775. Assert.AreEqual(Guid.Empty, c2.UpdatedBy_Id);
  776. }
  777. [Serializable]
  778. public partial class FaqItem
  779. {
  780. public FaqItem()
  781. {
  782. this.Sections = new HashSet<FaqSection>();
  783. }
  784. public int FaqId { get; set; }
  785. public string Name { get; set; }
  786. public bool IsDeleted { get; set; }
  787. public virtual ICollection<FaqSection> Sections { get; set; }
  788. }
  789. [MetadataType(typeof(FaqItemMetadata))]
  790. partial class FaqItem
  791. {
  792. [JsonProperty("FullSectionsProp")]
  793. public ICollection<FaqSection> FullSections
  794. {
  795. get { return Sections; }
  796. }
  797. }
  798. public class FaqItemMetadata
  799. {
  800. [JsonIgnore]
  801. public virtual ICollection<FaqSection> Sections { get; set; }
  802. }
  803. public class FaqSection
  804. {
  805. }
  806. public class FaqItemProxy : FaqItem
  807. {
  808. public bool IsProxy { get; set; }
  809. public override ICollection<FaqSection> Sections
  810. {
  811. get { return base.Sections; }
  812. set { base.Sections = value; }
  813. }
  814. }
  815. [Test]
  816. public void SerializeMetadataType2()
  817. {
  818. FaqItem c = new FaqItem()
  819. {
  820. FaqId = 1,
  821. Sections =
  822. {
  823. new FaqSection()
  824. }
  825. };
  826. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  827. StringAssert.AreEqual(@"{
  828. ""FaqId"": 1,
  829. ""Name"": null,
  830. ""IsDeleted"": false,
  831. ""FullSectionsProp"": [
  832. {}
  833. ]
  834. }", json);
  835. FaqItem c2 = JsonConvert.DeserializeObject<FaqItem>(json);
  836. Assert.AreEqual(1, c2.FaqId);
  837. Assert.AreEqual(1, c2.Sections.Count);
  838. }
  839. [Test]
  840. public void SerializeMetadataTypeInheritance()
  841. {
  842. FaqItemProxy c = new FaqItemProxy();
  843. c.FaqId = 1;
  844. c.Sections.Add(new FaqSection());
  845. c.IsProxy = true;
  846. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  847. StringAssert.AreEqual(@"{
  848. ""IsProxy"": true,
  849. ""FaqId"": 1,
  850. ""Name"": null,
  851. ""IsDeleted"": false,
  852. ""FullSectionsProp"": [
  853. {}
  854. ]
  855. }", json);
  856. FaqItemProxy c2 = JsonConvert.DeserializeObject<FaqItemProxy>(json);
  857. Assert.AreEqual(1, c2.FaqId);
  858. Assert.AreEqual(1, c2.Sections.Count);
  859. }
  860. #endif
  861. public class NullTestClass
  862. {
  863. public JObject Value1 { get; set; }
  864. public JValue Value2 { get; set; }
  865. public JRaw Value3 { get; set; }
  866. public JToken Value4 { get; set; }
  867. public object Value5 { get; set; }
  868. }
  869. [Test]
  870. public void DeserializeNullToJTokenProperty()
  871. {
  872. NullTestClass otc = JsonConvert.DeserializeObject<NullTestClass>(@"{
  873. ""Value1"": null,
  874. ""Value2"": null,
  875. ""Value3"": null,
  876. ""Value4"": null,
  877. ""Value5"": null
  878. }");
  879. Assert.IsNull(otc.Value1);
  880. Assert.AreEqual(JTokenType.Null, otc.Value2.Type);
  881. Assert.AreEqual(JTokenType.Raw, otc.Value3.Type);
  882. Assert.AreEqual(JTokenType.Null, otc.Value4.Type);
  883. Assert.IsNull(otc.Value5);
  884. }
  885. public class Link
  886. {
  887. /// <summary>
  888. /// The unique identifier.
  889. /// </summary>
  890. public int Id;
  891. /// <summary>
  892. /// The parent information identifier.
  893. /// </summary>
  894. public int ParentId;
  895. /// <summary>
  896. /// The child information identifier.
  897. /// </summary>
  898. public int ChildId;
  899. }
  900. #if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
  901. [Test]
  902. public void ReadIntegerWithError()
  903. {
  904. string json = @"{
  905. ParentId: 1,
  906. ChildId: 333333333333333333333333333333333333333
  907. }";
  908. Link l = JsonConvert.DeserializeObject<Link>(json, new JsonSerializerSettings
  909. {
  910. Error = (s, a) => a.ErrorContext.Handled = true
  911. });
  912. Assert.AreEqual(0, l.ChildId);
  913. }
  914. #endif
  915. #if !(NET20 || NET35)
  916. [Test]
  917. public void DeserializeObservableCollection()
  918. {
  919. ObservableCollection<string> s = JsonConvert.DeserializeObject<ObservableCollection<string>>("['1','2']");
  920. Assert.AreEqual(2, s.Count);
  921. Assert.AreEqual("1", s[0]);
  922. Assert.AreEqual("2", s[1]);
  923. }
  924. #endif
  925. [Test]
  926. public void DeserializeBoolAsStringInDictionary()
  927. {
  928. Dictionary<string, string> d = JsonConvert.DeserializeObject<Dictionary<string, string>>("{\"Test1\":false}");
  929. Assert.AreEqual(1, d.Count);
  930. Assert.AreEqual("false", d["Test1"]);
  931. }
  932. #if !NET20
  933. [Test]
  934. public void PopulateResetSettings()
  935. {
  936. JsonTextReader reader = new JsonTextReader(new StringReader(@"[""2000-01-01T01:01:01+00:00""]"));
  937. Assert.AreEqual(DateParseHandling.DateTime, reader.DateParseHandling);
  938. JsonSerializer serializer = new JsonSerializer();
  939. serializer.DateParseHandling = DateParseHandling.DateTimeOffset;
  940. IList<object> l = new List<object>();
  941. serializer.Populate(reader, l);
  942. Assert.AreEqual(typeof(DateTimeOffset), l[0].GetType());
  943. Assert.AreEqual(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero), l[0]);
  944. Assert.AreEqual(DateParseHandling.DateTime, reader.DateParseHandling);
  945. }
  946. #endif
  947. public class BaseClass
  948. {
  949. internal bool IsTransient { get; set; }
  950. }
  951. public class ChildClass : BaseClass
  952. {
  953. public new bool IsTransient { get; set; }
  954. }
  955. [Test]
  956. public void NewProperty()
  957. {
  958. Assert.AreEqual(@"{""IsTransient"":true}", JsonConvert.SerializeObject(new ChildClass { IsTransient = true }));
  959. var childClass = JsonConvert.DeserializeObject<ChildClass>(@"{""IsTransient"":true}");
  960. Assert.AreEqual(true, childClass.IsTransient);
  961. }
  962. public class BaseClassVirtual
  963. {
  964. internal virtual bool IsTransient { get; set; }
  965. }
  966. public class ChildClassVirtual : BaseClassVirtual
  967. {
  968. public new virtual bool IsTransient { get; set; }
  969. }
  970. [Test]
  971. public void NewPropertyVirtual()
  972. {
  973. Assert.AreEqual(@"{""IsTransient"":true}", JsonConvert.SerializeObject(new ChildClassVirtual { IsTransient = true }));
  974. var childClass = JsonConvert.DeserializeObject<ChildClassVirtual>(@"{""IsTransient"":true}");
  975. Assert.AreEqual(true, childClass.IsTransient);
  976. }
  977. public class ResponseWithNewGenericProperty<T> : SimpleResponse
  978. {
  979. public new T Data { get; set; }
  980. }
  981. public class ResponseWithNewGenericPropertyVirtual<T> : SimpleResponse
  982. {
  983. public new virtual T Data { get; set; }
  984. }
  985. public class ResponseWithNewGenericPropertyOverride<T> : ResponseWithNewGenericPropertyVirtual<T>
  986. {
  987. public override T Data { get; set; }
  988. }
  989. public abstract class SimpleResponse
  990. {
  991. public string Result { get; set; }
  992. public string Message { get; set; }
  993. public object Data { get; set; }
  994. protected SimpleResponse()
  995. {
  996. }
  997. protected SimpleResponse(string message)
  998. {
  999. Message = message;
  1000. }
  1001. }
  1002. [Test]
  1003. public void CanSerializeWithBuiltInTypeAsGenericArgument()
  1004. {
  1005. var input = new ResponseWithNewGenericProperty<int>()
  1006. {
  1007. Message = "Trying out integer as type parameter",
  1008. Data = 25,
  1009. Result = "This should be fine"
  1010. };
  1011. var json = JsonConvert.SerializeObject(input);
  1012. var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericProperty<int>>(json);
  1013. Assert.AreEqual(input.Data, deserialized.Data);
  1014. Assert.AreEqual(input.Message, deserialized.Message);
  1015. Assert.AreEqual(input.Result, deserialized.Result);
  1016. }
  1017. [Test]
  1018. public void CanSerializeWithBuiltInTypeAsGenericArgumentVirtual()
  1019. {
  1020. var input = new ResponseWithNewGenericPropertyVirtual<int>()
  1021. {
  1022. Message = "Trying out integer as type parameter",
  1023. Data = 25,
  1024. Result = "This should be fine"
  1025. };
  1026. var json = JsonConvert.SerializeObject(input);
  1027. var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericPropertyVirtual<int>>(json);
  1028. Assert.AreEqual(input.Data, deserialized.Data);
  1029. Assert.AreEqual(input.Message, deserialized.Message);
  1030. Assert.AreEqual(input.Result, deserialized.Result);
  1031. }
  1032. [Test]
  1033. public void CanSerializeWithBuiltInTypeAsGenericArgumentOverride()
  1034. {
  1035. var input = new ResponseWithNewGenericPropertyOverride<int>()
  1036. {
  1037. Message = "Trying out integer as type parameter",
  1038. Data = 25,
  1039. Result = "This should be fine"
  1040. };
  1041. var json = JsonConvert.SerializeObject(input);
  1042. var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericPropertyOverride<int>>(json);
  1043. Assert.AreEqual(input.Data, deserialized.Data);
  1044. Assert.AreEqual(input.Message, deserialized.Message);
  1045. Assert.AreEqual(input.Result, deserialized.Result);
  1046. }
  1047. [Test]
  1048. public void CanSerializedWithGenericClosedTypeAsArgument()
  1049. {
  1050. var input = new ResponseWithNewGenericProperty<List<int>>()
  1051. {
  1052. Message = "More complex case - generic list of int",
  1053. Data = Enumerable.Range(50, 70).ToList(),
  1054. Result = "This should be fine too"
  1055. };
  1056. var json = JsonConvert.SerializeObject(input);
  1057. var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericProperty<List<int>>>(json);
  1058. CollectionAssert.AreEqual(input.Data, deserialized.Data);
  1059. Assert.AreEqual(input.Message, deserialized.Message);
  1060. Assert.AreEqual(input.Result, deserialized.Result);
  1061. }
  1062. [Test]
  1063. public void DeserializeVersionString()
  1064. {
  1065. string json = "['1.2.3.4']";
  1066. List<Version> deserialized = JsonConvert.DeserializeObject<List<Version>>(json);
  1067. Assert.AreEqual(1, deserialized[0].Major);
  1068. Assert.AreEqual(2, deserialized[0].Minor);
  1069. Assert.AreEqual(3, deserialized[0].Build);
  1070. Assert.AreEqual(4, deserialized[0].Revision);
  1071. }
  1072. [Test]
  1073. public void DeserializeVersionString_Fail()
  1074. {
  1075. string json = "['1.2.3.4444444444444444444444']";
  1076. 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.");
  1077. }
  1078. [Test]
  1079. public void DeserializeJObjectWithComments()
  1080. {
  1081. string json = @"/* Test */
  1082. {
  1083. /*Test*/""A"":/* Test */true/* Test */,
  1084. /* Test */""B"":/* Test */false/* Test */,
  1085. /* Test */""C"":/* Test */[
  1086. /* Test */
  1087. 1/* Test */
  1088. ]/* Test */
  1089. }
  1090. /* Test */";
  1091. JObject o = (JObject)JsonConvert.DeserializeObject(json);
  1092. Assert.AreEqual(3, o.Count);
  1093. Assert.AreEqual(true, (bool)o["A"]);
  1094. Assert.AreEqual(false, (bool)o["B"]);
  1095. Assert.AreEqual(1, o["C"].Count());
  1096. Assert.AreEqual(1, (int)o["C"][0]);
  1097. Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
  1098. json = @"{/* Test */}";
  1099. o = (JObject)JsonConvert.DeserializeObject(json);
  1100. Assert.AreEqual(0, o.Count);
  1101. Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
  1102. json = @"{""A"": true/* Test */}";
  1103. o = (JObject)JsonConvert.DeserializeObject(json);
  1104. Assert.AreEqual(1, o.Count);
  1105. Assert.AreEqual(true, (bool)o["A"]);
  1106. Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
  1107. }
  1108. public class CommentTestObject
  1109. {
  1110. public bool? A { get; set; }
  1111. }
  1112. [Test]
  1113. public void DeserializeCommentTestObjectWithComments()
  1114. {
  1115. CommentTestObject o = JsonConvert.DeserializeObject<CommentTestObject>(@"{/* Test */}");
  1116. Assert.AreEqual(null, o.A);
  1117. o = JsonConvert.DeserializeObject<CommentTestObject>(@"{""A"": true/* Test */}");
  1118. Assert.AreEqual(true, o.A);
  1119. }
  1120. [Test]
  1121. public void JsonSerializerProperties()
  1122. {
  1123. JsonSerializer serializer = new JsonSerializer();
  1124. DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
  1125. #pragma warning disable CS0618 // Type or member is obsolete
  1126. serializer.Binder = customBinder;
  1127. Assert.AreEqual(customBinder, serializer.Binder);
  1128. #pragma warning restore CS0618 // Type or member is obsolete
  1129. Assert.IsInstanceOf(typeof(DefaultSerializationBinder), serializer.SerializationBinder);
  1130. serializer.SerializationBinder = customBinder;
  1131. Assert.AreEqual(customBinder, serializer.SerializationBinder);
  1132. #pragma warning disable CS0618 // Type or member is obsolete
  1133. // can still fetch because DefaultSerializationBinder inherits from SerializationBinder
  1134. Assert.AreEqual(customBinder, serializer.Binder);
  1135. #pragma warning restore CS0618 // Type or member is obsolete
  1136. serializer.CheckAdditionalContent = true;
  1137. Assert.AreEqual(true, serializer.CheckAdditionalContent);
  1138. serializer.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
  1139. Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, serializer.ConstructorHandling);
  1140. #if !(DNXCORE50)
  1141. serializer.Context = new StreamingContext(StreamingContextStates.Other);
  1142. Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), serializer.Context);
  1143. #endif
  1144. CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
  1145. serializer.ContractResolver = resolver;
  1146. Assert.AreEqual(resolver, serializer.ContractResolver);
  1147. serializer.Converters.Add(new StringEnumConverter());
  1148. Assert.AreEqual(1, serializer.Converters.Count);
  1149. serializer.Culture = new CultureInfo("en-nz");
  1150. Assert.AreEqual("en-NZ", serializer.Culture.ToString());
  1151. serializer.EqualityComparer = EqualityComparer<object>.Default;
  1152. Assert.AreEqual(EqualityComparer<object>.Default, serializer.EqualityComparer);
  1153. serializer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
  1154. Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, serializer.DateFormatHandling);
  1155. serializer.DateFormatString = "yyyy";
  1156. Assert.AreEqual("yyyy", serializer.DateFormatString);
  1157. serializer.DateParseHandling = DateParseHandling.None;
  1158. Assert.AreEqual(DateParseHandling.None, serializer.DateParseHandling);
  1159. serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
  1160. Assert.AreEqual(DateTimeZoneHandling.Utc, serializer.DateTimeZoneHandling);
  1161. serializer.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
  1162. Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, serializer.DefaultValueHandling);
  1163. serializer.FloatFormatHandling = FloatFormatHandling.Symbol;
  1164. Assert.AreEqual(FloatFormatHandling.Symbol, serializer.FloatFormatHandling);
  1165. serializer.FloatParseHandling = FloatParseHandling.Decimal;
  1166. Assert.AreEqual(FloatParseHandling.Decimal, serializer.FloatParseHandling);
  1167. serializer.Formatting = Formatting.Indented;
  1168. Assert.AreEqual(Formatting.Indented, serializer.Formatting);
  1169. serializer.MaxDepth = 9001;
  1170. Assert.AreEqual(9001, serializer.MaxDepth);
  1171. serializer.MissingMemberHandling = MissingMemberHandling.Error;
  1172. Assert.AreEqual(MissingMemberHandling.Error, serializer.MissingMemberHandling);
  1173. serializer.NullValueHandling = NullValueHandling.Ignore;
  1174. Assert.AreEqual(NullValueHandling.Ignore, serializer.NullValueHandling);
  1175. serializer.ObjectCreationHandling = ObjectCreationHandling.Replace;
  1176. Assert.AreEqual(ObjectCreationHandling.Replace, serializer.ObjectCreationHandling);
  1177. serializer.PreserveReferencesHandling = PreserveReferencesHandling.All;
  1178. Assert.AreEqual(PreserveReferencesHandling.All, serializer.PreserveReferencesHandling);
  1179. serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  1180. Assert.AreEqual(ReferenceLoopHandling.Ignore, serializer.ReferenceLoopHandling);
  1181. IdReferenceResolver referenceResolver = new IdReferenceResolver();
  1182. serializer.ReferenceResolver = referenceResolver;
  1183. Assert.AreEqual(referenceResolver, serializer.ReferenceResolver);
  1184. serializer.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
  1185. Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, serializer.StringEscapeHandling);
  1186. MemoryTraceWriter traceWriter = new MemoryTraceWriter();
  1187. serializer.TraceWriter = traceWriter;
  1188. Assert.AreEqual(traceWriter, serializer.TraceWriter);
  1189. #if !(PORTABLE || PORTABLE40 || NET20 || DNXCORE50)
  1190. #pragma warning disable 618
  1191. serializer.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
  1192. Assert.AreEqual(FormatterAssemblyStyle.Full, serializer.TypeNameAssemblyFormat);
  1193. #pragma warning restore 618
  1194. Assert.AreEqual(TypeNameAssemblyFormatHandling.Full, serializer.TypeNameAssemblyFormatHandling);
  1195. serializer.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple;
  1196. #pragma warning disable 618
  1197. Assert.AreEqual(FormatterAssemblyStyle.Simple, serializer.TypeNameAssemblyFormat);
  1198. #pragma warning restore 618
  1199. #endif

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