PageRenderTime 9ms CodeModel.GetById 4ms app.highlight 90ms RepoModel.GetById 1ms app.codeStats 1ms

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

https://bitbucket.org/wfpcoslv/maps-examples
C# | 2489 lines | 2440 code | 18 blank | 31 comment | 3 complexity | 4c4d27df53656e92ea12e479ecf4084c 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
  26#if NET20
  27using Newtonsoft.Json.Utilities.LinqBridge;
  28#else
  29using System.Linq;
  30#endif
  31#if !(PORTABLE || PORTABLE40)
  32using System.Collections.ObjectModel;
  33#if !(NET35 || NET20)
  34using System.Dynamic;
  35#endif
  36using System.Text;
  37using Newtonsoft.Json.Tests.Linq;
  38using System;
  39using System.Collections;
  40using System.Collections.Generic;
  41using System.Globalization;
  42using System.Runtime.Serialization.Formatters;
  43using Newtonsoft.Json.Linq;
  44using Newtonsoft.Json.Serialization;
  45using Newtonsoft.Json.Tests.TestObjects;
  46using Newtonsoft.Json.Tests.TestObjects.Organization;
  47#if DNXCORE50
  48using Xunit;
  49using Test = Xunit.FactAttribute;
  50using Assert = Newtonsoft.Json.Tests.XUnitAssert;
  51#else
  52using NUnit.Framework;
  53#endif
  54using Newtonsoft.Json.Utilities;
  55using System.Net;
  56using System.Runtime.Serialization;
  57using System.IO;
  58using System.Reflection;
  59
  60namespace Newtonsoft.Json.Tests.Serialization
  61{
  62    [TestFixture]
  63    public class TypeNameHandlingTests : TestFixtureBase
  64    {
  65#if !(NET20 || NET35)
  66        [Test]
  67        public void SerializeValueTupleWithTypeName()
  68        {
  69            string tupleRef = ReflectionUtils.GetTypeName(typeof(ValueTuple<int, int, string>), TypeNameAssemblyFormatHandling.Simple, null);
  70
  71            ValueTuple<int, int, string> t = ValueTuple.Create(1, 2, "string");
  72
  73            string json = JsonConvert.SerializeObject(t, Formatting.Indented, new JsonSerializerSettings
  74            {
  75                TypeNameHandling = TypeNameHandling.All
  76            });
  77
  78            StringAssert.AreEqual(@"{
  79  ""$type"": """ + tupleRef + @""",
  80  ""Item1"": 1,
  81  ""Item2"": 2,
  82  ""Item3"": ""string""
  83}", json);
  84
  85            ValueTuple<int, int, string> t2 = (ValueTuple<int, int, string>)JsonConvert.DeserializeObject(json, new JsonSerializerSettings
  86            {
  87                TypeNameHandling = TypeNameHandling.All
  88            });
  89
  90            Assert.AreEqual(1, t2.Item1);
  91            Assert.AreEqual(2, t2.Item2);
  92            Assert.AreEqual("string", t2.Item3);
  93        }
  94#endif
  95
  96#if !(NET20 || NET35 || NET40)
  97        public class KnownAutoTypes
  98        {
  99            public ICollection<string> Collection { get; set; }
 100            public IList<string> List { get; set; }
 101            public IDictionary<string, string> Dictionary { get; set; }
 102            public ISet<string> Set { get; set; }
 103            public IReadOnlyCollection<string> ReadOnlyCollection { get; set; }
 104            public IReadOnlyList<string> ReadOnlyList { get; set; }
 105            public IReadOnlyDictionary<string, string> ReadOnlyDictionary { get; set; }
 106        }
 107
 108        [Test]
 109        public void KnownAutoTypesTest()
 110        {
 111            KnownAutoTypes c = new KnownAutoTypes
 112            {
 113                Collection = new List<string> { "Collection value!" },
 114                List = new List<string> { "List value!" },
 115                Dictionary = new Dictionary<string, string>
 116                {
 117                    { "Dictionary key!", "Dictionary value!" }
 118                },
 119                ReadOnlyCollection = new ReadOnlyCollection<string>(new[] { "Read Only Collection value!" }),
 120                ReadOnlyList = new ReadOnlyCollection<string>(new[] { "Read Only List value!" }),
 121                Set = new HashSet<string> { "Set value!" },
 122                ReadOnlyDictionary = new ReadOnlyDictionary<string, string>(new Dictionary<string, string>
 123                {
 124                    { "Read Only Dictionary key!", "Read Only Dictionary value!" }
 125                })
 126            };
 127
 128            string json = JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings
 129            {
 130                TypeNameHandling = TypeNameHandling.Auto
 131            });
 132
 133            StringAssert.AreEqual(@"{
 134  ""Collection"": [
 135    ""Collection value!""
 136  ],
 137  ""List"": [
 138    ""List value!""
 139  ],
 140  ""Dictionary"": {
 141    ""Dictionary key!"": ""Dictionary value!""
 142  },
 143  ""Set"": [
 144    ""Set value!""
 145  ],
 146  ""ReadOnlyCollection"": [
 147    ""Read Only Collection value!""
 148  ],
 149  ""ReadOnlyList"": [
 150    ""Read Only List value!""
 151  ],
 152  ""ReadOnlyDictionary"": {
 153    ""Read Only Dictionary key!"": ""Read Only Dictionary value!""
 154  }
 155}", json);
 156        }
 157#endif
 158
 159        [Test]
 160        public void DictionaryAuto()
 161        {
 162            Dictionary<string, object> dic = new Dictionary<string, object>
 163            {
 164                { "movie", new Movie { Name = "Die Hard" } }
 165            };
 166
 167            string json = JsonConvert.SerializeObject(dic, Formatting.Indented, new JsonSerializerSettings
 168            {
 169                TypeNameHandling = TypeNameHandling.Auto
 170            });
 171
 172            StringAssert.AreEqual(@"{
 173  ""movie"": {
 174    ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Movie, Newtonsoft.Json.Tests"",
 175    ""Name"": ""Die Hard"",
 176    ""Description"": null,
 177    ""Classification"": null,
 178    ""Studio"": null,
 179    ""ReleaseDate"": null,
 180    ""ReleaseCountries"": null
 181  }
 182}", json);
 183        }
 184
 185        [Test]
 186        public void KeyValuePairAuto()
 187        {
 188            IList<KeyValuePair<string, object>> dic = new List<KeyValuePair<string, object>>
 189            {
 190                new KeyValuePair<string, object>("movie", new Movie { Name = "Die Hard" })
 191            };
 192
 193            string json = JsonConvert.SerializeObject(dic, Formatting.Indented, new JsonSerializerSettings
 194            {
 195                TypeNameHandling = TypeNameHandling.Auto
 196            });
 197
 198            StringAssert.AreEqual(@"[
 199  {
 200    ""Key"": ""movie"",
 201    ""Value"": {
 202      ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Movie, Newtonsoft.Json.Tests"",
 203      ""Name"": ""Die Hard"",
 204      ""Description"": null,
 205      ""Classification"": null,
 206      ""Studio"": null,
 207      ""ReleaseDate"": null,
 208      ""ReleaseCountries"": null
 209    }
 210  }
 211]", json);
 212        }
 213
 214        [Test]
 215        public void NestedValueObjects()
 216        {
 217            StringBuilder sb = new StringBuilder();
 218            for (int i = 0; i < 3; i++)
 219            {
 220                sb.Append(@"{""$value"":");
 221            }
 222
 223            ExceptionAssert.Throws<JsonSerializationException>(() =>
 224            {
 225                var reader = new JsonTextReader(new StringReader(sb.ToString()));
 226                var ser = new JsonSerializer();
 227                ser.MetadataPropertyHandling = MetadataPropertyHandling.Default;
 228                ser.Deserialize<sbyte>(reader);
 229            }, "Unexpected token when deserializing primitive value: StartObject. Path '$value', line 1, position 11.");
 230        }
 231
 232        [Test]
 233        public void SerializeRootTypeNameIfDerivedWithAuto()
 234        {
 235            var serializer = new JsonSerializer()
 236            {
 237                TypeNameHandling = TypeNameHandling.Auto
 238            };
 239            var sw = new StringWriter();
 240            serializer.Serialize(new JsonTextWriter(sw) { Formatting = Formatting.Indented }, new WagePerson(), typeof(Person));
 241            var result = sw.ToString();
 242
 243            StringAssert.AreEqual(@"{
 244  ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Organization.WagePerson, Newtonsoft.Json.Tests"",
 245  ""HourlyWage"": 0.0,
 246  ""Name"": null,
 247  ""BirthDate"": ""0001-01-01T00:00:00"",
 248  ""LastModified"": ""0001-01-01T00:00:00""
 249}", result);
 250
 251            Assert.IsTrue(result.Contains("WagePerson"));
 252            using (var rd = new JsonTextReader(new StringReader(result)))
 253            {
 254                var person = serializer.Deserialize<Person>(rd);
 255
 256                CustomAssert.IsInstanceOfType(typeof(WagePerson), person);
 257            }
 258        }
 259
 260        [Test]
 261        public void SerializeRootTypeNameAutoWithJsonConvert()
 262        {
 263            string json = JsonConvert.SerializeObject(new WagePerson(), typeof(object), Formatting.Indented, new JsonSerializerSettings
 264            {
 265                TypeNameHandling = TypeNameHandling.Auto
 266            });
 267
 268            StringAssert.AreEqual(@"{
 269  ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Organization.WagePerson, Newtonsoft.Json.Tests"",
 270  ""HourlyWage"": 0.0,
 271  ""Name"": null,
 272  ""BirthDate"": ""0001-01-01T00:00:00"",
 273  ""LastModified"": ""0001-01-01T00:00:00""
 274}", json);
 275        }
 276
 277        [Test]
 278        public void SerializeRootTypeNameAutoWithJsonConvert_Generic()
 279        {
 280            string json = JsonConvert.SerializeObject(new WagePerson(), typeof(object), Formatting.Indented, new JsonSerializerSettings
 281            {
 282                TypeNameHandling = TypeNameHandling.Auto
 283            });
 284
 285            StringAssert.AreEqual(@"{
 286  ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Organization.WagePerson, Newtonsoft.Json.Tests"",
 287  ""HourlyWage"": 0.0,
 288  ""Name"": null,
 289  ""BirthDate"": ""0001-01-01T00:00:00"",
 290  ""LastModified"": ""0001-01-01T00:00:00""
 291}", json);
 292        }
 293
 294        [Test]
 295        public void SerializeRootTypeNameAutoWithJsonConvert_Generic2()
 296        {
 297            string json = JsonConvert.SerializeObject(new WagePerson(), typeof(object), new JsonSerializerSettings
 298            {
 299                TypeNameHandling = TypeNameHandling.Auto
 300            });
 301
 302            StringAssert.AreEqual(@"{""$type"":""Newtonsoft.Json.Tests.TestObjects.Organization.WagePerson, Newtonsoft.Json.Tests"",""HourlyWage"":0.0,""Name"":null,""BirthDate"":""0001-01-01T00:00:00"",""LastModified"":""0001-01-01T00:00:00""}", json);
 303        }
 304
 305        public class Wrapper
 306        {
 307            public IList<EmployeeReference> Array { get; set; }
 308            public IDictionary<string, EmployeeReference> Dictionary { get; set; }
 309        }
 310
 311        [Test]
 312        public void SerializeWrapper()
 313        {
 314            Wrapper wrapper = new Wrapper();
 315            wrapper.Array = new List<EmployeeReference>
 316            {
 317                new EmployeeReference()
 318            };
 319            wrapper.Dictionary = new Dictionary<string, EmployeeReference>
 320            {
 321                { "First", new EmployeeReference() }
 322            };
 323
 324            string json = JsonConvert.SerializeObject(wrapper, Formatting.Indented, new JsonSerializerSettings
 325            {
 326                TypeNameHandling = TypeNameHandling.Auto
 327            });
 328
 329            StringAssert.AreEqual(@"{
 330  ""Array"": [
 331    {
 332      ""$id"": ""1"",
 333      ""Name"": null,
 334      ""Manager"": null
 335    }
 336  ],
 337  ""Dictionary"": {
 338    ""First"": {
 339      ""$id"": ""2"",
 340      ""Name"": null,
 341      ""Manager"": null
 342    }
 343  }
 344}", json);
 345
 346            Wrapper w2 = JsonConvert.DeserializeObject<Wrapper>(json);
 347            CustomAssert.IsInstanceOfType(typeof(List<EmployeeReference>), w2.Array);
 348            CustomAssert.IsInstanceOfType(typeof(Dictionary<string, EmployeeReference>), w2.Dictionary);
 349        }
 350
 351        [Test]
 352        public void WriteTypeNameForObjects()
 353        {
 354            string employeeRef = ReflectionUtils.GetTypeName(typeof(EmployeeReference), TypeNameAssemblyFormatHandling.Simple, null);
 355
 356            EmployeeReference employee = new EmployeeReference();
 357
 358            string json = JsonConvert.SerializeObject(employee, Formatting.Indented, new JsonSerializerSettings
 359            {
 360                TypeNameHandling = TypeNameHandling.Objects
 361            });
 362
 363            StringAssert.AreEqual(@"{
 364  ""$id"": ""1"",
 365  ""$type"": """ + employeeRef + @""",
 366  ""Name"": null,
 367  ""Manager"": null
 368}", json);
 369        }
 370
 371        [Test]
 372        public void DeserializeTypeName()
 373        {
 374            string employeeRef = ReflectionUtils.GetTypeName(typeof(EmployeeReference), TypeNameAssemblyFormatHandling.Simple, null);
 375
 376            string json = @"{
 377  ""$id"": ""1"",
 378  ""$type"": """ + employeeRef + @""",
 379  ""Name"": ""Name!"",
 380  ""Manager"": null
 381}";
 382
 383            object employee = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
 384            {
 385                TypeNameHandling = TypeNameHandling.Objects
 386            });
 387
 388            CustomAssert.IsInstanceOfType(typeof(EmployeeReference), employee);
 389            Assert.AreEqual("Name!", ((EmployeeReference)employee).Name);
 390        }
 391
 392#if !(PORTABLE || DNXCORE50)
 393        [Test]
 394        public void DeserializeTypeNameFromGacAssembly()
 395        {
 396            string cookieRef = ReflectionUtils.GetTypeName(typeof(Cookie), TypeNameAssemblyFormatHandling.Simple, null);
 397
 398            string json = @"{
 399  ""$id"": ""1"",
 400  ""$type"": """ + cookieRef + @"""
 401}";
 402
 403            object cookie = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
 404            {
 405                TypeNameHandling = TypeNameHandling.Objects
 406            });
 407
 408            CustomAssert.IsInstanceOfType(typeof(Cookie), cookie);
 409        }
 410#endif
 411
 412        [Test]
 413        public void SerializeGenericObjectListWithTypeName()
 414        {
 415            string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
 416            string personRef = typeof(Person).AssemblyQualifiedName;
 417
 418            List<object> values = new List<object>
 419            {
 420                new EmployeeReference
 421                {
 422                    Name = "Bob",
 423                    Manager = new EmployeeReference { Name = "Frank" }
 424                },
 425                new Person
 426                {
 427                    Department = "Department",
 428                    BirthDate = new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc),
 429                    LastModified = new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc)
 430                },
 431                "String!",
 432                int.MinValue
 433            };
 434
 435            string json = JsonConvert.SerializeObject(values, Formatting.Indented, new JsonSerializerSettings
 436            {
 437                TypeNameHandling = TypeNameHandling.Objects,
 438#pragma warning disable 618
 439                TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
 440#pragma warning restore 618
 441            });
 442
 443            StringAssert.AreEqual(@"[
 444  {
 445    ""$id"": ""1"",
 446    ""$type"": """ + employeeRef + @""",
 447    ""Name"": ""Bob"",
 448    ""Manager"": {
 449      ""$id"": ""2"",
 450      ""$type"": """ + employeeRef + @""",
 451      ""Name"": ""Frank"",
 452      ""Manager"": null
 453    }
 454  },
 455  {
 456    ""$type"": """ + personRef + @""",
 457    ""Name"": null,
 458    ""BirthDate"": ""2000-12-30T00:00:00Z"",
 459    ""LastModified"": ""2000-12-30T00:00:00Z""
 460  },
 461  ""String!"",
 462  -2147483648
 463]", json);
 464        }
 465
 466        [Test]
 467        public void DeserializeGenericObjectListWithTypeName()
 468        {
 469            string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
 470            string personRef = typeof(Person).AssemblyQualifiedName;
 471
 472            string json = @"[
 473  {
 474    ""$id"": ""1"",
 475    ""$type"": """ + employeeRef + @""",
 476    ""Name"": ""Bob"",
 477    ""Manager"": {
 478      ""$id"": ""2"",
 479      ""$type"": """ + employeeRef + @""",
 480      ""Name"": ""Frank"",
 481      ""Manager"": null
 482    }
 483  },
 484  {
 485    ""$type"": """ + personRef + @""",
 486    ""Name"": null,
 487    ""BirthDate"": ""\/Date(978134400000)\/"",
 488    ""LastModified"": ""\/Date(978134400000)\/""
 489  },
 490  ""String!"",
 491  -2147483648
 492]";
 493
 494            List<object> values = (List<object>)JsonConvert.DeserializeObject(json, typeof(List<object>), new JsonSerializerSettings
 495            {
 496                TypeNameHandling = TypeNameHandling.Objects,
 497#pragma warning disable 618
 498                TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
 499#pragma warning restore 618
 500            });
 501
 502            Assert.AreEqual(4, values.Count);
 503
 504            EmployeeReference e = (EmployeeReference)values[0];
 505            Person p = (Person)values[1];
 506
 507            Assert.AreEqual("Bob", e.Name);
 508            Assert.AreEqual("Frank", e.Manager.Name);
 509
 510            Assert.AreEqual(null, p.Name);
 511            Assert.AreEqual(new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc), p.BirthDate);
 512            Assert.AreEqual(new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc), p.LastModified);
 513
 514            Assert.AreEqual("String!", values[2]);
 515            Assert.AreEqual((long)int.MinValue, values[3]);
 516        }
 517
 518        [Test]
 519        public void DeserializeWithBadTypeName()
 520        {
 521            string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
 522            string personRef = typeof(Person).AssemblyQualifiedName;
 523
 524            string json = @"{
 525  ""$id"": ""1"",
 526  ""$type"": """ + employeeRef + @""",
 527  ""Name"": ""Name!"",
 528  ""Manager"": null
 529}";
 530
 531            try
 532            {
 533                JsonConvert.DeserializeObject(json, typeof(Person), new JsonSerializerSettings
 534                {
 535                    TypeNameHandling = TypeNameHandling.Objects,
 536#pragma warning disable 618
 537                    TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
 538#pragma warning restore 618
 539                });
 540            }
 541            catch (JsonSerializationException ex)
 542            {
 543                Assert.IsTrue(ex.Message.StartsWith(@"Type specified in JSON '" + employeeRef + @"' is not compatible with '" + personRef + @"'."));
 544            }
 545        }
 546
 547        [Test]
 548        public void DeserializeTypeNameWithNoTypeNameHandling()
 549        {
 550            string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
 551
 552            string json = @"{
 553  ""$id"": ""1"",
 554  ""$type"": """ + employeeRef + @""",
 555  ""Name"": ""Name!"",
 556  ""Manager"": null
 557}";
 558
 559            JObject o = (JObject)JsonConvert.DeserializeObject(json);
 560
 561            StringAssert.AreEqual(@"{
 562  ""Name"": ""Name!"",
 563  ""Manager"": null
 564}", o.ToString());
 565        }
 566
 567        [Test]
 568        public void DeserializeTypeNameOnly()
 569        {
 570            string json = @"{
 571  ""$id"": ""1"",
 572  ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Employee"",
 573  ""Name"": ""Name!"",
 574  ""Manager"": null
 575}";
 576
 577            ExceptionAssert.Throws<JsonSerializationException>(() =>
 578            {
 579                JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
 580                {
 581                    TypeNameHandling = TypeNameHandling.Objects
 582                });
 583            }, "Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved. Path '$type', line 3, position 55.");
 584        }
 585
 586        public interface ICorrelatedMessage
 587        {
 588            string CorrelationId { get; set; }
 589        }
 590
 591        public class SendHttpRequest : ICorrelatedMessage
 592        {
 593            public SendHttpRequest()
 594            {
 595                RequestEncoding = "UTF-8";
 596                Method = "GET";
 597            }
 598
 599            public string Method { get; set; }
 600            public Dictionary<string, string> Headers { get; set; }
 601            public string Url { get; set; }
 602            public Dictionary<string, string> RequestData;
 603            public string RequestBodyText { get; set; }
 604            public string User { get; set; }
 605            public string Passwd { get; set; }
 606            public string RequestEncoding { get; set; }
 607            public string CorrelationId { get; set; }
 608        }
 609
 610        [Test]
 611        public void DeserializeGenericTypeName()
 612        {
 613            string typeName = typeof(SendHttpRequest).AssemblyQualifiedName;
 614
 615            string json = @"{
 616""$type"": """ + typeName + @""",
 617""RequestData"": {
 618""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"",
 619""Id"": ""siedemnaście"",
 620""X"": ""323""
 621},
 622""Method"": ""GET"",
 623""Url"": ""http://www.onet.pl"",
 624""RequestEncoding"": ""UTF-8"",
 625""CorrelationId"": ""xyz""
 626}";
 627
 628            ICorrelatedMessage message = JsonConvert.DeserializeObject<ICorrelatedMessage>(json, new JsonSerializerSettings
 629            {
 630                TypeNameHandling = TypeNameHandling.Objects,
 631#pragma warning disable 618
 632                TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
 633#pragma warning restore 618
 634            });
 635
 636            CustomAssert.IsInstanceOfType(typeof(SendHttpRequest), message);
 637
 638            SendHttpRequest request = (SendHttpRequest)message;
 639            Assert.AreEqual("xyz", request.CorrelationId);
 640            Assert.AreEqual(2, request.RequestData.Count);
 641            Assert.AreEqual("siedemnaście", request.RequestData["Id"]);
 642        }
 643
 644        [Test]
 645        public void SerializeObjectWithMultipleGenericLists()
 646        {
 647            string containerTypeName = typeof(Container).AssemblyQualifiedName;
 648            string productListTypeName = typeof(List<Product>).AssemblyQualifiedName;
 649
 650            Container container = new Container
 651            {
 652                In = new List<Product>(),
 653                Out = new List<Product>()
 654            };
 655
 656            string json = JsonConvert.SerializeObject(container, Formatting.Indented,
 657                new JsonSerializerSettings
 658                {
 659                    NullValueHandling = NullValueHandling.Ignore,
 660                    TypeNameHandling = TypeNameHandling.All,
 661#pragma warning disable 618
 662                    TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
 663#pragma warning restore 618
 664                });
 665
 666            StringAssert.AreEqual(@"{
 667  ""$type"": """ + containerTypeName + @""",
 668  ""In"": {
 669    ""$type"": """ + productListTypeName + @""",
 670    ""$values"": []
 671  },
 672  ""Out"": {
 673    ""$type"": """ + productListTypeName + @""",
 674    ""$values"": []
 675  }
 676}", json);
 677        }
 678
 679        public class TypeNameProperty
 680        {
 681            public string Name { get; set; }
 682
 683            [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
 684            public object Value { get; set; }
 685        }
 686
 687        [Test]
 688        public void WriteObjectTypeNameForProperty()
 689        {
 690            string typeNamePropertyRef = ReflectionUtils.GetTypeName(typeof(TypeNameProperty), TypeNameAssemblyFormatHandling.Simple, null);
 691
 692            TypeNameProperty typeNameProperty = new TypeNameProperty
 693            {
 694                Name = "Name!",
 695                Value = new TypeNameProperty
 696                {
 697                    Name = "Nested!"
 698                }
 699            };
 700
 701            string json = JsonConvert.SerializeObject(typeNameProperty, Formatting.Indented);
 702
 703            StringAssert.AreEqual(@"{
 704  ""Name"": ""Name!"",
 705  ""Value"": {
 706    ""$type"": """ + typeNamePropertyRef + @""",
 707    ""Name"": ""Nested!"",
 708    ""Value"": null
 709  }
 710}", json);
 711
 712            TypeNameProperty deserialized = JsonConvert.DeserializeObject<TypeNameProperty>(json);
 713            Assert.AreEqual("Name!", deserialized.Name);
 714            CustomAssert.IsInstanceOfType(typeof(TypeNameProperty), deserialized.Value);
 715
 716            TypeNameProperty nested = (TypeNameProperty)deserialized.Value;
 717            Assert.AreEqual("Nested!", nested.Name);
 718            Assert.AreEqual(null, nested.Value);
 719        }
 720
 721        [Test]
 722        public void WriteListTypeNameForProperty()
 723        {
 724            string listRef = ReflectionUtils.GetTypeName(typeof(List<int>), TypeNameAssemblyFormatHandling.Simple, null);
 725
 726            TypeNameProperty typeNameProperty = new TypeNameProperty
 727            {
 728                Name = "Name!",
 729                Value = new List<int> { 1, 2, 3, 4, 5 }
 730            };
 731
 732            string json = JsonConvert.SerializeObject(typeNameProperty, Formatting.Indented);
 733
 734            StringAssert.AreEqual(@"{
 735  ""Name"": ""Name!"",
 736  ""Value"": {
 737    ""$type"": """ + listRef + @""",
 738    ""$values"": [
 739      1,
 740      2,
 741      3,
 742      4,
 743      5
 744    ]
 745  }
 746}", json);
 747
 748            TypeNameProperty deserialized = JsonConvert.DeserializeObject<TypeNameProperty>(json);
 749            Assert.AreEqual("Name!", deserialized.Name);
 750            CustomAssert.IsInstanceOfType(typeof(List<int>), deserialized.Value);
 751
 752            List<int> nested = (List<int>)deserialized.Value;
 753            Assert.AreEqual(5, nested.Count);
 754            Assert.AreEqual(1, nested[0]);
 755            Assert.AreEqual(2, nested[1]);
 756            Assert.AreEqual(3, nested[2]);
 757            Assert.AreEqual(4, nested[3]);
 758            Assert.AreEqual(5, nested[4]);
 759        }
 760
 761        [Test]
 762        public void DeserializeUsingCustomBinder()
 763        {
 764            string json = @"{
 765  ""$id"": ""1"",
 766  ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Employee"",
 767  ""Name"": ""Name!""
 768}";
 769
 770            object p = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
 771            {
 772                TypeNameHandling = TypeNameHandling.Objects,
 773#pragma warning disable CS0618 // Type or member is obsolete
 774                Binder = new CustomSerializationBinder()
 775#pragma warning restore CS0618 // Type or member is obsolete
 776            });
 777
 778            CustomAssert.IsInstanceOfType(typeof(Person), p);
 779
 780            Person person = (Person)p;
 781
 782            Assert.AreEqual("Name!", person.Name);
 783        }
 784
 785        public class CustomSerializationBinder : SerializationBinder
 786        {
 787            public override Type BindToType(string assemblyName, string typeName)
 788            {
 789                return typeof(Person);
 790            }
 791        }
 792
 793#if !(NET20 || NET35)
 794        [Test]
 795        public void SerializeUsingCustomBinder()
 796        {
 797            TypeNameSerializationBinder binder = new TypeNameSerializationBinder("Newtonsoft.Json.Tests.Serialization.{0}, Newtonsoft.Json.Tests");
 798
 799            IList<object> values = new List<object>
 800            {
 801                new Customer
 802                {
 803                    Name = "Caroline Customer"
 804                },
 805                new Purchase
 806                {
 807                    ProductName = "Elbow Grease",
 808                    Price = 5.99m,
 809                    Quantity = 1
 810                }
 811            };
 812
 813            string json = JsonConvert.SerializeObject(values, Formatting.Indented, new JsonSerializerSettings
 814            {
 815                TypeNameHandling = TypeNameHandling.Auto,
 816#pragma warning disable CS0618 // Type or member is obsolete
 817                Binder = binder
 818#pragma warning restore CS0618 // Type or member is obsolete
 819            });
 820
 821            //[
 822            //  {
 823            //    "$type": "Customer",
 824            //    "Name": "Caroline Customer"
 825            //  },
 826            //  {
 827            //    "$type": "Purchase",
 828            //    "ProductName": "Elbow Grease",
 829            //    "Price": 5.99,
 830            //    "Quantity": 1
 831            //  }
 832            //]
 833
 834            StringAssert.AreEqual(@"[
 835  {
 836    ""$type"": ""Customer"",
 837    ""Name"": ""Caroline Customer""
 838  },
 839  {
 840    ""$type"": ""Purchase"",
 841    ""ProductName"": ""Elbow Grease"",
 842    ""Price"": 5.99,
 843    ""Quantity"": 1
 844  }
 845]", json);
 846
 847            IList<object> newValues = JsonConvert.DeserializeObject<IList<object>>(json, new JsonSerializerSettings
 848            {
 849                TypeNameHandling = TypeNameHandling.Auto,
 850#pragma warning disable CS0618 // Type or member is obsolete
 851                Binder = new TypeNameSerializationBinder("Newtonsoft.Json.Tests.Serialization.{0}, Newtonsoft.Json.Tests")
 852#pragma warning restore CS0618 // Type or member is obsolete
 853            });
 854
 855            CustomAssert.IsInstanceOfType(typeof(Customer), newValues[0]);
 856            Customer customer = (Customer)newValues[0];
 857            Assert.AreEqual("Caroline Customer", customer.Name);
 858
 859            CustomAssert.IsInstanceOfType(typeof(Purchase), newValues[1]);
 860            Purchase purchase = (Purchase)newValues[1];
 861            Assert.AreEqual("Elbow Grease", purchase.ProductName);
 862        }
 863
 864        public class TypeNameSerializationBinder : SerializationBinder
 865        {
 866            public string TypeFormat { get; private set; }
 867
 868            public TypeNameSerializationBinder(string typeFormat)
 869            {
 870                TypeFormat = typeFormat;
 871            }
 872
 873            public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
 874            {
 875                assemblyName = null;
 876                typeName = serializedType.Name;
 877            }
 878
 879            public override Type BindToType(string assemblyName, string typeName)
 880            {
 881                string resolvedTypeName = string.Format(TypeFormat, typeName);
 882
 883                return Type.GetType(resolvedTypeName, true);
 884            }
 885        }
 886#endif
 887
 888        [Test]
 889        public void NewSerializeUsingCustomBinder()
 890        {
 891            NewTypeNameSerializationBinder binder = new NewTypeNameSerializationBinder("Newtonsoft.Json.Tests.Serialization.{0}, Newtonsoft.Json.Tests");
 892
 893            IList<object> values = new List<object>
 894            {
 895                new Customer
 896                {
 897                    Name = "Caroline Customer"
 898                },
 899                new Purchase
 900                {
 901                    ProductName = "Elbow Grease",
 902                    Price = 5.99m,
 903                    Quantity = 1
 904                }
 905            };
 906
 907            string json = JsonConvert.SerializeObject(values, Formatting.Indented, new JsonSerializerSettings
 908            {
 909                TypeNameHandling = TypeNameHandling.Auto,
 910                SerializationBinder = binder
 911            });
 912
 913            //[
 914            //  {
 915            //    "$type": "Customer",
 916            //    "Name": "Caroline Customer"
 917            //  },
 918            //  {
 919            //    "$type": "Purchase",
 920            //    "ProductName": "Elbow Grease",
 921            //    "Price": 5.99,
 922            //    "Quantity": 1
 923            //  }
 924            //]
 925
 926            StringAssert.AreEqual(@"[
 927  {
 928    ""$type"": ""Customer"",
 929    ""Name"": ""Caroline Customer""
 930  },
 931  {
 932    ""$type"": ""Purchase"",
 933    ""ProductName"": ""Elbow Grease"",
 934    ""Price"": 5.99,
 935    ""Quantity"": 1
 936  }
 937]", json);
 938
 939            IList<object> newValues = JsonConvert.DeserializeObject<IList<object>>(json, new JsonSerializerSettings
 940            {
 941                TypeNameHandling = TypeNameHandling.Auto,
 942                SerializationBinder = new NewTypeNameSerializationBinder("Newtonsoft.Json.Tests.Serialization.{0}, Newtonsoft.Json.Tests")
 943            });
 944
 945            CustomAssert.IsInstanceOfType(typeof(Customer), newValues[0]);
 946            Customer customer = (Customer)newValues[0];
 947            Assert.AreEqual("Caroline Customer", customer.Name);
 948
 949            CustomAssert.IsInstanceOfType(typeof(Purchase), newValues[1]);
 950            Purchase purchase = (Purchase)newValues[1];
 951            Assert.AreEqual("Elbow Grease", purchase.ProductName);
 952        }
 953
 954        public class NewTypeNameSerializationBinder : ISerializationBinder
 955        {
 956            public string TypeFormat { get; private set; }
 957
 958            public NewTypeNameSerializationBinder(string typeFormat)
 959            {
 960                TypeFormat = typeFormat;
 961            }
 962
 963            public void BindToName(Type serializedType, out string assemblyName, out string typeName)
 964            {
 965                assemblyName = null;
 966                typeName = serializedType.Name;
 967            }
 968
 969            public Type BindToType(string assemblyName, string typeName)
 970            {
 971                string resolvedTypeName = string.Format(TypeFormat, typeName);
 972
 973                return Type.GetType(resolvedTypeName, true);
 974            }
 975        }
 976
 977        [Test]
 978        public void CollectionWithAbstractItems()
 979        {
 980            HolderClass testObject = new HolderClass();
 981            testObject.TestMember = new ContentSubClass("First One");
 982            testObject.AnotherTestMember = new Dictionary<int, IList<ContentBaseClass>>();
 983            testObject.AnotherTestMember.Add(1, new List<ContentBaseClass>());
 984            testObject.AnotherTestMember[1].Add(new ContentSubClass("Second One"));
 985            testObject.AThirdTestMember = new ContentSubClass("Third One");
 986
 987            JsonSerializer serializingTester = new JsonSerializer();
 988            serializingTester.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
 989
 990            StringWriter sw = new StringWriter();
 991            using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
 992            {
 993                jsonWriter.Formatting = Formatting.Indented;
 994                serializingTester.TypeNameHandling = TypeNameHandling.Auto;
 995                serializingTester.Serialize(jsonWriter, testObject);
 996            }
 997
 998            string json = sw.ToString();
 999
1000            string contentSubClassRef = ReflectionUtils.GetTypeName(typeof(ContentSubClass), TypeNameAssemblyFormatHandling.Simple, null);
1001            string dictionaryRef = ReflectionUtils.GetTypeName(typeof(Dictionary<int, IList<ContentBaseClass>>), TypeNameAssemblyFormatHandling.Simple, null);
1002            string listRef = ReflectionUtils.GetTypeName(typeof(List<ContentBaseClass>), TypeNameAssemblyFormatHandling.Simple, null);
1003
1004            string expected = @"{
1005  ""TestMember"": {
1006    ""$type"": """ + contentSubClassRef + @""",
1007    ""SomeString"": ""First One""
1008  },
1009  ""AnotherTestMember"": {
1010    ""$type"": """ + dictionaryRef + @""",
1011    ""1"": [
1012      {
1013        ""$type"": """ + contentSubClassRef + @""",
1014        ""SomeString"": ""Second One""
1015      }
1016    ]
1017  },
1018  ""AThirdTestMember"": {
1019    ""$type"": """ + contentSubClassRef + @""",
1020    ""SomeString"": ""Third One""
1021  }
1022}";
1023
1024            StringAssert.AreEqual(expected, json);
1025
1026            StringReader sr = new StringReader(json);
1027
1028            JsonSerializer deserializingTester = new JsonSerializer();
1029
1030            HolderClass anotherTestObject;
1031
1032            using (JsonTextReader jsonReader = new JsonTextReader(sr))
1033            {
1034                deserializingTester.TypeNameHandling = TypeNameHandling.Auto;
1035
1036                anotherTestObject = deserializingTester.Deserialize<HolderClass>(jsonReader);
1037            }
1038
1039            Assert.IsNotNull(anotherTestObject);
1040            CustomAssert.IsInstanceOfType(typeof(ContentSubClass), anotherTestObject.TestMember);
1041            CustomAssert.IsInstanceOfType(typeof(Dictionary<int, IList<ContentBaseClass>>), anotherTestObject.AnotherTestMember);
1042            Assert.AreEqual(1, anotherTestObject.AnotherTestMember.Count);
1043
1044            IList<ContentBaseClass> list = anotherTestObject.AnotherTestMember[1];
1045
1046            CustomAssert.IsInstanceOfType(typeof(List<ContentBaseClass>), list);
1047            Assert.AreEqual(1, list.Count);
1048            CustomAssert.IsInstanceOfType(typeof(ContentSubClass), list[0]);
1049        }
1050
1051        [Test]
1052        public void WriteObjectTypeNameForPropertyDemo()
1053        {
1054            Message message = new Message();
1055            message.Address = "http://www.google.com";
1056            message.Body = new SearchDetails
1057            {
1058                Query = "Json.NET",
1059                Language = "en-us"
1060            };
1061
1062            string json = JsonConvert.SerializeObject(message, Formatting.Indented);
1063            // {
1064            //   "Address": "http://www.google.com",
1065            //   "Body": {
1066            //     "$type": "Newtonsoft.Json.Tests.Serialization.SearchDetails, Newtonsoft.Json.Tests",
1067            //     "Query": "Json.NET",
1068            //     "Language": "en-us"
1069            //   }
1070            // }
1071
1072            Message deserialized = JsonConvert.DeserializeObject<Message>(json);
1073
1074            SearchDetails searchDetails = (SearchDetails)deserialized.Body;
1075            // Json.NET
1076        }
1077
1078        public class UrlStatus
1079        {
1080            public int Status { get; set; }
1081            public string Url { get; set; }
1082        }
1083
1084        [Test]
1085        public void GenericDictionaryObject()
1086        {
1087            Dictionary<string, object> collection = new Dictionary<string, object>()
1088            {
1089                { "First", new UrlStatus { Status = 404, Url = @"http://www.bing.com" } },
1090                { "Second", new UrlStatus { Status = 400, Url = @"http://www.google.com" } },
1091                {
1092                    "List", new List<UrlStatus>
1093                    {
1094                        new UrlStatus { Status = 300, Url = @"http://www.yahoo.com" },
1095                        new UrlStatus { Status = 200, Url = @"http://www.askjeeves.com" }
1096                    }
1097                }
1098            };
1099
1100            string json = JsonConvert.SerializeObject(collection, Formatting.Indented, new JsonSerializerSettings
1101            {
1102                TypeNameHandling = TypeNameHandling.All,
1103#pragma warning disable 618
1104                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
1105#pragma warning restore 618
1106            });
1107
1108            string urlStatusTypeName = ReflectionUtils.GetTypeName(typeof(UrlStatus), TypeNameAssemblyFormatHandling.Simple, null);
1109
1110            StringAssert.AreEqual(@"{
1111  ""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"",
1112  ""First"": {
1113    ""$type"": """ + urlStatusTypeName + @""",
1114    ""Status"": 404,
1115    ""Url"": ""http://www.bing.com""
1116  },
1117  ""Second"": {
1118    ""$type"": """ + urlStatusTypeName + @""",
1119    ""Status"": 400,
1120    ""Url"": ""http://www.google.com""
1121  },
1122  ""List"": {
1123    ""$type"": ""System.Collections.Generic.List`1[[" + urlStatusTypeName + @"]], mscorlib"",
1124    ""$values"": [
1125      {
1126        ""$type"": """ + urlStatusTypeName + @""",
1127        ""Status"": 300,
1128        ""Url"": ""http://www.yahoo.com""
1129      },
1130      {
1131        ""$type"": """ + urlStatusTypeName + @""",
1132        ""Status"": 200,
1133        ""Url"": ""http://www.askjeeves.com""
1134      }
1135    ]
1136  }
1137}", json);
1138
1139            object c = JsonConvert.DeserializeObject(json, new JsonSerializerSettings
1140            {
1141                TypeNameHandling = TypeNameHandling.All,
1142#pragma warning disable 618
1143                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
1144#pragma warning restore 618
1145            });
1146
1147            CustomAssert.IsInstanceOfType(typeof(Dictionary<string, object>), c);
1148
1149            Dictionary<string, object> newCollection = (Dictionary<string, object>)c;
1150            Assert.AreEqual(3, newCollection.Count);
1151            Assert.AreEqual(@"http://www.bing.com", ((UrlStatus)newCollection["First"]).Url);
1152
1153            List<UrlStatus> statues = (List<UrlStatus>)newCollection["List"];
1154            Assert.AreEqual(2, statues.Count);
1155        }
1156
1157        [Test]
1158        public void SerializingIEnumerableOfTShouldRetainGenericTypeInfo()
1159        {
1160            string productClassRef = ReflectionUtils.GetTypeName(typeof(CustomEnumerable<Product>), TypeNameAssemblyFormatHandling.Simple, null);
1161
1162            CustomEnumerable<Product> products = new CustomEnumerable<Product>();
1163
1164            string json = JsonConvert.SerializeObject(products, Formatting.Indented, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
1165
1166            StringAssert.AreEqual(@"{
1167  ""$type"": """ + productClassRef + @""",
1168  ""$values"": []
1169}", json);
1170        }
1171
1172        public class CustomEnumerable<T> : IEnumerable<T>
1173        {
1174            //NOTE: a simple linked list
1175            private readonly T value;
1176            private readonly CustomEnumerable<T> next;
1177            private readonly int count;
1178
1179            private CustomEnumerable(T value, CustomEnumerable<T> next)
1180            {
1181                this.value = value;
1182                this.next = next;
1183                count = this.next.count + 1;
1184            }
1185
1186            public CustomEnumerable()
1187            {
1188                count = 0;
1189            }
1190
1191            public CustomEnumerable<T> AddFirst(T newVal)
1192            {
1193                return new CustomEnumerable<T>(newVal, this);
1194            }
1195
1196            public IEnumerator<T> GetEnumerator()
1197            {
1198                if (count == 0) // last node
1199                {
1200                    yield break;
1201                }
1202                yield return value;
1203
1204                var nextInLine = next;
1205                while (nextInLine != null)
1206                {
1207                    if (nextInLine.count != 0)
1208                    {
1209                        yield return nextInLine.value;
1210                    }
1211                    nextInLine = nextInLine.next;
1212                }
1213            }
1214
1215            IEnumerator IEnumerable.GetEnumerator()
1216            {
1217                return GetEnumerator();
1218            }
1219        }
1220
1221        public class Car
1222        {
1223            // included in JSON
1224            public string Model { get; set; }
1225            public DateTime Year { get; set; }
1226            public List<string> Features { get; set; }
1227            public object[] Objects { get; set; }
1228
1229            // ignored
1230            [JsonIgnore]
1231            public DateTime LastModified { get; set; }
1232        }
1233
1234        [Test]
1235        public void ByteArrays()
1236        {
1237            Car testerObject = new Car();
1238            testerObject.Year = new DateTime(2000, 10, 5, 1, 1, 1, DateTimeKind.Utc);
1239            byte[] data = new byte[] { 75, 65, 82, 73, 82, 65 };
1240            testerObject.Objects = new object[] { data, "prueba" };
1241
1242            JsonSerializerSettings jsonSettings = new JsonSerializerSettings();
1243            jsonSettings.NullValueHandling = NullValueHandling.Ignore;
1244            jsonSettings.TypeNameHandling = TypeNameHandling.All;
1245
1246            string output = JsonConvert.SerializeObject(testerObject, Formatting.Indented, jsonSettings);
1247
1248            string carClassRef = ReflectionUtils.GetTypeName(typeof(Car), TypeNameAssemblyFormatHandling.Simple, null);
1249
1250            StringAssert.AreEqual(output, @"{
1251  ""$type"": """ + carClassRef + @""",
1252  ""Year"": ""2000-10-05T01:01:01Z"",
1253  ""Objects"": {
1254    ""$type"": ""System.Object[], mscorlib"",
1255    ""$values"": [
1256      {
1257        ""$type"": ""System.Byte[], mscorlib"",
1258        ""$value"": ""S0FSSVJB""
1259      },
1260      ""prueba""
1261    ]
1262  }
1263}");
1264            Car obj = JsonConvert.DeserializeObject<Car>(output, jsonSettings);
1265
1266            Assert.IsNotNull(obj);
1267
1268            Assert.IsTrue(obj.Objects[0] is byte[]);
1269
1270            byte[] d = (byte[])obj.Objects[0];
1271            CollectionAssert.AreEquivalent(data, d);
1272        }
1273
1274#if !(DNXCORE50)
1275        [Test]
1276        public void ISerializableTypeNameHandlingTest()
1277        {
1278            //Create an instance of our example type
1279            IExample e = new Example("Rob");
1280
1281            SerializableWrapper w = new SerializableWrapper
1282            {
1283                Content = e
1284            };
1285
1286            //Test Binary Serialization Round Trip
1287            //This will work find because the Binary Formatter serializes type names
1288            //this.TestBinarySerializationRoundTrip(e);
1289
1290            //Test Json Serialization
1291            //This fails because the JsonSerializer doesn't serialize type names correctly for ISerializable objects
1292            //Type Names should be serialized for All, Auto and Object modes
1293            TestJsonSerializationRoundTrip(w, TypeNameHandling.All);
1294            TestJsonSerializationRoundTrip(w, TypeNameHandling.Auto);
1295            TestJsonSerializationRoundTrip(w, TypeNameHandling.Objects);
1296        }
1297
1298        private void TestJsonSerializationRoundTrip(SerializableWrapper e, TypeNameHandling flag)
1299        {
1300            StringWriter writer = new StringWriter();
1301
1302            //Create our serializer and set Type Name Handling appropriately
1303            JsonSerializer serializer = new JsonSerializer();
1304            serializer.TypeNameHandling = flag;
1305
1306            //Do the actual serialization and dump to Console for inspection
1307            serializer.Serialize(new JsonTextWriter(writer), e);
1308
1309            //Now try to deserialize
1310            //Json.Net will cause an error here as it will try and instantiate
1311            //the interface directly because it failed to respect the
1312            //TypeNameHandling property on serialization
1313            SerializableWrapper f = serializer.Deserialize<SerializableWrapper>(new JsonTextReader(new StringReader(writer.ToString())));
1314
1315            //Check Round Trip
1316            Assert.AreEqual(e, f, "Objects should be equal after round trip json serialization");
1317        }
1318#endif
1319
1320#if !(NET20 || NET35)
1321        [Test]
1322        public void SerializationBinderWithFullName()
1323        {
1324            Message message = new Message
1325            {
1326                Address = "jamesnk@testtown.com",
1327                Body = new Version(1, 2, 3, 4)
1328            };
1329
1330            string json = JsonConvert.SerializeObject(message, Formatting.Indented, new JsonSerializerSettings
1331            {
1332                TypeNameHandling = TypeNameHandling.All,
1333#pragma warning disable CS0618 // Type or member is obsolete
1334                TypeNameAssemblyFormat = FormatterAssemblyStyle.Full,
1335                Binder = new MetroBinder(),
1336#pragma warning restore CS0618 // Type or member is obsolete
1337                ContractResolver = new DefaultContractResolver
1338                {
1339#if !(PORTABLE || DNXCORE50)
1340                    IgnoreSerializableAttribute = true
1341#endif
1342                }
1343            });
1344
1345            StringAssert.AreEqual(@"{
1346  ""$type"": "":::MESSAGE:::, AssemblyName"",
1347  ""Address"": ""jamesnk@testtown.com"",
1348  ""Body"": {
1349    ""$type"": "":::VERSION:::, AssemblyName"",
1350    ""Major"": 1,
1351    ""Minor"": 2,
1352    ""Build"": 3,
1353    ""Revision"": 4,
1354    ""MajorRevision"": 0,
1355    ""MinorRevision"": 4
1356  }
1357}", json);
1358        }
1359
1360        public class MetroBinder : SerializationBinder
1361        {
1362            public override Type BindToType(string assemblyName, string typeName)
1363            {
1364                return null;
1365            }
1366
1367            public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
1368            {
1369                assemblyName = "AssemblyName";
1370#if !(DNXCORE50)
1371                typeName = ":::" + serializedType.Name.ToUpper(CultureInfo.InvariantCulture) + ":::";
1372#else
1373                typeName = ":::" + serializedType.Name.ToUpper() + ":::";
1374#endif
1375            }
1376        }
1377#endif
1378
1379        [Test]
1380        public void TypeNameIntList()
1381        {
1382            TypeNameList<int> l = new TypeNameList<int>();
1383            l.Add(1);
1384            l.Add(2);
1385            l.Add(3);
1386
1387            string json = JsonConvert.SerializeObject(l, Formatting.Indented);
1388            StringAssert.AreEqual(@"[
1389  1,
1390  2,
1391  3
1392]", json);
1393        }
1394
1395        [Test]
1396        public void TypeNameComponentList()
1397        {
1398            var c1 = new TestComponentSimple();
1399
1400            TypeNameList<object> l = new TypeNameList<object>();
1401            l.Add(c1);
1402            l.Add(new Employee
1403            {
1404                BirthDate = new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc),
1405                Department = "Department!"
1406            });
1407            l.Add("String!");
1408            l.Add(long.MaxValue);
1409
1410            string json = JsonConvert.SerializeObject(l, Formatting.Indented);
1411            StringAssert.AreEqual(@"[
1412  {
1413    ""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
1414    ""MyProperty"": 0
1415  },
1416  {
1417    ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Organization.Employee, Newtonsoft.Json.Tests"",
1418    ""FirstName"": null,
1419    ""LastName"": null,
1420    ""BirthDate"": ""2000-12-12T12:12:12Z"",
1421    ""Department"": ""Department!"",
1422    ""JobTitle"": null
1423  },
1424  ""String!"",
1425  9223372036854775807
1426]", json);
1427
1428            TypeNameList<object> l2 = JsonConvert.DeserializeObject<TypeNameList<object>>(json);
1429            Assert.AreEqual(4, l2.Count);
1430
1431            CustomAssert.IsInstanceOfType(typeof(TestComponentSimple), l2[0]);
1432            CustomAssert.IsInstanceOfType(typeof(Employee), l2[1]);
1433            CustomAssert.IsInstanceOfType(typeof(string), l2[2]);
1434            CustomAssert.IsInstanceOfType(typeof(long), l2[3]);
1435        }
1436
1437        [Test]
1438        public void TypeNameDictionary()
1439        {
1440      

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