PageRenderTime 75ms CodeModel.GetById 9ms app.highlight 39ms RepoModel.GetById 1ms app.codeStats 3ms

/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

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

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