PageRenderTime 84ms CodeModel.GetById 7ms app.highlight 49ms RepoModel.GetById 1ms app.codeStats 2ms

/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
  26using System;
  27using System.ComponentModel;
  28#if !(NET35 || NET20)
  29using System.Collections.Concurrent;
  30#endif
  31using System.Collections.Generic;
  32#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
  33using System.Numerics;
  34#endif
  35#if !(NET20 || DNXCORE50)
  36using System.ComponentModel.DataAnnotations;
  37using System.Configuration;
  38using System.Runtime.CompilerServices;
  39using System.Runtime.Serialization.Formatters;
  40using System.Threading;
  41using System.Web.Script.Serialization;
  42#endif
  43using System.Text;
  44using System.Text.RegularExpressions;
  45#if DNXCORE50
  46using Xunit;
  47using Test = Xunit.FactAttribute;
  48using Assert = Newtonsoft.Json.Tests.XUnitAssert;
  49#else
  50using NUnit.Framework;
  51#endif
  52using Newtonsoft.Json;
  53using System.IO;
  54using System.Collections;
  55using System.Xml;
  56using System.Xml.Serialization;
  57using System.Collections.ObjectModel;
  58using System.Diagnostics;
  59using Newtonsoft.Json.Bson;
  60using Newtonsoft.Json.Linq;
  61using Newtonsoft.Json.Converters;
  62#if !(NET20 || NET35)
  63using System.Runtime.Serialization.Json;
  64#endif
  65using Newtonsoft.Json.Serialization;
  66using Newtonsoft.Json.Tests.Linq;
  67using Newtonsoft.Json.Tests.TestObjects;
  68using Newtonsoft.Json.Tests.TestObjects.Events;
  69using Newtonsoft.Json.Tests.TestObjects.GeoCoding;
  70using Newtonsoft.Json.Tests.TestObjects.Organization;
  71using System.Runtime.Serialization;
  72using System.Globalization;
  73using Newtonsoft.Json.Utilities;
  74using System.Reflection;
  75#if !NET20
  76using System.Xml.Linq;
  77using System.Collections.Specialized;
  78using System.Linq.Expressions;
  79#endif
  80#if !(NET35 || NET20)
  81using System.Dynamic;
  82#endif
  83#if NET20
  84using Newtonsoft.Json.Utilities.LinqBridge;
  85using Action = Newtonsoft.Json.Serialization.Action;
  86#else
  87using System.Linq;
  88#endif
  89#if !(DNXCORE50)
  90using System.Drawing;
  91
  92#endif
  93
  94namespace Newtonsoft.Json.Tests.Serialization
  95{
  96    [TestFixture]
  97    public class JsonSerializerTest : TestFixtureBase
  98    {
  99        public struct ImmutableStruct
 100        {
 101            public ImmutableStruct(string value)
 102            {
 103                Value = value;
 104                Value2 = 0;
 105            }
 106
 107            public string Value { get; }
 108            public int Value2 { get; set; }
 109        }
 110
 111        [Test]
 112        public void DeserializeImmutableStruct()
 113        {
 114            var result = JsonConvert.DeserializeObject<ImmutableStruct>("{ \"Value\": \"working\", \"Value2\": 2 }");
 115
 116            Assert.AreEqual("working", result.Value);
 117            Assert.AreEqual(2, result.Value2);
 118        }
 119
 120        public struct AlmostImmutableStruct
 121        {
 122            public AlmostImmutableStruct(string value, int value2)
 123            {
 124                Value = value;
 125                Value2 = value2;
 126            }
 127
 128            public string Value { get; }
 129            public int Value2 { get; set; }
 130        }
 131
 132        [Test]
 133        public void DeserializeAlmostImmutableStruct()
 134        {
 135            var result = JsonConvert.DeserializeObject<AlmostImmutableStruct>("{ \"Value\": \"working\", \"Value2\": 2 }");
 136
 137            Assert.AreEqual(null, result.Value);
 138            Assert.AreEqual(2, result.Value2);
 139        }
 140
 141        public class ErroringClass
 142        {
 143            public DateTime Tags { get; set; }
 144        }
 145
 146        [Test]
 147        public void DontCloseInputOnDeserializeError()
 148        {
 149            using (var s = System.IO.File.OpenRead("large.json"))
 150            {
 151                try
 152                {
 153                    using (JsonTextReader reader = new JsonTextReader(new StreamReader(s)))
 154                    {
 155                        reader.SupportMultipleContent = true;
 156                        reader.CloseInput = false;
 157
 158                        // read into array
 159                        reader.Read();
 160
 161                        var ser = new JsonSerializer();
 162                        ser.CheckAdditionalContent = false;
 163
 164                        ser.Deserialize<IList<ErroringClass>>(reader);
 165                    }
 166
 167                    Assert.Fail();
 168                }
 169                catch (Exception)
 170                {
 171                    Assert.IsTrue(s.Position > 0);
 172
 173                    s.Seek(0, SeekOrigin.Begin);
 174
 175                    Assert.AreEqual(0, s.Position);
 176                }
 177            }
 178        }
 179
 180        public interface ISubclassBase
 181        {
 182            int ID { get; set; }
 183            string Name { get; set; }
 184            bool P1 { get; }
 185        }
 186
 187        public interface ISubclass : ISubclassBase
 188        {
 189            new bool P1 { get; set; }
 190            int P2 { get; set; }
 191        }
 192
 193        public interface IMainClass
 194        {
 195            int ID { get; set; }
 196            string Name { get; set; }
 197            ISubclass Subclass { get; set; }
 198        }
 199
 200        public class Subclass : ISubclass
 201        {
 202            public int ID { get; set; }
 203            public string Name { get; set; }
 204            public bool P1 { get; set; }
 205            public int P2 { get; set; }
 206        }
 207
 208        public class MainClass : IMainClass
 209        {
 210            public int ID { get; set; }
 211            public string Name { get; set; }
 212            public ISubclass Subclass { get; set; }
 213        }
 214
 215        public class MyFactory
 216        {
 217            public static ISubclass InstantiateSubclass()
 218            {
 219                return new Subclass
 220                {
 221                    ID = 123,
 222                    Name = "ABC",
 223                    P1 = true,
 224                    P2 = 44
 225                };
 226            }
 227
 228            public static IMainClass InstantiateManiClass()
 229            {
 230                return new MainClass
 231                {
 232                    ID = 567,
 233                    Name = "XYZ",
 234                    Subclass = InstantiateSubclass()
 235                };
 236            }
 237        }
 238
 239        [Test]
 240        public void SerializeInterfaceWithHiddenProperties()
 241        {
 242            var mySubclass = MyFactory.InstantiateSubclass();
 243            var myMainClass = MyFactory.InstantiateManiClass();
 244
 245            //Class implementing interface with hidden members - flat object. 
 246            var strJsonSubclass = JsonConvert.SerializeObject(mySubclass, Formatting.Indented);
 247
 248            StringAssert.AreEqual(@"{
 249  ""ID"": 123,
 250  ""Name"": ""ABC"",
 251  ""P1"": true,
 252  ""P2"": 44
 253}", strJsonSubclass);
 254
 255            //Class implementing interface with hidden members - member of another class. 
 256            var strJsonMainClass = JsonConvert.SerializeObject(myMainClass, Formatting.Indented);
 257
 258            StringAssert.AreEqual(@"{
 259  ""ID"": 567,
 260  ""Name"": ""XYZ"",
 261  ""Subclass"": {
 262    ""ID"": 123,
 263    ""Name"": ""ABC"",
 264    ""P1"": true,
 265    ""P2"": 44
 266  }
 267}", strJsonMainClass);
 268        }
 269
 270        [Test]
 271        public void DeserializeGenericIEnumerableWithImplicitConversion()
 272        {
 273            string deserialized = @"{
 274  ""Enumerable"": [ ""abc"", ""def"" ] 
 275}";
 276            var enumerableClass = JsonConvert.DeserializeObject<GenericIEnumerableWithImplicitConversion>(deserialized);
 277            var enumerableObject = enumerableClass.Enumerable.ToArray();
 278            Assert.AreEqual(2, enumerableObject.Length);
 279            Assert.AreEqual("abc", enumerableObject[0].Value);
 280            Assert.AreEqual("def", enumerableObject[1].Value);
 281        }
 282
 283        public class GenericIEnumerableWithImplicitConversion
 284        {
 285            public IEnumerable<ClassWithImplicitOperator> Enumerable { get; set; }
 286        }
 287
 288        public class ClassWithImplicitOperator
 289        {
 290            public string Value { get; set; }
 291
 292            public static implicit operator ClassWithImplicitOperator(string value)
 293            {
 294                return new ClassWithImplicitOperator() { Value = value };
 295            }
 296        }
 297
 298#if !(PORTABLE || PORTABLE40 || NET20 || NET35)
 299        [Test]
 300        public void LargeIntegerAsString()
 301        {
 302            var largeBrokenNumber = JsonConvert.DeserializeObject<Foo64>("{\"Blah\": 43443333222211111117 }");
 303            Assert.AreEqual("43443333222211111117", largeBrokenNumber.Blah);
 304
 305            var largeOddWorkingNumber = JsonConvert.DeserializeObject<Foo64>("{\"Blah\": 53443333222211111117 }");
 306            Assert.AreEqual("53443333222211111117", largeOddWorkingNumber.Blah);
 307        }
 308
 309        public class Foo64
 310        {
 311            public string Blah { get; set; }
 312        }
 313#endif
 314
 315#if !NET20
 316        [Test]
 317        public void DeserializeMSDateTimeOffset()
 318        {
 319            DateTimeOffset d = JsonConvert.DeserializeObject<DateTimeOffset>(@"""/Date(1418924498000+0800)/""");
 320            long initialTicks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(d.DateTime, d.Offset);
 321
 322            Assert.AreEqual(1418924498000, initialTicks);
 323            Assert.AreEqual(8, d.Offset.Hours);
 324        }
 325#endif
 326
 327        [Test]
 328        public void DeserializeBoolean_Null()
 329        {
 330            ExceptionAssert.Throws<JsonSerializationException>(
 331                () => JsonConvert.DeserializeObject<IList<bool>>(@"[null]"),
 332                "Error converting value {null} to type 'System.Boolean'. Path '[0]', line 1, position 5.");
 333        }
 334
 335        [Test]
 336        public void DeserializeBoolean_DateTime()
 337        {
 338            ExceptionAssert.Throws<JsonReaderException>(
 339                () => JsonConvert.DeserializeObject<IList<bool>>(@"['2000-12-20T10:55:55Z']"),
 340                "Could not convert string to boolean: 2000-12-20T10:55:55Z. Path '[0]', line 1, position 23.");
 341        }
 342
 343        [Test]
 344        public void DeserializeBoolean_BadString()
 345        {
 346            ExceptionAssert.Throws<JsonReaderException>(
 347                () => JsonConvert.DeserializeObject<IList<bool>>(@"['pie']"),
 348                @"Could not convert string to boolean: pie. Path '[0]', line 1, position 6.");
 349        }
 350
 351        [Test]
 352        public void DeserializeBoolean_EmptyString()
 353        {
 354            ExceptionAssert.Throws<JsonSerializationException>(
 355                () => JsonConvert.DeserializeObject<IList<bool>>(@"['']"),
 356                @"Error converting value {null} to type 'System.Boolean'. Path '[0]', line 1, position 3.");
 357        }
 358
 359#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
 360        [Test]
 361        public void DeserializeBooleans()
 362        {
 363            IList<bool> l = JsonConvert.DeserializeObject<IList<bool>>(@"[
 364  1,
 365  0,
 366  1.1,
 367  0.0,
 368  0.000000000001,
 369  9999999999,
 370  -9999999999,
 371  9999999999999999999999999999999999999999999999999999999999999999999999,
 372  -9999999999999999999999999999999999999999999999999999999999999999999999,
 373  'true',
 374  'TRUE',
 375  'false',
 376  'FALSE'
 377]");
 378
 379            int i = 0;
 380            Assert.AreEqual(true, l[i++]);
 381            Assert.AreEqual(false, l[i++]);
 382            Assert.AreEqual(true, l[i++]);
 383            Assert.AreEqual(false, l[i++]);
 384            Assert.AreEqual(true, l[i++]);
 385            Assert.AreEqual(true, l[i++]);
 386            Assert.AreEqual(true, l[i++]);
 387            Assert.AreEqual(true, l[i++]);
 388            Assert.AreEqual(true, l[i++]);
 389            Assert.AreEqual(true, l[i++]);
 390            Assert.AreEqual(true, l[i++]);
 391            Assert.AreEqual(false, l[i++]);
 392            Assert.AreEqual(false, l[i++]);
 393        }
 394
 395        [Test]
 396        public void DeserializeNullableBooleans()
 397        {
 398            IList<bool?> l = JsonConvert.DeserializeObject<IList<bool?>>(@"[
 399  1,
 400  0,
 401  1.1,
 402  0.0,
 403  0.000000000001,
 404  9999999999,
 405  -9999999999,
 406  9999999999999999999999999999999999999999999999999999999999999999999999,
 407  -9999999999999999999999999999999999999999999999999999999999999999999999,
 408  'true',
 409  'TRUE',
 410  'false',
 411  'FALSE',
 412  '',
 413  null
 414]");
 415
 416            int i = 0;
 417            Assert.AreEqual(true, l[i++]);
 418            Assert.AreEqual(false, l[i++]);
 419            Assert.AreEqual(true, l[i++]);
 420            Assert.AreEqual(false, l[i++]);
 421            Assert.AreEqual(true, l[i++]);
 422            Assert.AreEqual(true, l[i++]);
 423            Assert.AreEqual(true, l[i++]);
 424            Assert.AreEqual(true, l[i++]);
 425            Assert.AreEqual(true, l[i++]);
 426            Assert.AreEqual(true, l[i++]);
 427            Assert.AreEqual(true, l[i++]);
 428            Assert.AreEqual(false, l[i++]);
 429            Assert.AreEqual(false, l[i++]);
 430            Assert.AreEqual(null, l[i++]);
 431            Assert.AreEqual(null, l[i++]);
 432        }
 433#endif
 434
 435        [Test]
 436        public void CaseInsensitiveRequiredPropertyConstructorCreation()
 437        {
 438            FooRequired foo1 = new FooRequired(new[] { "A", "B", "C" });
 439            string json = JsonConvert.SerializeObject(foo1);
 440
 441            StringAssert.AreEqual(@"{""Bars"":[""A"",""B"",""C""]}", json);
 442
 443            FooRequired foo2 = JsonConvert.DeserializeObject<FooRequired>(json);
 444            Assert.AreEqual(foo1.Bars.Count, foo2.Bars.Count);
 445            Assert.AreEqual(foo1.Bars[0], foo2.Bars[0]);
 446            Assert.AreEqual(foo1.Bars[1], foo2.Bars[1]);
 447            Assert.AreEqual(foo1.Bars[2], foo2.Bars[2]);
 448        }
 449
 450        public class FooRequired
 451        {
 452            [JsonProperty(Required = Required.Always)]
 453            public List<string> Bars { get; private set; }
 454
 455            public FooRequired(IEnumerable<string> bars)
 456            {
 457                Bars = new List<string>();
 458                if (bars != null)
 459                {
 460                    Bars.AddRange(bars);
 461                }
 462            }
 463        }
 464
 465        [Test]
 466        public void CoercedEmptyStringWithRequired()
 467        {
 468            ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Binding>("{requiredProperty:''}"); }, "Required property 'RequiredProperty' expects a value but got null. Path '', line 1, position 21.");
 469        }
 470
 471        [Test]
 472        public void CoercedEmptyStringWithRequired_DisallowNull()
 473        {
 474            ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Binding_DisallowNull>("{requiredProperty:''}"); }, "Required property 'RequiredProperty' expects a non-null value. Path '', line 1, position 21.");
 475        }
 476
 477        [Test]
 478        public void DisallowNull_NoValue()
 479        {
 480            Binding_DisallowNull o = JsonConvert.DeserializeObject<Binding_DisallowNull>("{}");
 481            Assert.IsNull(o.RequiredProperty);
 482        }
 483
 484        [Test]
 485        public void CoercedEmptyStringWithRequiredConstructor()
 486        {
 487            ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<FooRequired>("{Bars:''}"); }, "Required property 'Bars' expects a value but got null. Path '', line 1, position 9.");
 488        }
 489
 490        public class IgnoredProperty
 491        {
 492            [JsonIgnore]
 493            [JsonProperty(Required = Required.Always)]
 494            public string StringProp1 { get; set; }
 495
 496            [JsonIgnore]
 497            public string StringProp2 { get; set; }
 498        }
 499
 500        [Test]
 501        public void NoErrorWhenValueDoesNotMatchIgnoredProperty()
 502        {
 503            IgnoredProperty p = JsonConvert.DeserializeObject<IgnoredProperty>("{'StringProp1':[1,2,3],'StringProp2':{}}");
 504            Assert.IsNull(p.StringProp1);
 505            Assert.IsNull(p.StringProp2);
 506        }
 507
 508        public class Binding
 509        {
 510            [JsonProperty(Required = Required.Always)]
 511            public Binding RequiredProperty { get; set; }
 512        }
 513
 514        public class Binding_DisallowNull
 515        {
 516            [JsonProperty(Required = Required.DisallowNull)]
 517            public Binding RequiredProperty { get; set; }
 518        }
 519
 520        [Test]
 521        public void Serialize_Required_DisallowedNull()
 522        {
 523            ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.SerializeObject(new Binding_DisallowNull()); }, "Cannot write a null value for property 'RequiredProperty'. Property requires a non-null value. Path ''.");
 524        }
 525
 526        [Test]
 527        public void Serialize_Required_DisallowedNull_NullValueHandlingIgnore()
 528        {
 529            string json = JsonConvert.SerializeObject(new Binding_DisallowNull(), new JsonSerializerSettings
 530            {
 531                NullValueHandling = NullValueHandling.Ignore
 532            });
 533            Assert.AreEqual("{}", json);
 534        }
 535
 536        [JsonObject(ItemRequired = Required.DisallowNull)]
 537        public class DictionaryWithNoNull
 538        {
 539            public string Name { get; set; }
 540        }
 541
 542        [Test]
 543        public void Serialize_ItemRequired_DisallowedNull()
 544        {
 545            ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.SerializeObject(new DictionaryWithNoNull()); }, "Cannot write a null value for property 'Name'. Property requires a non-null value. Path ''.");
 546        }
 547
 548        public class DictionaryKeyContractResolver : DefaultContractResolver
 549        {
 550            protected override string ResolveDictionaryKey(string dictionaryKey)
 551            {
 552                return dictionaryKey;
 553            }
 554
 555            protected override string ResolvePropertyName(string propertyName)
 556            {
 557#if DNXCORE50
 558                return propertyName.ToUpperInvariant();
 559#else
 560                return propertyName.ToUpper(CultureInfo.InvariantCulture);
 561#endif
 562            }
 563        }
 564
 565        [Test]
 566        public void DictionaryKeyContractResolverTest()
 567        {
 568            var person = new
 569            {
 570                Name = "James",
 571                Age = 1,
 572                RoleNames = new Dictionary<string, bool>
 573                {
 574                    { "IsAdmin", true },
 575                    { "IsModerator", false }
 576                }
 577            };
 578
 579            string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
 580            {
 581                ContractResolver = new DictionaryKeyContractResolver()
 582            });
 583
 584            Assert.AreEqual(@"{
 585  ""NAME"": ""James"",
 586  ""AGE"": 1,
 587  ""ROLENAMES"": {
 588    ""IsAdmin"": true,
 589    ""IsModerator"": false
 590  }
 591}", json);
 592        }
 593
 594        [Test]
 595        public void IncompleteContainers()
 596        {
 597            ExceptionAssert.Throws<JsonSerializationException>(
 598                () => JsonConvert.DeserializeObject<IList<object>>("[1,"),
 599                "Unexpected end when deserializing array. Path '[0]', line 1, position 3.");
 600
 601            ExceptionAssert.Throws<JsonSerializationException>(
 602                () => JsonConvert.DeserializeObject<IList<int>>("[1,"),
 603                "Unexpected end when deserializing array. Path '[0]', line 1, position 3.");
 604
 605            ExceptionAssert.Throws<JsonSerializationException>(
 606                () => JsonConvert.DeserializeObject<IList<int>>("[1"),
 607                "Unexpected end when deserializing array. Path '[0]', line 1, position 2.");
 608
 609            ExceptionAssert.Throws<JsonSerializationException>(
 610                () => JsonConvert.DeserializeObject<IDictionary<string, int>>("{'key':1,"),
 611                "Unexpected end when deserializing object. Path 'key', line 1, position 9.");
 612
 613            ExceptionAssert.Throws<JsonSerializationException>(
 614                () => JsonConvert.DeserializeObject<IDictionary<string, int>>("{'key':1"),
 615                "Unexpected end when deserializing object. Path 'key', line 1, position 8.");
 616
 617            ExceptionAssert.Throws<JsonSerializationException>(
 618                () => JsonConvert.DeserializeObject<IncompleteTestClass>("{'key':1,"),
 619                "Unexpected end when deserializing object. Path 'key', line 1, position 9.");
 620
 621            ExceptionAssert.Throws<JsonSerializationException>(
 622                () => JsonConvert.DeserializeObject<IncompleteTestClass>("{'key':1"),
 623                "Unexpected end when deserializing object. Path 'key', line 1, position 8.");
 624        }
 625
 626        public class IncompleteTestClass
 627        {
 628            public int Key { get; set; }
 629        }
 630
 631#if !NET20
 632        public enum EnumA
 633        {
 634            [EnumMember(Value = "value_a")]
 635            ValueA
 636        }
 637
 638        [Test]
 639        public void DeserializeEnumsByName()
 640        {
 641            var e1 = JsonConvert.DeserializeObject<EnumA>("'ValueA'");
 642            Assert.AreEqual(EnumA.ValueA, e1);
 643
 644            var e2 = JsonConvert.DeserializeObject<EnumA>("'value_a'", new StringEnumConverter());
 645            Assert.AreEqual(EnumA.ValueA, e2);
 646        }
 647#endif
 648
 649        public class RequiredPropertyTestClass
 650        {
 651            [JsonRequired]
 652            internal string Name { get; set; }
 653        }
 654
 655        [Test]
 656        public void RequiredPropertyTest()
 657        {
 658            RequiredPropertyTestClass c1 = new RequiredPropertyTestClass();
 659
 660            ExceptionAssert.Throws<JsonSerializationException>(
 661                () => JsonConvert.SerializeObject(c1),
 662                "Cannot write a null value for property 'Name'. Property requires a value. Path ''.");
 663
 664            RequiredPropertyTestClass c2 = new RequiredPropertyTestClass
 665            {
 666                Name = "Name!"
 667            };
 668
 669            string json = JsonConvert.SerializeObject(c2);
 670
 671            Assert.AreEqual(@"{""Name"":""Name!""}", json);
 672
 673            ExceptionAssert.Throws<JsonSerializationException>(
 674                () => JsonConvert.DeserializeObject<RequiredPropertyTestClass>(@"{}"),
 675                "Required property 'Name' not found in JSON. Path '', line 1, position 2.");
 676
 677            ExceptionAssert.Throws<JsonSerializationException>(
 678                () => JsonConvert.DeserializeObject<RequiredPropertyTestClass>(@"{""Name"":null}"),
 679                "Required property 'Name' expects a value but got null. Path '', line 1, position 13.");
 680
 681            RequiredPropertyTestClass c3 = JsonConvert.DeserializeObject<RequiredPropertyTestClass>(@"{""Name"":""Name!""}");
 682
 683            Assert.AreEqual("Name!", c3.Name);
 684        }
 685
 686        public class RequiredPropertyConstructorTestClass
 687        {
 688            public RequiredPropertyConstructorTestClass(string name)
 689            {
 690                Name = name;
 691            }
 692
 693            [JsonRequired]
 694            internal string Name { get; set; }
 695        }
 696
 697        [Test]
 698        public void RequiredPropertyConstructorTest()
 699        {
 700            RequiredPropertyConstructorTestClass c1 = new RequiredPropertyConstructorTestClass(null);
 701
 702            ExceptionAssert.Throws<JsonSerializationException>(
 703                () => JsonConvert.SerializeObject(c1),
 704                "Cannot write a null value for property 'Name'. Property requires a value. Path ''.");
 705
 706            RequiredPropertyConstructorTestClass c2 = new RequiredPropertyConstructorTestClass("Name!");
 707
 708            string json = JsonConvert.SerializeObject(c2);
 709
 710            Assert.AreEqual(@"{""Name"":""Name!""}", json);
 711
 712            ExceptionAssert.Throws<JsonSerializationException>(
 713                () => JsonConvert.DeserializeObject<RequiredPropertyConstructorTestClass>(@"{}"),
 714                "Required property 'Name' not found in JSON. Path '', line 1, position 2.");
 715
 716            RequiredPropertyConstructorTestClass c3 = JsonConvert.DeserializeObject<RequiredPropertyConstructorTestClass>(@"{""Name"":""Name!""}");
 717
 718            Assert.AreEqual("Name!", c3.Name);
 719        }
 720
 721        public class IgnoredPropertiesTestClass
 722        {
 723            [JsonIgnore]
 724            public Version IgnoredProperty { get; set; }
 725
 726            [JsonIgnore]
 727            public List<Version> IgnoredList { get; set; }
 728
 729            [JsonIgnore]
 730            public Dictionary<string, Version> IgnoredDictionary { get; set; }
 731
 732            [JsonProperty(Required = Required.Always)]
 733            public string Name { get; set; }
 734        }
 735
 736        public class IgnoredPropertiesContractResolver : DefaultContractResolver
 737        {
 738            public override JsonContract ResolveContract(Type type)
 739            {
 740                if (type == typeof(Version))
 741                {
 742                    throw new Exception("Error!");
 743                }
 744
 745                return base.ResolveContract(type);
 746            }
 747        }
 748
 749        [Test]
 750        public void NeverResolveIgnoredPropertyTypes()
 751        {
 752            Version v = new Version(1, 2, 3, 4);
 753
 754            IgnoredPropertiesTestClass c1 = new IgnoredPropertiesTestClass
 755            {
 756                IgnoredProperty = v,
 757                IgnoredList = new List<Version>
 758                {
 759                    v
 760                },
 761                IgnoredDictionary = new Dictionary<string, Version>
 762                {
 763                    { "Value", v }
 764                },
 765                Name = "Name!"
 766            };
 767
 768            string json = JsonConvert.SerializeObject(c1, Formatting.Indented, new JsonSerializerSettings
 769            {
 770                ContractResolver = new IgnoredPropertiesContractResolver()
 771            });
 772
 773            Assert.AreEqual(@"{
 774  ""Name"": ""Name!""
 775}", json);
 776
 777            string deserializeJson = @"{
 778  ""IgnoredList"": [
 779    {
 780      ""Major"": 1,
 781      ""Minor"": 2,
 782      ""Build"": 3,
 783      ""Revision"": 4,
 784      ""MajorRevision"": 0,
 785      ""MinorRevision"": 4
 786    }
 787  ],
 788  ""IgnoredDictionary"": {
 789    ""Value"": {
 790      ""Major"": 1,
 791      ""Minor"": 2,
 792      ""Build"": 3,
 793      ""Revision"": 4,
 794      ""MajorRevision"": 0,
 795      ""MinorRevision"": 4
 796    }
 797  },
 798  ""Name"": ""Name!""
 799}";
 800
 801            IgnoredPropertiesTestClass c2 = JsonConvert.DeserializeObject<IgnoredPropertiesTestClass>(deserializeJson, new JsonSerializerSettings
 802            {
 803                ContractResolver = new IgnoredPropertiesContractResolver()
 804            });
 805
 806            Assert.AreEqual("Name!", c2.Name);
 807        }
 808
 809#if !(NET20 || NET35)
 810        [Test]
 811        public void SerializeValueTuple()
 812        {
 813            ValueTuple<int, int, string> t = ValueTuple.Create(1, 2, "string");
 814
 815            string json = JsonConvert.SerializeObject(t, Formatting.Indented);
 816
 817            StringAssert.AreEqual(@"{
 818  ""Item1"": 1,
 819  ""Item2"": 2,
 820  ""Item3"": ""string""
 821}", json);
 822
 823            ValueTuple<int, int, string> t2 = JsonConvert.DeserializeObject<ValueTuple<int, int, string>>(json);
 824
 825            Assert.AreEqual(1, t2.Item1);
 826            Assert.AreEqual(2, t2.Item2);
 827            Assert.AreEqual("string", t2.Item3);
 828        }
 829#endif
 830
 831        [Test]
 832        public void DeserializeStructWithConstructorAttribute()
 833        {
 834            ImmutableStructWithConstructorAttribute result = JsonConvert.DeserializeObject<ImmutableStructWithConstructorAttribute>("{ \"Value\": \"working\" }");
 835
 836            Assert.AreEqual("working", result.Value);
 837        }
 838
 839        public struct ImmutableStructWithConstructorAttribute
 840        {
 841            [JsonConstructor]
 842            public ImmutableStructWithConstructorAttribute(string value)
 843            {
 844                Value = value;
 845            }
 846
 847            public string Value { get; }
 848        }
 849
 850#if !(DNXCORE50 || NET20)
 851        [MetadataType(typeof(CustomerValidation))]
 852        public partial class CustomerWithMetadataType
 853        {
 854            public System.Guid UpdatedBy_Id { get; set; }
 855
 856            public class CustomerValidation
 857            {
 858                [JsonIgnore]
 859                public System.Guid UpdatedBy_Id { get; set; }
 860            }
 861        }
 862
 863        [Test]
 864        public void SerializeMetadataType()
 865        {
 866            CustomerWithMetadataType c = new CustomerWithMetadataType()
 867            {
 868                UpdatedBy_Id = Guid.NewGuid()
 869            };
 870            string json = JsonConvert.SerializeObject(c);
 871
 872            Assert.AreEqual("{}", json);
 873
 874            CustomerWithMetadataType c2 = JsonConvert.DeserializeObject<CustomerWithMetadataType>("{'UpdatedBy_Id':'F6E0666D-13C7-4745-B486-800812C8F6DE'}");
 875
 876            Assert.AreEqual(Guid.Empty, c2.UpdatedBy_Id);
 877        }
 878
 879        [Serializable]
 880        public partial class FaqItem
 881        {
 882            public FaqItem()
 883            {
 884                this.Sections = new HashSet<FaqSection>();
 885            }
 886
 887            public int FaqId { get; set; }
 888            public string Name { get; set; }
 889            public bool IsDeleted { get; set; }
 890
 891            public virtual ICollection<FaqSection> Sections { get; set; }
 892        }
 893
 894        [MetadataType(typeof(FaqItemMetadata))]
 895        partial class FaqItem
 896        {
 897            [JsonProperty("FullSectionsProp")]
 898            public ICollection<FaqSection> FullSections
 899            {
 900                get { return Sections; }
 901            }
 902        }
 903
 904        public class FaqItemMetadata
 905        {
 906            [JsonIgnore]
 907            public virtual ICollection<FaqSection> Sections { get; set; }
 908        }
 909
 910        public class FaqSection
 911        {
 912        }
 913
 914        public class FaqItemProxy : FaqItem
 915        {
 916            public bool IsProxy { get; set; }
 917
 918            public override ICollection<FaqSection> Sections
 919            {
 920                get { return base.Sections; }
 921                set { base.Sections = value; }
 922            }
 923        }
 924
 925        [Test]
 926        public void SerializeMetadataType2()
 927        {
 928            FaqItem c = new FaqItem()
 929            {
 930                FaqId = 1,
 931                Sections =
 932                {
 933                    new FaqSection()
 934                }
 935            };
 936
 937            string json = JsonConvert.SerializeObject(c, Formatting.Indented);
 938
 939            StringAssert.AreEqual(@"{
 940  ""FaqId"": 1,
 941  ""Name"": null,
 942  ""IsDeleted"": false,
 943  ""FullSectionsProp"": [
 944    {}
 945  ]
 946}", json);
 947
 948            FaqItem c2 = JsonConvert.DeserializeObject<FaqItem>(json);
 949
 950            Assert.AreEqual(1, c2.FaqId);
 951            Assert.AreEqual(1, c2.Sections.Count);
 952        }
 953
 954        [Test]
 955        public void SerializeMetadataTypeInheritance()
 956        {
 957            FaqItemProxy c = new FaqItemProxy();
 958            c.FaqId = 1;
 959            c.Sections.Add(new FaqSection());
 960            c.IsProxy = true;
 961
 962            string json = JsonConvert.SerializeObject(c, Formatting.Indented);
 963
 964            StringAssert.AreEqual(@"{
 965  ""IsProxy"": true,
 966  ""FaqId"": 1,
 967  ""Name"": null,
 968  ""IsDeleted"": false,
 969  ""FullSectionsProp"": [
 970    {}
 971  ]
 972}", json);
 973
 974            FaqItemProxy c2 = JsonConvert.DeserializeObject<FaqItemProxy>(json);
 975
 976            Assert.AreEqual(1, c2.FaqId);
 977            Assert.AreEqual(1, c2.Sections.Count);
 978        }
 979#endif
 980
 981        public class NullTestClass
 982        {
 983            public JObject Value1 { get; set; }
 984            public JValue Value2 { get; set; }
 985            public JRaw Value3 { get; set; }
 986            public JToken Value4 { get; set; }
 987            public object Value5 { get; set; }
 988        }
 989
 990        [Test]
 991        public void DeserializeNullToJTokenProperty()
 992        {
 993            NullTestClass otc = JsonConvert.DeserializeObject<NullTestClass>(@"{
 994    ""Value1"": null,
 995    ""Value2"": null,
 996    ""Value3"": null,
 997    ""Value4"": null,
 998    ""Value5"": null
 999}");
1000            Assert.IsNull(otc.Value1);
1001            Assert.AreEqual(JTokenType.Null, otc.Value2.Type);
1002            Assert.AreEqual(JTokenType.Raw, otc.Value3.Type);
1003            Assert.AreEqual(JTokenType.Null, otc.Value4.Type);
1004            Assert.IsNull(otc.Value5);
1005        }
1006
1007        public class Link
1008        {
1009            /// <summary>
1010            /// The unique identifier.
1011            /// </summary>
1012            public int Id;
1013
1014            /// <summary>
1015            /// The parent information identifier.
1016            /// </summary>
1017            public int ParentId;
1018
1019            /// <summary>
1020            /// The child information identifier.
1021            /// </summary>
1022            public int ChildId;
1023        }
1024
1025#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
1026        [Test]
1027        public void ReadIntegerWithError()
1028        {
1029            string json = @"{
1030    ParentId: 1,
1031    ChildId: 333333333333333333333333333333333333333
1032}";
1033
1034            Link l = JsonConvert.DeserializeObject<Link>(json, new JsonSerializerSettings
1035            {
1036                Error = (s, a) => a.ErrorContext.Handled = true
1037            });
1038
1039            Assert.AreEqual(0, l.ChildId);
1040        }
1041#endif
1042
1043#if !(NET20 || NET35)
1044        [Test]
1045        public void DeserializeObservableCollection()
1046        {
1047            ObservableCollection<string> s = JsonConvert.DeserializeObject<ObservableCollection<string>>("['1','2']");
1048            Assert.AreEqual(2, s.Count);
1049            Assert.AreEqual("1", s[0]);
1050            Assert.AreEqual("2", s[1]);
1051        }
1052#endif
1053
1054        [Test]
1055        public void DeserializeBoolAsStringInDictionary()
1056        {
1057            Dictionary<string, string> d = JsonConvert.DeserializeObject<Dictionary<string, string>>("{\"Test1\":false}");
1058            Assert.AreEqual(1, d.Count);
1059            Assert.AreEqual("false", d["Test1"]);
1060        }
1061
1062#if !NET20
1063        [Test]
1064        public void PopulateResetSettings()
1065        {
1066            JsonTextReader reader = new JsonTextReader(new StringReader(@"[""2000-01-01T01:01:01+00:00""]"));
1067            Assert.AreEqual(DateParseHandling.DateTime, reader.DateParseHandling);
1068
1069            JsonSerializer serializer = new JsonSerializer();
1070            serializer.DateParseHandling = DateParseHandling.DateTimeOffset;
1071
1072            IList<object> l = new List<object>();
1073            serializer.Populate(reader, l);
1074
1075            Assert.AreEqual(typeof(DateTimeOffset), l[0].GetType());
1076            Assert.AreEqual(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero), l[0]);
1077
1078            Assert.AreEqual(DateParseHandling.DateTime, reader.DateParseHandling);
1079        }
1080#endif
1081
1082        public class BaseClass
1083        {
1084            internal bool IsTransient { get; set; }
1085        }
1086
1087        public class ChildClass : BaseClass
1088        {
1089            public new bool IsTransient { get; set; }
1090        }
1091
1092        [Test]
1093        public void NewProperty()
1094        {
1095            Assert.AreEqual(@"{""IsTransient"":true}", JsonConvert.SerializeObject(new ChildClass { IsTransient = true }));
1096
1097            var childClass = JsonConvert.DeserializeObject<ChildClass>(@"{""IsTransient"":true}");
1098            Assert.AreEqual(true, childClass.IsTransient);
1099        }
1100
1101        public class BaseClassVirtual
1102        {
1103            internal virtual bool IsTransient { get; set; }
1104        }
1105
1106        public class ChildClassVirtual : BaseClassVirtual
1107        {
1108            public new virtual bool IsTransient { get; set; }
1109        }
1110
1111        [Test]
1112        public void NewPropertyVirtual()
1113        {
1114            Assert.AreEqual(@"{""IsTransient"":true}", JsonConvert.SerializeObject(new ChildClassVirtual { IsTransient = true }));
1115
1116            var childClass = JsonConvert.DeserializeObject<ChildClassVirtual>(@"{""IsTransient"":true}");
1117            Assert.AreEqual(true, childClass.IsTransient);
1118        }
1119
1120        public class ResponseWithNewGenericProperty<T> : SimpleResponse
1121        {
1122            public new T Data { get; set; }
1123        }
1124
1125        public class ResponseWithNewGenericPropertyVirtual<T> : SimpleResponse
1126        {
1127            public new virtual T Data { get; set; }
1128        }
1129
1130        public class ResponseWithNewGenericPropertyOverride<T> : ResponseWithNewGenericPropertyVirtual<T>
1131        {
1132            public override T Data { get; set; }
1133        }
1134
1135        public abstract class SimpleResponse
1136        {
1137            public string Result { get; set; }
1138            public string Message { get; set; }
1139            public object Data { get; set; }
1140
1141            protected SimpleResponse()
1142            {
1143            }
1144
1145            protected SimpleResponse(string message)
1146            {
1147                Message = message;
1148            }
1149        }
1150
1151        [Test]
1152        public void CanSerializeWithBuiltInTypeAsGenericArgument()
1153        {
1154            var input = new ResponseWithNewGenericProperty<int>()
1155            {
1156                Message = "Trying out integer as type parameter",
1157                Data = 25,
1158                Result = "This should be fine"
1159            };
1160
1161            var json = JsonConvert.SerializeObject(input);
1162            var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericProperty<int>>(json);
1163
1164            Assert.AreEqual(input.Data, deserialized.Data);
1165            Assert.AreEqual(input.Message, deserialized.Message);
1166            Assert.AreEqual(input.Result, deserialized.Result);
1167        }
1168
1169        [Test]
1170        public void CanSerializeWithBuiltInTypeAsGenericArgumentVirtual()
1171        {
1172            var input = new ResponseWithNewGenericPropertyVirtual<int>()
1173            {
1174                Message = "Trying out integer as type parameter",
1175                Data = 25,
1176                Result = "This should be fine"
1177            };
1178
1179            var json = JsonConvert.SerializeObject(input);
1180            var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericPropertyVirtual<int>>(json);
1181
1182            Assert.AreEqual(input.Data, deserialized.Data);
1183            Assert.AreEqual(input.Message, deserialized.Message);
1184            Assert.AreEqual(input.Result, deserialized.Result);
1185        }
1186
1187        [Test]
1188        public void CanSerializeWithBuiltInTypeAsGenericArgumentOverride()
1189        {
1190            var input = new ResponseWithNewGenericPropertyOverride<int>()
1191            {
1192                Message = "Trying out integer as type parameter",
1193                Data = 25,
1194                Result = "This should be fine"
1195            };
1196
1197            var json = JsonConvert.SerializeObject(input);
1198            var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericPropertyOverride<int>>(json);
1199
1200            Assert.AreEqual(input.Data, deserialized.Data);
1201            Assert.AreEqual(input.Message, deserialized.Message);
1202            Assert.AreEqual(input.Result, deserialized.Result);
1203        }
1204
1205        [Test]
1206        public void CanSerializedWithGenericClosedTypeAsArgument()
1207        {
1208            var input = new ResponseWithNewGenericProperty<List<int>>()
1209            {
1210                Message = "More complex case - generic list of int",
1211                Data = Enumerable.Range(50, 70).ToList(),
1212                Result = "This should be fine too"
1213            };
1214
1215            var json = JsonConvert.SerializeObject(input);
1216            var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericProperty<List<int>>>(json);
1217
1218            CollectionAssert.AreEqual(input.Data, deserialized.Data);
1219            Assert.AreEqual(input.Message, deserialized.Message);
1220            Assert.AreEqual(input.Result, deserialized.Result);
1221        }
1222
1223        [Test]
1224        public void DeserializeVersionString()
1225        {
1226            string json = "['1.2.3.4']";
1227            List<Version> deserialized = JsonConvert.DeserializeObject<List<Version>>(json);
1228
1229            Assert.AreEqual(1, deserialized[0].Major);
1230            Assert.AreEqual(2, deserialized[0].Minor);
1231            Assert.AreEqual(3, deserialized[0].Build);
1232            Assert.AreEqual(4, deserialized[0].Revision);
1233        }
1234
1235        [Test]
1236        public void DeserializeVersionString_Fail()
1237        {
1238            string json = "['1.2.3.4444444444444444444444']";
1239
1240            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.");
1241        }
1242
1243        [Test]
1244        public void DeserializeJObjectWithComments()
1245        {
1246            string json = @"/* Test */
1247            {
1248                /*Test*/""A"":/* Test */true/* Test */,
1249                /* Test */""B"":/* Test */false/* Test */,
1250                /* Test */""C"":/* Test */[
1251                    /* Test */
1252                    1/* Test */
1253                ]/* Test */
1254            }
1255            /* Test */";
1256            JObject o = (JObject)JsonConvert.DeserializeObject(json);
1257            Assert.AreEqual(3, o.Count);
1258            Assert.AreEqual(true, (bool)o["A"]);
1259            Assert.AreEqual(false, (bool)o["B"]);
1260            Assert.AreEqual(1, o["C"].Count());
1261            Assert.AreEqual(1, (int)o["C"][0]);
1262
1263            Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
1264
1265            json = @"{/* Test */}";
1266            o = (JObject)JsonConvert.DeserializeObject(json);
1267            Assert.AreEqual(0, o.Count);
1268            Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
1269
1270            json = @"{""A"": true/* Test */}";
1271            o = (JObject)JsonConvert.DeserializeObject(json);
1272            Assert.AreEqual(1, o.Count);
1273            Assert.AreEqual(true, (bool)o["A"]);
1274            Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
1275        }
1276
1277        public class CommentTestObject
1278        {
1279            public bool? A { get; set; }
1280        }
1281
1282        [Test]
1283        public void DeserializeCommentTestObjectWithComments()
1284        {
1285            CommentTestObject o = JsonConvert.DeserializeObject<CommentTestObject>(@"{/* Test */}");
1286            Assert.AreEqual(null, o.A);
1287
1288            o = JsonConvert.DeserializeObject<CommentTestObject>(@"{""A"": true/* Test */}");
1289            Assert.AreEqual(true, o.A);
1290        }
1291
1292        [Test]
1293        public void JsonSerializerProperties()
1294        {
1295            JsonSerializer serializer = new JsonSerializer();
1296
1297            DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
1298#pragma warning disable CS0618 // Type or member is obsolete
1299            serializer.Binder = customBinder;
1300            Assert.AreEqual(customBinder, serializer.Binder);
1301#pragma warning restore CS0618 // Type or member is obsolete
1302
1303            Assert.IsInstanceOf(typeof(SerializationBinderAdapter), serializer.SerializationBinder);
1304
1305            serializer.SerializationBinder = customBinder;
1306            Assert.AreEqual(customBinder, serializer.SerializationBinder);
1307
1308            ExceptionAssert.Throws<InvalidOperationException>(() =>
1309            {
1310#pragma warning disable CS0618 // Type or member is obsolete
1311                var serializationBinder = serializer.Binder;
1312#pragma warning restore CS0618 // Type or member is obsolete
1313                serializationBinder.ToString();
1314            }, "Cannot get SerializationBinder because an ISerializationBinder was previously set.");
1315
1316            serializer.CheckAdditionalContent = true;
1317            Assert.AreEqual(true, serializer.CheckAdditionalContent);
1318
1319            serializer.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
1320            Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, serializer.ConstructorHandling);
1321
1322#if !(DNXCORE50)
1323            serializer.Context = new StreamingContext(StreamingContextStates.Other);
1324            Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), serializer.Context);
1325#endif
1326
1327            CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
1328            serializer.ContractResolver = resolver;
1329            Assert.AreEqual(resolver, serializer.ContractResolver);
1330
1331            serializer.Converters.Add(new StringEnumConverter());
1332            Assert.AreEqual(1, serializer.Converters.Count);
1333
1334            serializer.Culture = new CultureInfo("en-nz");
1335            Assert.AreEqual("en-NZ", serializer.Culture.ToString());
1336
1337            serializer.EqualityComparer = EqualityComparer<object>.Default;
1338            Assert.AreEqual(EqualityComparer<object>.Default, serializer.EqualityComparer);
1339
1340            serializer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
1341            Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, serializer.DateFormatHandling);
1342
1343            serializer.DateFormatString = "yyyy";
1344            Assert.AreEqual("yyyy", serializer.DateFormatString);
1345
1346            serializer.DateParseHandling = DateParseHandling.None;
1347            Assert.AreEqual(DateParseHandling.None, serializer.DateParseHandling);
1348
1349            serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
1350            Assert.AreEqual(DateTimeZoneHandling.Utc, serializer.DateTimeZoneHandling);
1351
1352            serializer.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
1353            Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, serializer.DefaultValueHandling);
1354
1355            serializer.FloatFormatHandling = FloatFormatHandling.Symbol;
1356            Assert.AreEqual(FloatFormatHandling.Symbol, serializer.FloatFormatHandling);
1357
1358            serializer.FloatParseHandling = FloatParseHandling.Decimal;
1359            Assert.AreEqual(FloatParseHandling.Decimal, serializer.FloatParseHandling);
1360
1361            serializer.Formatting = Formatting.Indented;
1362            Assert.AreEqual(Formatting.Indented, serializer.Formatting);
1363
1364            serializer.MaxDepth = 9001;
1365            Assert.AreEqual(9001, serializer.MaxDepth);
1366
1367            serializer.MissingMemberHandling = MissingMemberHandling.Error;
1368            Assert.AreEqual(MissingMemberHandling.Error, serializer.MissingMemberHandling);
1369
1370            serializer.NullValueHandling = NullValueHandling.Ignore;
1371            Assert.AreEqual(NullValueHandling.Ignore, serializer.NullValueHandling);
1372
1373            serializer.ObjectCreationHandling = ObjectCreationHandling.Replace;
1374            Assert.AreEqual(ObjectCreationHandling.Replace, serializer.ObjectCreationHandling);
1375
1376            serializer.PreserveReferencesHandling = PreserveReferencesHandling.All;
1377            Assert.AreEqual(PreserveReferencesHandling.All, serializer.PreserveReferencesHandling);
1378
1379            serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
1380            Assert.AreEqual(ReferenceLoopHandling.Ignore, serializer.ReferenceLoopHandling);
1381
1382            IdReferenceResolver referenceResolver = new IdReferenceResolver();
1383            serializer.ReferenceResolver = referenceResolver;
1384            Assert.AreEqual(referenceResolver, serializer.ReferenceResolver);
1385
1386            serializer.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
1387            Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, serializer.StringEscapeHandling);
1388
1389            MemoryTraceWriter traceWriter = new MemoryTraceWriter();
1390            serializer.TraceWriter = traceWriter;
1391            Assert.AreEqual(traceWriter, serializer.TraceWriter);
1392
1393#if !(PORTABLE || PORTABLE40 || NET20 || DNXCORE50)
1394#pragma warning disable 618
1395            serializer.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
1396            Assert.AreEqual(FormatterAssemblyStyle.Full, serializer.TypeNameAssemblyFormat);
1397#pragma warning restore 618
1398
1399            Assert.AreEqual(TypeNameAssemblyFormatHandling.Full, serializer.TypeNameAssemblyFormatHandling);
1400
1401            serializer.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple;
1402#pragma warning disable 618
1403            Assert.AreEqual(FormatterAssemblyStyle.Simple, serializer.TypeNameAssemblyFormat);
1404#pragma warning restore 618
1405#endif
1406
1407            serializer.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full;
1408            Assert.AreEqual(TypeNameAssemblyFormatHandling.Full, serializer.TypeNameAssemblyFormatHandling);
1409
1410            serializer.TypeNameHandling = TypeNameHandling.All;
1411            Assert.AreEqual(TypeNameHandling.All, serializer.TypeNameHandling);
1412        }
1413
1414        [Test]
1415        public void JsonSerializerSettingsProperties()
1416        {
1417            JsonSerializerSettings settings = new JsonSerializerSettings();
1418
1419            DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
1420#pragma warning disable CS0618 // Type or member is obsolete
1421            settings.Binder = customBinder;
1422            Assert.AreEqual(customBinder, settings.Binder);
1423#pragma warning restore CS0618 // Type or member is obsolete
1424
1425            settings.CheckAdditionalContent = true;
1426            Assert.AreEqual(true, settings.CheckAdditionalContent);
1427
1428            settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
1429            Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, settings.ConstructorHandling);
1430
1431#if !(DNXCORE50)
1432            settings.Context = new StreamingContext(StreamingContextStates.Other);
1433            Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), settings.Context);
1434#endif
1435
1436            CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
1437            settings.ContractResolver = resolver;
1438            Assert.AreEqual(resolver, settings.ContractResolver);
1439
1440            settings.Converters.Add(new StringEnumConverter());
1441            Assert.AreEqual(1, settings.Converters.Count);
1442
1443            settings.Culture = new CultureInfo("en-nz");
1444            Assert.AreEqual("en-NZ", settings.Culture.ToString());
1445
1446            settings.EqualityComparer = EqualityComparer<object>.Default;
1447            Assert.AreEqual(EqualityComparer<object>.Default, settings.EqualityComparer);
1448
1449            settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
1450            Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, settings.DateFormatHandling);
1451
1452            settings.DateFormatString = "yyyy";
1453            As

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