PageRenderTime 82ms CodeModel.GetById 9ms app.highlight 47ms RepoModel.GetById 1ms app.codeStats 2ms

/modules/JSON/Source/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs

https://bitbucket.org/ipre/calico
C# | 10532 lines | 9489 code | 889 blank | 154 comment | 89 complexity | 1710ae0df72a54210941fb297c9bbcbd 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 || SILVERLIGHT)
  29using System.Collections.Concurrent;
  30#endif
  31using System.Collections.Generic;
  32#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
  33using System.Numerics;
  34#endif
  35#if !SILVERLIGHT && !NET20 && !NETFX_CORE
  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 !NETFX_CORE
  46using NUnit.Framework;
  47#else
  48using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
  49using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
  50using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
  51#endif
  52using Newtonsoft.Json;
  53using System.IO;
  54using System.Collections;
  55using System.Xml;
  56using System.Xml.Serialization;
  57using System.Collections.ObjectModel;
  58using Newtonsoft.Json.Bson;
  59using Newtonsoft.Json.Linq;
  60using Newtonsoft.Json.Converters;
  61#if !NET20
  62using System.Runtime.Serialization.Json;
  63#endif
  64using Newtonsoft.Json.Serialization;
  65using Newtonsoft.Json.Tests.Linq;
  66using Newtonsoft.Json.Tests.TestObjects;
  67using System.Runtime.Serialization;
  68using System.Globalization;
  69using Newtonsoft.Json.Utilities;
  70using System.Reflection;
  71#if !NET20 && !SILVERLIGHT
  72using System.Xml.Linq;
  73using System.Collections.Specialized;
  74using System.Linq.Expressions;
  75#endif
  76#if !(NET35 || NET20)
  77using System.Dynamic;
  78#endif
  79#if NET20
  80using Newtonsoft.Json.Utilities.LinqBridge;
  81#else
  82using System.Linq;
  83#endif
  84#if !(SILVERLIGHT || NETFX_CORE)
  85using System.Drawing;
  86using System.Diagnostics;
  87#endif
  88
  89namespace Newtonsoft.Json.Tests.Serialization
  90{
  91  [TestFixture]
  92  public class JsonSerializerTest : TestFixtureBase
  93  {
  94    public class GenericItem<T>
  95    {
  96      public T Value { get; set; }
  97    }
  98
  99    public class NonGenericItem : GenericItem<string>
 100    {
 101
 102    }
 103
 104    public class GenericClass<T, TValue> : IEnumerable<T>
 105      where T : GenericItem<TValue>, new()
 106    {
 107      public IList<T> Items { get; set; }
 108
 109      public GenericClass()
 110      {
 111        Items = new List<T>();
 112      }
 113
 114      public IEnumerator<T> GetEnumerator()
 115      {
 116        if (Items != null)
 117        {
 118          foreach (T item in Items)
 119          {
 120            yield return item;
 121          }
 122        }
 123        else
 124          yield break;
 125      }
 126
 127      IEnumerator IEnumerable.GetEnumerator()
 128      {
 129        return GetEnumerator();
 130      }
 131    }
 132
 133    public class NonGenericClass : GenericClass<GenericItem<string>, string>
 134    {
 135
 136    }
 137
 138#pragma warning disable 169
 139    public class CustomerInvoice
 140    {
 141      // we're only modifing the tax rate
 142      public decimal TaxRate { get; set; }
 143
 144      // everything else gets stored here
 145      [JsonExtensionData]
 146      private IDictionary<string, JToken> _additionalData;
 147    }
 148#pragma warning restore 169
 149
 150    [Test]
 151    public void ExtensionDataExample()
 152    {
 153      string json = @"{
 154        'HourlyRate': 150,
 155        'Hours': 40,
 156        'TaxRate': 0.125
 157      }";
 158
 159      var invoice = JsonConvert.DeserializeObject<CustomerInvoice>(json);
 160
 161      // increase tax to 15%
 162      invoice.TaxRate = 0.15m;
 163
 164      string result = JsonConvert.SerializeObject(invoice);
 165      // {
 166      //   'TaxRate': 0.15,
 167      //   'HourlyRate': 150,
 168      //   'Hours': 40
 169      // }
 170
 171      Assert.AreEqual(@"{""TaxRate"":0.15,""HourlyRate"":150,""Hours"":40}", result);
 172    }
 173
 174    public class ExtensionDataTestClass
 175    {
 176      public string Name { get; set; }
 177      [JsonProperty("custom_name")]
 178      public string CustomName { get; set; }
 179      [JsonIgnore]
 180      public IList<int> Ignored { get; set; }
 181      public bool GetPrivate { get; internal set; }
 182      public bool GetOnly
 183      {
 184        get { return true; }
 185      }
 186      public readonly string Readonly = "Readonly";
 187      public IList<int> Ints { get; set; }
 188        
 189      [JsonExtensionData]
 190      internal IDictionary<string, JToken> ExtensionData { get; set; }
 191
 192      public ExtensionDataTestClass()
 193      {
 194        Ints = new List<int> { 0 };
 195      }
 196    }
 197
 198    public class JObjectExtensionDataTestClass
 199    {
 200      public string Name { get; set; }
 201      [JsonExtensionData]
 202      public JObject ExtensionData { get; set; }
 203    }
 204
 205    [Test]
 206    public void RoundTripJObjectExtensionData()
 207    {
 208      JObjectExtensionDataTestClass c = new JObjectExtensionDataTestClass();
 209      c.Name = "Name!";
 210      c.ExtensionData = new JObject
 211        {
 212          {"one",1},
 213          {"two","II"},
 214          {"three",new JArray(1,1,1)}
 215        };
 216
 217      string json = JsonConvert.SerializeObject(c, Formatting.Indented);
 218
 219      JObjectExtensionDataTestClass c2 = JsonConvert.DeserializeObject<JObjectExtensionDataTestClass>(json);
 220
 221      Assert.AreEqual("Name!", c2.Name);
 222      Assert.IsTrue(JToken.DeepEquals(c.ExtensionData, c2.ExtensionData));
 223    }
 224
 225    [Test]
 226    public void JsonSerializerProperties()
 227    {
 228      JsonSerializer serializer = new JsonSerializer();
 229
 230      DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
 231      serializer.Binder = customBinder;
 232      Assert.AreEqual(customBinder, serializer.Binder);
 233
 234      serializer.CheckAdditionalContent = true;
 235      Assert.AreEqual(true, serializer.CheckAdditionalContent);
 236
 237      serializer.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
 238      Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, serializer.ConstructorHandling);
 239
 240#if !NETFX_CORE
 241      serializer.Context = new StreamingContext(StreamingContextStates.Other);
 242      Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), serializer.Context);
 243#endif
 244
 245      CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
 246      serializer.ContractResolver = resolver;
 247      Assert.AreEqual(resolver, serializer.ContractResolver);
 248
 249      serializer.Converters.Add(new StringEnumConverter());
 250      Assert.AreEqual(1, serializer.Converters.Count);
 251
 252      serializer.Culture = new CultureInfo("en-nz");
 253      Assert.AreEqual("en-NZ", serializer.Culture.ToString());
 254
 255      serializer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
 256      Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, serializer.DateFormatHandling);
 257
 258      serializer.DateFormatString = "yyyy";
 259      Assert.AreEqual("yyyy", serializer.DateFormatString);
 260
 261      serializer.DateParseHandling = DateParseHandling.None;
 262      Assert.AreEqual(DateParseHandling.None, serializer.DateParseHandling);
 263
 264      serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
 265      Assert.AreEqual(DateTimeZoneHandling.Utc, serializer.DateTimeZoneHandling);
 266
 267      serializer.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
 268      Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, serializer.DefaultValueHandling);
 269
 270      serializer.FloatFormatHandling = FloatFormatHandling.Symbol;
 271      Assert.AreEqual(FloatFormatHandling.Symbol, serializer.FloatFormatHandling);
 272
 273      serializer.FloatParseHandling = FloatParseHandling.Decimal;
 274      Assert.AreEqual(FloatParseHandling.Decimal, serializer.FloatParseHandling);
 275
 276      serializer.Formatting = Formatting.Indented;
 277      Assert.AreEqual(Formatting.Indented, serializer.Formatting);
 278
 279      serializer.MaxDepth = 9001;
 280      Assert.AreEqual(9001, serializer.MaxDepth);
 281
 282      serializer.MissingMemberHandling = MissingMemberHandling.Error;
 283      Assert.AreEqual(MissingMemberHandling.Error, serializer.MissingMemberHandling);
 284
 285      serializer.NullValueHandling = NullValueHandling.Ignore;
 286      Assert.AreEqual(NullValueHandling.Ignore, serializer.NullValueHandling);
 287
 288      serializer.ObjectCreationHandling = ObjectCreationHandling.Replace;
 289      Assert.AreEqual(ObjectCreationHandling.Replace, serializer.ObjectCreationHandling);
 290
 291      serializer.PreserveReferencesHandling = PreserveReferencesHandling.All;
 292      Assert.AreEqual(PreserveReferencesHandling.All, serializer.PreserveReferencesHandling);
 293
 294      serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
 295      Assert.AreEqual(ReferenceLoopHandling.Ignore, serializer.ReferenceLoopHandling);
 296
 297      IdReferenceResolver referenceResolver = new IdReferenceResolver();
 298      serializer.ReferenceResolver = referenceResolver;
 299      Assert.AreEqual(referenceResolver, serializer.ReferenceResolver);
 300
 301      serializer.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
 302      Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, serializer.StringEscapeHandling);
 303
 304      MemoryTraceWriter traceWriter = new MemoryTraceWriter();
 305      serializer.TraceWriter = traceWriter;
 306      Assert.AreEqual(traceWriter, serializer.TraceWriter);
 307
 308#if !(PORTABLE || PORTABLE40 || NETFX_CORE || NET20)
 309      serializer.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
 310      Assert.AreEqual(FormatterAssemblyStyle.Full, serializer.TypeNameAssemblyFormat);
 311#endif
 312
 313      serializer.TypeNameHandling = TypeNameHandling.All;
 314      Assert.AreEqual(TypeNameHandling.All, serializer.TypeNameHandling);
 315    }
 316
 317    [Test]
 318    public void JsonSerializerSettingsProperties()
 319    {
 320      JsonSerializerSettings settings = new JsonSerializerSettings();
 321
 322      DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
 323      settings.Binder = customBinder;
 324      Assert.AreEqual(customBinder, settings.Binder);
 325
 326      settings.CheckAdditionalContent = true;
 327      Assert.AreEqual(true, settings.CheckAdditionalContent);
 328
 329      settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
 330      Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, settings.ConstructorHandling);
 331
 332#if !NETFX_CORE
 333      settings.Context = new StreamingContext(StreamingContextStates.Other);
 334      Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), settings.Context);
 335#endif
 336
 337      CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
 338      settings.ContractResolver = resolver;
 339      Assert.AreEqual(resolver, settings.ContractResolver);
 340
 341      settings.Converters.Add(new StringEnumConverter());
 342      Assert.AreEqual(1, settings.Converters.Count);
 343
 344      settings.Culture = new CultureInfo("en-nz");
 345      Assert.AreEqual("en-NZ", settings.Culture.ToString());
 346
 347      settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
 348      Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, settings.DateFormatHandling);
 349
 350      settings.DateFormatString = "yyyy";
 351      Assert.AreEqual("yyyy", settings.DateFormatString);
 352
 353      settings.DateParseHandling = DateParseHandling.None;
 354      Assert.AreEqual(DateParseHandling.None, settings.DateParseHandling);
 355
 356      settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
 357      Assert.AreEqual(DateTimeZoneHandling.Utc, settings.DateTimeZoneHandling);
 358
 359      settings.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
 360      Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, settings.DefaultValueHandling);
 361
 362      settings.FloatFormatHandling = FloatFormatHandling.Symbol;
 363      Assert.AreEqual(FloatFormatHandling.Symbol, settings.FloatFormatHandling);
 364
 365      settings.FloatParseHandling = FloatParseHandling.Decimal;
 366      Assert.AreEqual(FloatParseHandling.Decimal, settings.FloatParseHandling);
 367
 368      settings.Formatting = Formatting.Indented;
 369      Assert.AreEqual(Formatting.Indented, settings.Formatting);
 370
 371      settings.MaxDepth = 9001;
 372      Assert.AreEqual(9001, settings.MaxDepth);
 373
 374      settings.MissingMemberHandling = MissingMemberHandling.Error;
 375      Assert.AreEqual(MissingMemberHandling.Error, settings.MissingMemberHandling);
 376
 377      settings.NullValueHandling = NullValueHandling.Ignore;
 378      Assert.AreEqual(NullValueHandling.Ignore, settings.NullValueHandling);
 379
 380      settings.ObjectCreationHandling = ObjectCreationHandling.Replace;
 381      Assert.AreEqual(ObjectCreationHandling.Replace, settings.ObjectCreationHandling);
 382
 383      settings.PreserveReferencesHandling = PreserveReferencesHandling.All;
 384      Assert.AreEqual(PreserveReferencesHandling.All, settings.PreserveReferencesHandling);
 385
 386      settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
 387      Assert.AreEqual(ReferenceLoopHandling.Ignore, settings.ReferenceLoopHandling);
 388
 389      IdReferenceResolver referenceResolver = new IdReferenceResolver();
 390      settings.ReferenceResolver = referenceResolver;
 391      Assert.AreEqual(referenceResolver, settings.ReferenceResolver);
 392
 393      settings.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
 394      Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, settings.StringEscapeHandling);
 395
 396      MemoryTraceWriter traceWriter = new MemoryTraceWriter();
 397      settings.TraceWriter = traceWriter;
 398      Assert.AreEqual(traceWriter, settings.TraceWriter);
 399
 400#if !(PORTABLE || PORTABLE40 || NETFX_CORE || NET20)
 401      settings.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
 402      Assert.AreEqual(FormatterAssemblyStyle.Full, settings.TypeNameAssemblyFormat);
 403#endif
 404
 405      settings.TypeNameHandling = TypeNameHandling.All;
 406      Assert.AreEqual(TypeNameHandling.All, settings.TypeNameHandling);
 407    }
 408
 409    [Test]
 410    public void JsonSerializerProxyProperties()
 411    {
 412      JsonSerializerProxy serializerProxy = new JsonSerializerProxy(new JsonSerializerInternalReader(new JsonSerializer()));
 413
 414      DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
 415      serializerProxy.Binder = customBinder;
 416      Assert.AreEqual(customBinder, serializerProxy.Binder);
 417
 418      serializerProxy.CheckAdditionalContent = true;
 419      Assert.AreEqual(true, serializerProxy.CheckAdditionalContent);
 420
 421      serializerProxy.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
 422      Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, serializerProxy.ConstructorHandling);
 423
 424#if !NETFX_CORE
 425      serializerProxy.Context = new StreamingContext(StreamingContextStates.Other);
 426      Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), serializerProxy.Context);
 427#endif
 428
 429      CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
 430      serializerProxy.ContractResolver = resolver;
 431      Assert.AreEqual(resolver, serializerProxy.ContractResolver);
 432
 433      serializerProxy.Converters.Add(new StringEnumConverter());
 434      Assert.AreEqual(1, serializerProxy.Converters.Count);
 435
 436      serializerProxy.Culture = new CultureInfo("en-nz");
 437      Assert.AreEqual("en-NZ", serializerProxy.Culture.ToString());
 438
 439      serializerProxy.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
 440      Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, serializerProxy.DateFormatHandling);
 441
 442      serializerProxy.DateFormatString = "yyyy";
 443      Assert.AreEqual("yyyy", serializerProxy.DateFormatString);
 444
 445      serializerProxy.DateParseHandling = DateParseHandling.None;
 446      Assert.AreEqual(DateParseHandling.None, serializerProxy.DateParseHandling);
 447
 448      serializerProxy.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
 449      Assert.AreEqual(DateTimeZoneHandling.Utc, serializerProxy.DateTimeZoneHandling);
 450
 451      serializerProxy.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
 452      Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, serializerProxy.DefaultValueHandling);
 453
 454      serializerProxy.FloatFormatHandling = FloatFormatHandling.Symbol;
 455      Assert.AreEqual(FloatFormatHandling.Symbol, serializerProxy.FloatFormatHandling);
 456
 457      serializerProxy.FloatParseHandling = FloatParseHandling.Decimal;
 458      Assert.AreEqual(FloatParseHandling.Decimal, serializerProxy.FloatParseHandling);
 459
 460      serializerProxy.Formatting = Formatting.Indented;
 461      Assert.AreEqual(Formatting.Indented, serializerProxy.Formatting);
 462
 463      serializerProxy.MaxDepth = 9001;
 464      Assert.AreEqual(9001, serializerProxy.MaxDepth);
 465
 466      serializerProxy.MissingMemberHandling = MissingMemberHandling.Error;
 467      Assert.AreEqual(MissingMemberHandling.Error, serializerProxy.MissingMemberHandling);
 468
 469      serializerProxy.NullValueHandling = NullValueHandling.Ignore;
 470      Assert.AreEqual(NullValueHandling.Ignore, serializerProxy.NullValueHandling);
 471
 472      serializerProxy.ObjectCreationHandling = ObjectCreationHandling.Replace;
 473      Assert.AreEqual(ObjectCreationHandling.Replace, serializerProxy.ObjectCreationHandling);
 474
 475      serializerProxy.PreserveReferencesHandling = PreserveReferencesHandling.All;
 476      Assert.AreEqual(PreserveReferencesHandling.All, serializerProxy.PreserveReferencesHandling);
 477
 478      serializerProxy.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
 479      Assert.AreEqual(ReferenceLoopHandling.Ignore, serializerProxy.ReferenceLoopHandling);
 480
 481      IdReferenceResolver referenceResolver = new IdReferenceResolver();
 482      serializerProxy.ReferenceResolver = referenceResolver;
 483      Assert.AreEqual(referenceResolver, serializerProxy.ReferenceResolver);
 484
 485      serializerProxy.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
 486      Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, serializerProxy.StringEscapeHandling);
 487
 488      MemoryTraceWriter traceWriter = new MemoryTraceWriter();
 489      serializerProxy.TraceWriter = traceWriter;
 490      Assert.AreEqual(traceWriter, serializerProxy.TraceWriter);
 491
 492#if !(PORTABLE || PORTABLE40 || NETFX_CORE || NET20)
 493      serializerProxy.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
 494      Assert.AreEqual(FormatterAssemblyStyle.Full, serializerProxy.TypeNameAssemblyFormat);
 495#endif
 496
 497      serializerProxy.TypeNameHandling = TypeNameHandling.All;
 498      Assert.AreEqual(TypeNameHandling.All, serializerProxy.TypeNameHandling);
 499    }
 500
 501#if !(NETFX_CORE || PORTABLE || PORTABLE40)
 502    [Test]
 503    public void DeserializeISerializableIConvertible()
 504    {
 505      Ratio ratio = new Ratio(2, 1);
 506      string json = JsonConvert.SerializeObject(ratio);
 507
 508      Assert.AreEqual(@"{""n"":2,""d"":1}", json);
 509
 510      Ratio ratio2 = JsonConvert.DeserializeObject<Ratio>(json);
 511
 512      Assert.AreEqual(ratio.Denominator, ratio2.Denominator);
 513      Assert.AreEqual(ratio.Numerator, ratio2.Numerator);
 514    }
 515#endif
 516
 517    [Test]
 518    public void DeserializeLargeFloat()
 519    {
 520      object o = JsonConvert.DeserializeObject("100000000000000000000000000000000000000.0");
 521
 522      CustomAssert.IsInstanceOfType(typeof(double), o);
 523
 524      Assert.IsTrue(MathUtils.ApproxEquals(1E+38, (double)o));
 525    }
 526
 527    [Test]
 528    public void SerializeDeserializeRegex()
 529    {
 530      Regex regex = new Regex("(hi)", RegexOptions.CultureInvariant);
 531
 532      string json = JsonConvert.SerializeObject(regex, Formatting.Indented);
 533
 534      Regex r2 = JsonConvert.DeserializeObject<Regex>(json);
 535
 536      Assert.AreEqual("(hi)", r2.ToString());
 537      Assert.AreEqual(RegexOptions.CultureInvariant, r2.Options);
 538    }
 539
 540    [Test]
 541    public void ExtensionDataTest()
 542    {
 543      string json = @"{
 544  ""Ints"": [1,2,3],
 545  ""Ignored"": [1,2,3],
 546  ""Readonly"": ""Readonly"",
 547  ""Name"": ""Actually set!"",
 548  ""CustomName"": ""Wrong name!"",
 549  ""GetPrivate"": true,
 550  ""GetOnly"": true,
 551  ""NewValueSimple"": true,
 552  ""NewValueComplex"": [1,2,3]
 553}";
 554
 555      ExtensionDataTestClass c = JsonConvert.DeserializeObject<ExtensionDataTestClass>(json);
 556
 557      Assert.AreEqual("Actually set!", c.Name);
 558      Assert.AreEqual(4, c.Ints.Count);
 559      
 560      Assert.AreEqual("Readonly", (string)c.ExtensionData["Readonly"]);
 561      Assert.AreEqual("Wrong name!", (string)c.ExtensionData["CustomName"]);
 562      Assert.AreEqual(true, (bool)c.ExtensionData["GetPrivate"]);
 563      Assert.AreEqual(true, (bool)c.ExtensionData["GetOnly"]);
 564      Assert.AreEqual(true, (bool)c.ExtensionData["NewValueSimple"]);
 565      Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), c.ExtensionData["NewValueComplex"]));
 566      Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), c.ExtensionData["Ignored"]));
 567
 568      Assert.AreEqual(7, c.ExtensionData.Count);
 569    }
 570
 571    public class MultipleExtensionDataAttributesTestClass
 572    {
 573      public string Name { get; set; }
 574      [JsonExtensionData]
 575      internal IDictionary<string, JToken> ExtensionData1 { get; set; }
 576      [JsonExtensionData]
 577      internal IDictionary<string, JToken> ExtensionData2 { get; set; }
 578    }
 579
 580    public class ExtensionDataAttributesInheritanceTestClass : MultipleExtensionDataAttributesTestClass
 581    {
 582      [JsonExtensionData]
 583      internal IDictionary<string, JToken> ExtensionData0 { get; set; }
 584    }
 585
 586    public class FieldExtensionDataAttributeTestClass
 587    {
 588      [JsonExtensionData]
 589      internal IDictionary<object, object> ExtensionData;
 590    }
 591
 592    public class PublicExtensionDataAttributeTestClass
 593    {
 594      public string Name { get; set; }
 595      [JsonExtensionData]
 596      public IDictionary<object, object> ExtensionData;
 597    }
 598
 599    public class PublicNoReadExtensionDataAttributeTestClass
 600    {
 601      public string Name { get; set; }
 602      [JsonExtensionData(ReadData = false)]
 603      public IDictionary<object, object> ExtensionData;
 604    }
 605
 606    public class PublicNoWriteExtensionDataAttributeTestClass
 607    {
 608      public string Name { get; set; }
 609      [JsonExtensionData(WriteData = false)]
 610      public IDictionary<object, object> ExtensionData;
 611    }
 612
 613    public class PublicJTokenExtensionDataAttributeTestClass
 614    {
 615      public string Name { get; set; }
 616      [JsonExtensionData]
 617      public IDictionary<string, JToken> ExtensionData;
 618    }
 619
 620    [Test]
 621    public void DeserializeDirectoryAccount()
 622    {
 623      string json = @"{'DisplayName':'John Smith', 'SAMAccountName':'contoso\\johns'}";
 624
 625      DirectoryAccount account = JsonConvert.DeserializeObject<DirectoryAccount>(json);
 626
 627      Assert.AreEqual("John Smith", account.DisplayName);
 628      Assert.AreEqual("contoso", account.Domain);
 629      Assert.AreEqual("johns", account.UserName);
 630    }
 631
 632    [Test]
 633    public void SerializePublicExtensionData()
 634    {
 635      string json = JsonConvert.SerializeObject(new PublicExtensionDataAttributeTestClass
 636        {
 637          Name = "Name!",
 638          ExtensionData = new Dictionary<object, object>
 639            {
 640              { "Test", 1 }
 641            }
 642        });
 643
 644      Assert.AreEqual(@"{""Name"":""Name!"",""Test"":1}", json);
 645    }
 646
 647    [Test]
 648    public void SerializePublicExtensionDataNull()
 649    {
 650      string json = JsonConvert.SerializeObject(new PublicExtensionDataAttributeTestClass
 651      {
 652        Name = "Name!"
 653      });
 654
 655      Assert.AreEqual(@"{""Name"":""Name!""}", json);
 656    }
 657
 658    [Test]
 659    public void SerializePublicNoWriteExtensionData()
 660    {
 661      string json = JsonConvert.SerializeObject(new PublicNoWriteExtensionDataAttributeTestClass
 662      {
 663        Name = "Name!",
 664        ExtensionData = new Dictionary<object, object>
 665            {
 666              { "Test", 1 }
 667            }
 668      });
 669
 670      Assert.AreEqual(@"{""Name"":""Name!""}", json);
 671    }
 672
 673    [Test]
 674    public void DeserializeNoReadPublicExtensionData()
 675    {
 676      PublicNoReadExtensionDataAttributeTestClass c = JsonConvert.DeserializeObject<PublicNoReadExtensionDataAttributeTestClass>(@"{""Name"":""Name!"",""Test"":1}");
 677
 678      Assert.AreEqual(null, c.ExtensionData);
 679    }
 680
 681    [Test]
 682    public void SerializePublicExtensionDataCircularReference()
 683    {
 684      var c = new PublicExtensionDataAttributeTestClass
 685        {
 686          Name = "Name!",
 687          ExtensionData = new Dictionary<object, object>
 688            {
 689              { "Test", 1 }
 690            }
 691        };
 692      c.ExtensionData["Self"] = c;
 693
 694      string json = JsonConvert.SerializeObject(c, new JsonSerializerSettings
 695        {
 696          PreserveReferencesHandling = PreserveReferencesHandling.All,
 697          Formatting = Formatting.Indented
 698        });
 699
 700      Assert.AreEqual(@"{
 701  ""$id"": ""1"",
 702  ""Name"": ""Name!"",
 703  ""Test"": 1,
 704  ""Self"": {
 705    ""$ref"": ""1""
 706  }
 707}", json);
 708
 709      var c2 = JsonConvert.DeserializeObject<PublicExtensionDataAttributeTestClass>(json, new JsonSerializerSettings
 710        {
 711          PreserveReferencesHandling = PreserveReferencesHandling.All
 712        });
 713
 714      Assert.AreEqual("Name!", c2.Name);
 715
 716      PublicExtensionDataAttributeTestClass bizzaroC2 = (PublicExtensionDataAttributeTestClass)c2.ExtensionData["Self"];
 717
 718      Assert.AreEqual(c2, bizzaroC2);
 719      Assert.AreEqual(1, (long)bizzaroC2.ExtensionData["Test"]);
 720    }
 721
 722    [Test]
 723    public void DeserializePublicJTokenExtensionDataCircularReference()
 724    {
 725      string json = @"{
 726  ""$id"": ""1"",
 727  ""Name"": ""Name!"",
 728  ""Test"": 1,
 729  ""Self"": {
 730    ""$ref"": ""1""
 731  }
 732}";
 733
 734      var c2 = JsonConvert.DeserializeObject<PublicJTokenExtensionDataAttributeTestClass>(json, new JsonSerializerSettings
 735      {
 736        PreserveReferencesHandling = PreserveReferencesHandling.All
 737      });
 738
 739      Assert.AreEqual("Name!", c2.Name);
 740
 741      JObject bizzaroC2 = (JObject)c2.ExtensionData["Self"];
 742
 743      Assert.AreEqual("Name!", (string)bizzaroC2["Name"]);
 744      Assert.AreEqual(1, (int)bizzaroC2["Test"]);
 745
 746      Assert.AreEqual(1, (int)c2.ExtensionData["Test"]);
 747    }
 748
 749    [Test]
 750    public void DeserializePublicExtensionDataTypeNamdHandling()
 751    {
 752      string json = @"{
 753  ""$id"": ""1"",
 754  ""Name"": ""Name!"",
 755  ""Test"": 1,
 756  ""Self"": {
 757    ""$type"": ""Newtonsoft.Json.Tests.TestObjects.WagePerson, Newtonsoft.Json.Tests"",
 758    ""HourlyWage"": 2.0,
 759    ""Name"": null,
 760    ""BirthDate"": ""0001-01-01T00:00:00"",
 761    ""LastModified"": ""0001-01-01T00:00:00""
 762  }
 763}";
 764
 765      PublicExtensionDataAttributeTestClass c2 = JsonConvert.DeserializeObject<PublicExtensionDataAttributeTestClass>(json, new JsonSerializerSettings
 766      {
 767        TypeNameHandling = TypeNameHandling.Objects
 768      });
 769
 770      Assert.AreEqual("Name!", c2.Name);
 771
 772      WagePerson bizzaroC2 = (WagePerson)c2.ExtensionData["Self"];
 773
 774      Assert.AreEqual(2m, bizzaroC2.HourlyWage);
 775    }
 776
 777    [Test]
 778    public void SerializePublicExtensionDataTypeNamdHandling()
 779    {
 780      PublicExtensionDataAttributeTestClass c = new PublicExtensionDataAttributeTestClass
 781        {
 782          Name = "Name!",
 783          ExtensionData = new Dictionary<object, object>
 784            {
 785              {
 786                "Test", new WagePerson
 787                  {
 788                    HourlyWage = 2.1m
 789                  }
 790              }
 791            }
 792        };
 793
 794      string json = JsonConvert.SerializeObject(c, new JsonSerializerSettings
 795        {
 796          TypeNameHandling = TypeNameHandling.Objects,
 797          Formatting = Formatting.Indented
 798        });
 799
 800      Assert.AreEqual(@"{
 801  ""$type"": ""Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+PublicExtensionDataAttributeTestClass, Newtonsoft.Json.Tests"",
 802  ""Name"": ""Name!"",
 803  ""Test"": {
 804    ""$type"": ""Newtonsoft.Json.Tests.TestObjects.WagePerson, Newtonsoft.Json.Tests"",
 805    ""HourlyWage"": 2.1,
 806    ""Name"": null,
 807    ""BirthDate"": ""0001-01-01T00:00:00"",
 808    ""LastModified"": ""0001-01-01T00:00:00""
 809  }
 810}", json);
 811    }
 812
 813    [Test]
 814    public void DeserializePublicExtensionData()
 815    {
 816      string json = @"{
 817  'Name':'Name!',
 818  'NoMatch':'NoMatch!',
 819  'ExtensionData':{'HAI':true}
 820}";
 821
 822      var c = JsonConvert.DeserializeObject<PublicExtensionDataAttributeTestClass>(json);
 823
 824      Assert.AreEqual("Name!", c.Name);
 825      Assert.AreEqual(2, c.ExtensionData.Count);
 826
 827      Assert.AreEqual("NoMatch!", (string)c.ExtensionData["NoMatch"]);
 828
 829      // the ExtensionData property is put into the extension data
 830      // inception
 831      var o = (JObject)c.ExtensionData["ExtensionData"];
 832      Assert.AreEqual(1, o.Count);
 833      Assert.IsTrue(JToken.DeepEquals(new JObject { { "HAI", true } }, o));
 834    }
 835
 836    [Test]
 837    public void FieldExtensionDataAttributeTest_Serialize()
 838    {
 839      FieldExtensionDataAttributeTestClass c = new FieldExtensionDataAttributeTestClass
 840        {
 841          ExtensionData = new Dictionary<object, object>()
 842        };
 843
 844      string json = JsonConvert.SerializeObject(c);
 845
 846      Assert.AreEqual("{}", json);
 847    }
 848
 849    [Test]
 850    public void FieldExtensionDataAttributeTest_Deserialize()
 851    {
 852      var c = JsonConvert.DeserializeObject<FieldExtensionDataAttributeTestClass>("{'first':1,'second':2}");
 853
 854      Assert.AreEqual(2, c.ExtensionData.Count);
 855      Assert.AreEqual(1, (long)c.ExtensionData["first"]);
 856      Assert.AreEqual(2, (long)c.ExtensionData["second"]);
 857    }
 858
 859    [Test]
 860    public void MultipleExtensionDataAttributesTest()
 861    {
 862      var c = JsonConvert.DeserializeObject<MultipleExtensionDataAttributesTestClass>("{'first':[1],'second':[2]}");
 863
 864      Assert.AreEqual(null, c.ExtensionData1);
 865      Assert.AreEqual(2, c.ExtensionData2.Count);
 866      Assert.AreEqual(1, (int)((JArray)c.ExtensionData2["first"])[0]);
 867      Assert.AreEqual(2, (int)((JArray)c.ExtensionData2["second"])[0]);
 868    }
 869
 870    [Test]
 871    public void ExtensionDataAttributesInheritanceTest()
 872    {
 873      var c = JsonConvert.DeserializeObject<ExtensionDataAttributesInheritanceTestClass>("{'first':1,'second':2}");
 874
 875      Assert.AreEqual(null, c.ExtensionData1);
 876      Assert.AreEqual(null, c.ExtensionData2);
 877      Assert.AreEqual(2, c.ExtensionData0.Count);
 878      Assert.AreEqual(1, (int)c.ExtensionData0["first"]);
 879      Assert.AreEqual(2, (int)c.ExtensionData0["second"]);
 880    }
 881
 882    [Test]
 883    public void GenericCollectionInheritance()
 884    {
 885      string json;
 886
 887      GenericClass<GenericItem<string>, string> foo1 = new GenericClass<GenericItem<string>, string>();
 888      foo1.Items.Add(new GenericItem<string> {Value = "Hello"});
 889
 890      json = JsonConvert.SerializeObject(new {selectList = foo1});
 891      Assert.AreEqual(@"{""selectList"":[{""Value"":""Hello""}]}", json);
 892
 893      GenericClass<NonGenericItem, string> foo2 = new GenericClass<NonGenericItem, string>();
 894      foo2.Items.Add(new NonGenericItem {Value = "Hello"});
 895
 896      json = JsonConvert.SerializeObject(new { selectList = foo2 });
 897      Assert.AreEqual(@"{""selectList"":[{""Value"":""Hello""}]}", json);
 898
 899      NonGenericClass foo3 = new NonGenericClass();
 900      foo3.Items.Add(new NonGenericItem {Value = "Hello"});
 901
 902      json = JsonConvert.SerializeObject(new { selectList = foo3 });
 903      Assert.AreEqual(@"{""selectList"":[{""Value"":""Hello""}]}", json);
 904    }
 905
 906#if !NET20
 907    [DataContract]
 908    public class BaseDataContractWithHidden
 909    {
 910      [DataMember(Name = "virtualMember")]
 911      public virtual string VirtualMember { get; set; }
 912
 913      [DataMember(Name = "nonVirtualMember")]
 914      public string NonVirtualMember { get; set; }
 915
 916      public virtual object NewMember { get; set; }
 917    }
 918
 919    public class ChildDataContractWithHidden : BaseDataContractWithHidden
 920    {
 921      [DataMember(Name = "NewMember")]
 922      public virtual new string NewMember { get; set; }
 923      public override string VirtualMember { get; set; }
 924      public string AddedMember { get; set; }
 925    }
 926
 927    [Test]
 928    public void ChildDataContractTestWithHidden()
 929    {
 930      var cc = new ChildDataContractWithHidden
 931      {
 932        VirtualMember = "VirtualMember!",
 933        NonVirtualMember = "NonVirtualMember!",
 934        NewMember = "NewMember!"
 935      };
 936
 937      string result = JsonConvert.SerializeObject(cc);
 938      Assert.AreEqual(@"{""NewMember"":""NewMember!"",""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
 939    }
 940
 941    // ignore hiding members compiler warning
 942#pragma warning disable 108,114
 943    [DataContract]
 944    public class BaseWithContract
 945    {
 946      [DataMember(Name = "VirtualWithDataMemberBase")]
 947      public virtual string VirtualWithDataMember { get; set; }
 948      [DataMember]
 949      public virtual string Virtual { get; set; }
 950      [DataMember(Name = "WithDataMemberBase")]
 951      public string WithDataMember { get; set; }
 952      [DataMember]
 953      public string JustAProperty { get; set; }
 954    }
 955
 956    [DataContract]
 957    public class BaseWithoutContract
 958    {
 959      [DataMember(Name = "VirtualWithDataMemberBase")]
 960      public virtual string VirtualWithDataMember { get; set; }
 961      [DataMember]
 962      public virtual string Virtual { get; set; }
 963      [DataMember(Name = "WithDataMemberBase")]
 964      public string WithDataMember { get; set; }
 965      [DataMember]
 966      public string JustAProperty { get; set; }
 967    }
 968
 969    [DataContract]
 970    public class SubWithoutContractNewProperties : BaseWithContract
 971    {
 972      [DataMember(Name = "VirtualWithDataMemberSub")]
 973      public string VirtualWithDataMember { get; set; }
 974      public string Virtual { get; set; }
 975      [DataMember(Name = "WithDataMemberSub")]
 976      public string WithDataMember { get; set; }
 977      public string JustAProperty { get; set; }
 978    }
 979
 980    [DataContract]
 981    public class SubWithoutContractVirtualProperties : BaseWithContract
 982    {
 983      public override string VirtualWithDataMember { get; set; }
 984      [DataMember(Name = "VirtualSub")]
 985      public override string Virtual { get; set; }
 986    }
 987
 988    [DataContract]
 989    public class SubWithContractNewProperties : BaseWithContract
 990    {
 991      [DataMember(Name = "VirtualWithDataMemberSub")]
 992      public string VirtualWithDataMember { get; set; }
 993      [DataMember(Name = "Virtual2")]
 994      public string Virtual { get; set; }
 995      [DataMember(Name = "WithDataMemberSub")]
 996      public string WithDataMember { get; set; }
 997      [DataMember(Name = "JustAProperty2")]
 998      public string JustAProperty { get; set; }
 999    }
1000
1001    [DataContract]
1002    public class SubWithContractVirtualProperties : BaseWithContract
1003    {
1004      [DataMember(Name = "VirtualWithDataMemberSub")]
1005      public virtual string VirtualWithDataMember { get; set; }
1006    }
1007#pragma warning restore 108,114
1008
1009    [Test]
1010    public void SubWithoutContractNewPropertiesTest()
1011    {
1012      BaseWithContract baseWith = new SubWithoutContractNewProperties
1013        {
1014          JustAProperty = "JustAProperty!",
1015          Virtual = "Virtual!",
1016          VirtualWithDataMember = "VirtualWithDataMember!",
1017          WithDataMember = "WithDataMember!"
1018        };
1019
1020      baseWith.JustAProperty = "JustAProperty2!";
1021      baseWith.Virtual = "Virtual2!";
1022      baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
1023      baseWith.WithDataMember = "WithDataMember2!";
1024
1025      string json = AssertSerializeDeserializeEqual(baseWith);
1026
1027      Assert.AreEqual(@"{
1028  ""JustAProperty"": ""JustAProperty2!"",
1029  ""Virtual"": ""Virtual2!"",
1030  ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
1031  ""VirtualWithDataMemberSub"": ""VirtualWithDataMember!"",
1032  ""WithDataMemberBase"": ""WithDataMember2!"",
1033  ""WithDataMemberSub"": ""WithDataMember!""
1034}", json);
1035    }
1036
1037    [Test]
1038    public void SubWithoutContractVirtualPropertiesTest()
1039    {
1040      BaseWithContract baseWith = new SubWithoutContractVirtualProperties
1041      {
1042        JustAProperty = "JustAProperty!",
1043        Virtual = "Virtual!",
1044        VirtualWithDataMember = "VirtualWithDataMember!",
1045        WithDataMember = "WithDataMember!"
1046      };
1047
1048      baseWith.JustAProperty = "JustAProperty2!";
1049      baseWith.Virtual = "Virtual2!";
1050      baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
1051      baseWith.WithDataMember = "WithDataMember2!";
1052
1053      string json = JsonConvert.SerializeObject(baseWith, Formatting.Indented);
1054
1055      Console.WriteLine(json);
1056
1057      Assert.AreEqual(@"{
1058  ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
1059  ""VirtualSub"": ""Virtual2!"",
1060  ""WithDataMemberBase"": ""WithDataMember2!"",
1061  ""JustAProperty"": ""JustAProperty2!""
1062}", json);
1063    }
1064
1065    [Test]
1066    public void SubWithContractNewPropertiesTest()
1067    {
1068      BaseWithContract baseWith = new SubWithContractNewProperties
1069      {
1070        JustAProperty = "JustAProperty!",
1071        Virtual = "Virtual!",
1072        VirtualWithDataMember = "VirtualWithDataMember!",
1073        WithDataMember = "WithDataMember!"
1074      };
1075
1076      baseWith.JustAProperty = "JustAProperty2!";
1077      baseWith.Virtual = "Virtual2!";
1078      baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
1079      baseWith.WithDataMember = "WithDataMember2!";
1080
1081      string json = AssertSerializeDeserializeEqual(baseWith);
1082
1083      Assert.AreEqual(@"{
1084  ""JustAProperty"": ""JustAProperty2!"",
1085  ""JustAProperty2"": ""JustAProperty!"",
1086  ""Virtual"": ""Virtual2!"",
1087  ""Virtual2"": ""Virtual!"",
1088  ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
1089  ""VirtualWithDataMemberSub"": ""VirtualWithDataMember!"",
1090  ""WithDataMemberBase"": ""WithDataMember2!"",
1091  ""WithDataMemberSub"": ""WithDataMember!""
1092}", json);
1093    }
1094
1095    [Test]
1096    public void SubWithContractVirtualPropertiesTest()
1097    {
1098      BaseWithContract baseWith = new SubWithContractVirtualProperties
1099      {
1100        JustAProperty = "JustAProperty!",
1101        Virtual = "Virtual!",
1102        VirtualWithDataMember = "VirtualWithDataMember!",
1103        WithDataMember = "WithDataMember!"
1104      };
1105
1106      baseWith.JustAProperty = "JustAProperty2!";
1107      baseWith.Virtual = "Virtual2!";
1108      baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
1109      baseWith.WithDataMember = "WithDataMember2!";
1110
1111      string json = AssertSerializeDeserializeEqual(baseWith);
1112
1113      Assert.AreEqual(@"{
1114  ""JustAProperty"": ""JustAProperty2!"",
1115  ""Virtual"": ""Virtual2!"",
1116  ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
1117  ""VirtualWithDataMemberSub"": ""VirtualWithDataMember!"",
1118  ""WithDataMemberBase"": ""WithDataMember2!""
1119}", json);
1120    }
1121
1122    private string AssertSerializeDeserializeEqual(object o)
1123    {
1124      MemoryStream ms = new MemoryStream();
1125      DataContractJsonSerializer s = new DataContractJsonSerializer(o.GetType());
1126      s.WriteObject(ms, o);
1127
1128      var data = ms.ToArray();
1129      JObject dataContractJson = JObject.Parse(Encoding.UTF8.GetString(data, 0, data.Length));
1130      dataContractJson = new JObject(dataContractJson.Properties().OrderBy(p => p.Name));
1131
1132      JObject jsonNetJson = JObject.Parse(JsonConvert.SerializeObject(o));
1133      jsonNetJson = new JObject(jsonNetJson.Properties().OrderBy(p => p.Name));
1134
1135      Console.WriteLine("Results for " + o.GetType().Name);
1136      Console.WriteLine("DataContractJsonSerializer: " + dataContractJson);
1137      Console.WriteLine("JsonDotNetSerializer      : " + jsonNetJson);
1138
1139      Assert.AreEqual(dataContractJson.Count, jsonNetJson.Count);
1140      foreach (KeyValuePair<string, JToken> property in dataContractJson)
1141      {
1142        Assert.IsTrue(JToken.DeepEquals(jsonNetJson[property.Key], property.Value), "Property not equal: " + property.Key);
1143      }
1144
1145      return jsonNetJson.ToString();
1146    }
1147#endif
1148
1149    [Test]
1150    public void PersonTypedObjectDeserialization()
1151    {
1152      Store store = new Store();
1153
1154      string jsonText = JsonConvert.SerializeObject(store);
1155
1156      Store deserializedStore = (Store)JsonConvert.DeserializeObject(jsonText, typeof(Store));
1157
1158      Assert.AreEqual(store.Establised, deserializedStore.Establised);
1159      Assert.AreEqual(store.product.Count, deserializedStore.product.Count);
1160
1161      Console.WriteLine(jsonText);
1162    }
1163
1164    [Test]
1165    public void TypedObjectDeserialization()
1166    {
1167      Product product = new Product();
1168
1169      product.Name = "Apple";
1170      product.ExpiryDate = new DateTime(2008, 12, 28);
1171      product.Price = 3.99M;
1172      product.Sizes = new string[] { "Small", "Medium", "Large" };
1173
1174      string output = JsonConvert.SerializeObject(product);
1175      //{
1176      //  "Name": "Apple",
1177      //  "ExpiryDate": "\/Date(1230375600000+1300)\/",
1178      //  "Price": 3.99,
1179      //  "Sizes": [
1180      //    "Small",
1181      //    "Medium",
1182      //    "Large"
1183      //  ]
1184      //}
1185
1186      Product deserializedProduct = (Product)JsonConvert.DeserializeObject(output, typeof(Product));
1187
1188      Assert.AreEqual("Apple", deserializedProduct.Name);
1189      Assert.AreEqual(new DateTime(2008, 12, 28), deserializedProduct.ExpiryDate);
1190      Assert.AreEqual(3.99m, deserializedProduct.Price);
1191      Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
1192      Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
1193      Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
1194    }
1195
1196    //[Test]
1197    //public void Advanced()
1198    //{
1199    //  Product product = new Product();
1200    //  product.ExpiryDate = new DateTime(2008, 12, 28);
1201
1202    //  JsonSerializer serializer = new JsonSerializer();
1203    //  serializer.Converters.Add(new JavaScriptDateTimeConverter());
1204    //  serializer.NullValueHandling = NullValueHandling.Ignore;
1205
1206    //  using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
1207    //  using (JsonWriter writer = new JsonTextWriter(sw))
1208    //  {
1209    //    serializer.Serialize(writer, product);
1210    //    // {"ExpiryDate":new Date(1230375600000),"Price":0}
1211    //  }
1212    //}
1213
1214    [Test]
1215    public void JsonConvertSerializer()
1216    {
1217      string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
1218
1219      Product p = JsonConvert.DeserializeObject(value, typeof(Product)) as Product;
1220
1221      Assert.AreEqual("Orange", p.Name);
1222      Assert.AreEqual(new DateTime(2010, 1, 24, 12, 0, 0), p.ExpiryDate);
1223      Assert.AreEqual(3.99m, p.Price);
1224    }
1225
1226    [Test]
1227    public void DeserializeJavaScriptDate()
1228    {
1229      DateTime dateValue = new DateTime(2010, 3, 30);
1230      Dictionary<string, object> testDictionary = new Dictionary<string, object>();
1231      testDictionary["date"] = dateValue;
1232
1233      string jsonText = JsonConvert.SerializeObject(testDictionary);
1234
1235#if !NET20
1236      MemoryStream ms = new MemoryStream();
1237      DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<string, object>));
1238      serializer.WriteObject(ms, testDictionary);
1239
1240      byte[] data = ms.ToArray();
1241      string output = Encoding.UTF8.GetString(data, 0, data.Length);
1242#endif
1243
1244      Dictionary<string, object> deserializedDictionary = (Dictionary<string, object>)JsonConvert.DeserializeObject(jsonText, typeof(Dictionary<string, object>));
1245      DateTime deserializedDate = (DateTime)deserializedDictionary["date"];
1246
1247      Assert.AreEqual(dateValue, deserializedDate);
1248    }
1249
1250    [Test]
1251    public void TestMethodExecutorObject()
1252    {
1253      MethodExecutorObject executorObject = new MethodExecutorObject();
1254      executorObject.serverClassName = "BanSubs";
1255      executorObject.serverMethodParams = new object[] { "21321546", "101", "1236", "D:\\1.txt" };
1256      executorObject.clientGetResultFunction = "ClientBanSubsCB";
1257
1258      string output = JsonConvert.SerializeObject(executorObject);
1259
1260      MethodExecutorObject executorObject2 = JsonConvert.DeserializeObject(output, typeof(MethodExecutorObject)) as MethodExecutorObject;
1261
1262      Assert.AreNotSame(executorObject, executorObject2);
1263      Assert.AreEqual(executorObject2.serverClassName, "BanSubs");
1264      Assert.AreEqual(executorObject2.serverMethodParams.Length, 4);
1265      CustomAssert.Contains(executorObject2.serverMethodParams, "101");
1266      Assert.AreEqual(executorObject2.clientGetResultFunction, "ClientBanSubsCB");
1267    }
1268
1269#if !SILVERLIGHT && !NETFX_CORE
1270    [Test]
1271    public void HashtableDeserialization()
1272    {
1273      string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
1274
1275      Hashtable p = JsonConvert.DeserializeObject(value, typeof(Hashtable)) as Hashtable;
1276
1277      Assert.AreEqual("Orange", p["Name"].ToString());
1278    }
1279
1280    [Test]
1281    public void TypedHashtableDeserialization()
1282    {
1283      string value = @"{""Name"":""Orange"", ""Hash"":{""ExpiryDate"":""01/24/2010 12:00:00"",""UntypedArray"":[""01/24/2010 12:00:00""]}}";
1284
1285      TypedSubHashtable p = JsonConvert.DeserializeObject(value, typeof(TypedSubHashtable)) as TypedSubHashtable;
1286
1287      Assert.AreEqual("01/24/2010 12:00:00", p.Hash["ExpiryDate"].ToString());
1288      Assert.AreEqual(@"[
1289  ""01/24/2010 12:00:00""
1290]", p.Hash["UntypedArray"].ToString());
1291    }
1292#endif
1293
1294    [Test]
1295    public void SerializeDeserializeGetOnlyProperty()
1296    {
1297      string value = JsonConvert.SerializeObject(new GetOnlyPropertyClass());
1298
1299      GetOnlyPropertyClass c = JsonConvert.DeserializeObject<GetOnlyPropertyClass>(value);
1300
1301      Assert.AreEqual(c.Field, "Field");
1302      Assert.AreEqual(c.GetOnlyProperty, "GetOnlyProperty");
1303    }
1304
1305    [Test]
1306    public void SerializeDeserializeSetOnlyProperty()
1307    {
1308      string value = JsonConvert.SerializeObject(new SetOnlyPropertyClass());
1309
1310      SetOnlyPropertyClass c = JsonConvert.DeserializeObject<SetOnlyPropertyClass>(value);
1311
1312      Assert.AreEqual(c.Field, "Field");
1313    }
1314
1315    [Test]
1316    public void JsonIgnoreAttributeTest()
1317    {
1318      string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeTestClass());
1319
1320      Assert.AreEqual(@"{""Field"":0,""Property"":21}", json);
1321
1322      JsonIgnoreAttributeTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeTestClass>(@"{""Field"":99,""Property"":-1,""IgnoredField"":-1,""IgnoredObject"":[1,2,3,4,5]}");
1323
1324      Assert.AreEqual(0, c.IgnoredField);
1325      Assert.AreEqual(99, c.Field);
1326    }
1327
1328    [Test]
1329    public void GoogleSearchAPI()
1330    {
1331      string json = @"{
1332    results:
1333        [
1334            {
1335                GsearchResultClass:""GwebSearch"",
1336                unescapedUrl : ""http://www.google.com/"",
1337                url : ""http://www.google.com/"",
1338                visibleUrl : ""www.google.com"",
1339                cacheUrl : 
1340""http://www.google.com/search?q=cache:zhool8dxBV4J:www.google.com"",
1341                title : ""Google"",
1342                titleNoFormatting : ""Google"",
1343                content : ""Enables users to search the Web, Usenet, and 
1344images. Features include PageRank,   caching and translation of 
1345results, and an option to find similar pages.""
1346            },
1347            {
1348                GsearchResultClass:""GwebSearch"",
1349                unescapedUrl : ""http://news.google.com/"",
1350                url : ""http://news.google.com/"",
1351                visibleUrl : ""news.google.com"",
1352                cacheUrl : 
1353""http://www.google.com/search?q=cache:Va_XShOz_twJ:news.google.com"",
1354                title : ""Google News"",
1355                titleNoFormatting : ""Google News"",
1356                content : ""Aggregated headlines and a search engine of many of the world's news sources.""
1357            },
1358            
1359            {
1360                GsearchResultClass:""GwebSearch"",
1361                unescapedUrl : ""http://groups.google.com/"",
1362                url : ""http://groups.google.com/"",
1363                visibleUrl : ""groups.google.com"",
1364                cacheUrl : 
1365""http://www.google.com/search?q=cache:x2uPD3hfkn0J:groups.google.com"",
1366                title : ""Google Groups"",
1367                titleNoFormatting : ""Google Groups"",
1368                content : ""Enables users to search and browse the Usenet 
1369archives which consist of over 700   million messages, and post new 
1370comments.""
1371            },
1372            
1373            {
1374                GsearchResultClass:""GwebSearch"",
1375                unescapedUrl : ""http://maps.google.com/"",
1376                url : ""http://maps.google.com/"",
1377                visibleUrl : ""maps.google.com"",
1378                cacheUrl : 
1379""http://www.google.com/search?q=cache:dkf5u2twBXIJ:maps.google.com"",
1380                title : ""Google Maps"",
1381                titleNoFormatting : ""Google Maps"",
1382                content : ""Provides directions, interactive maps, and 
1383satellite/aerial imagery of the United   States. Can also search by 
1384keyword such as type of business.""
1385            }
1386        ],
1387        
1388    adResults:
1389        [
1390            {
1391                GsearchResultClass:""GwebSearch.ad"",
1392                title : ""Gartner Symposium/ITxpo"",
1393                content1 : ""Meet brilliant Gartner IT analysts"",
1394                content2 : ""20-23 May 2007- Barcelona, Spain"",
1395                url : 
1396""http://www.google.com/url?sa=L&ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB&num=1&q=http://www.gartner.com/it/sym/2007/spr8/spr8.jsp%3Fsrc%3D_spain_07_%26WT.srch%3D1&usg=__CxRH06E4Xvm9Muq13S4MgMtnziY="", 
1397
1398                impressionUrl : 
1399""http://www.google.com/uds/css/ad-indicator-on.gif?ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB"", 
1400
1401                unescapedUrl : 
1402""http://www.google.com/url?sa=L&ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB&num=1&q=http://www.gartner.com/it/sym/2007/spr8/spr8.jsp%3Fsrc%3D_spain_07_%26WT.srch%3D1&usg=__CxRH06E4Xvm9Muq13S4MgMtnziY="", 
1403
1404                visibleUrl : ""www.gartner.com""
1405            }
1406        ]
1407}
1408";
1409      object o = JsonConvert.DeserializeObject(json);
1410      string s = string.Empty;
1411      s += s;
1412    }
1413
1414    [Test]
1415    public void TorrentDeserializeTest()
1416    {
1417      string jsonText = @"{
1418"""":"""",
1419""label"": [
1420       [""SomeName"",6]
1421],
1422""torrents"": [
1423       [""192D99A5C943555CB7F00A852821CF6D6DB3008A"",201,""filename.av…

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