PageRenderTime 13ms CodeModel.GetById 7ms app.highlight 35ms RepoModel.GetById 1ms app.codeStats 2ms

/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs

https://github.com/dmgores/Newtonsoft.Json
C# | 7989 lines | 7047 code | 841 blank | 101 comment | 61 complexity | 47375c7d5e276f3ea785fa4217096b31 MD5 | raw file

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

   1#region License
   2// Copyright (c) 2007 James Newton-King
   3//
   4// Permission is hereby granted, free of charge, to any person
   5// obtaining a copy of this software and associated documentation
   6// files (the "Software"), to deal in the Software without
   7// restriction, including without limitation the rights to use,
   8// copy, modify, merge, publish, distribute, sublicense, and/or sell
   9// copies of the Software, and to permit persons to whom the
  10// Software is furnished to do so, subject to the following
  11// conditions:
  12//
  13// The above copyright notice and this permission notice shall be
  14// included in all copies or substantial portions of the Software.
  15//
  16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  18// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  20// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23// OTHER DEALINGS IN THE SOFTWARE.
  24#endregion
  25
  26using System;
  27using System.ComponentModel;
  28#if !(NET35 || NET20)
  29using System.Collections.Concurrent;
  30#endif
  31using System.Collections.Generic;
  32#if !(NET20 || NET35 || PORTABLE)
  33using System.Numerics;
  34#endif
  35#if !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
  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 !(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 BaseClass
  95        {
  96            internal bool IsTransient { get; set; }
  97        }
  98
  99        public class ChildClass : BaseClass
 100        {
 101            public new bool IsTransient { get; set; }
 102        }
 103
 104        [Test]
 105        public void NewProperty()
 106        {
 107            Assert.AreEqual(@"{""IsTransient"":true}", JsonConvert.SerializeObject(new ChildClass { IsTransient = true }));
 108
 109            var childClass = JsonConvert.DeserializeObject<ChildClass>(@"{""IsTransient"":true}");
 110            Assert.AreEqual(true, childClass.IsTransient);
 111        }
 112
 113        public class BaseClassVirtual
 114        {
 115            internal virtual bool IsTransient { get; set; }
 116        }
 117
 118        public class ChildClassVirtual : BaseClassVirtual
 119        {
 120            public virtual new bool IsTransient { get; set; }
 121        }
 122
 123        [Test]
 124        public void NewPropertyVirtual()
 125        {
 126            Assert.AreEqual(@"{""IsTransient"":true}", JsonConvert.SerializeObject(new ChildClassVirtual { IsTransient = true }));
 127
 128            var childClass = JsonConvert.DeserializeObject<ChildClassVirtual>(@"{""IsTransient"":true}");
 129            Assert.AreEqual(true, childClass.IsTransient);
 130        }
 131
 132        public class ResponseWithNewGenericProperty<T> : SimpleResponse
 133        {
 134            public new T Data { get; set; }
 135        }
 136
 137        public class ResponseWithNewGenericPropertyVirtual<T> : SimpleResponse
 138        {
 139            public virtual new T Data { get; set; }
 140        }
 141
 142        public class ResponseWithNewGenericPropertyOverride<T> : ResponseWithNewGenericPropertyVirtual<T>
 143        {
 144            public override T Data { get; set; }
 145        }
 146
 147        public abstract class SimpleResponse
 148        {
 149            public string Result { get; set; }
 150            public string Message { get; set; }
 151            public object Data { get; set; }
 152
 153            protected SimpleResponse()
 154            {
 155
 156            }
 157
 158            protected SimpleResponse(string message)
 159            {
 160                Message = message;
 161            }
 162        }
 163
 164        [Test]
 165        public void CanSerializeWithBuiltInTypeAsGenericArgument()
 166        {
 167            var input = new ResponseWithNewGenericProperty<int>()
 168            {
 169                Message = "Trying out integer as type parameter",
 170                Data = 25,
 171                Result = "This should be fine"
 172            };
 173
 174            var json = JsonConvert.SerializeObject(input);
 175            var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericProperty<int>>(json);
 176
 177            Assert.AreEqual(input.Data, deserialized.Data);
 178            Assert.AreEqual(input.Message, deserialized.Message);
 179            Assert.AreEqual(input.Result, deserialized.Result);
 180        }
 181
 182        [Test]
 183        public void CanSerializeWithBuiltInTypeAsGenericArgumentVirtual()
 184        {
 185            var input = new ResponseWithNewGenericPropertyVirtual<int>()
 186            {
 187                Message = "Trying out integer as type parameter",
 188                Data = 25,
 189                Result = "This should be fine"
 190            };
 191
 192            var json = JsonConvert.SerializeObject(input);
 193            var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericPropertyVirtual<int>>(json);
 194
 195            Assert.AreEqual(input.Data, deserialized.Data);
 196            Assert.AreEqual(input.Message, deserialized.Message);
 197            Assert.AreEqual(input.Result, deserialized.Result);
 198        }
 199
 200        [Test]
 201        public void CanSerializeWithBuiltInTypeAsGenericArgumentOverride()
 202        {
 203            var input = new ResponseWithNewGenericPropertyOverride<int>()
 204            {
 205                Message = "Trying out integer as type parameter",
 206                Data = 25,
 207                Result = "This should be fine"
 208            };
 209
 210            var json = JsonConvert.SerializeObject(input);
 211            var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericPropertyOverride<int>>(json);
 212
 213            Assert.AreEqual(input.Data, deserialized.Data);
 214            Assert.AreEqual(input.Message, deserialized.Message);
 215            Assert.AreEqual(input.Result, deserialized.Result);
 216        }
 217
 218        [Test]
 219        public void CanSerializedWithGenericClosedTypeAsArgument()
 220        {
 221            var input = new ResponseWithNewGenericProperty<List<int>>()
 222            {
 223                Message = "More complex case - generic list of int",
 224                Data = Enumerable.Range(50, 70).ToList(),
 225                Result = "This should be fine too"
 226            };
 227
 228            var json = JsonConvert.SerializeObject(input);
 229            var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericProperty<List<int>>>(json);
 230
 231            CollectionAssert.AreEqual(input.Data, deserialized.Data);
 232            Assert.AreEqual(input.Message, deserialized.Message);
 233            Assert.AreEqual(input.Result, deserialized.Result);
 234        }
 235
 236        [Test]
 237        public void JsonSerializerProperties()
 238        {
 239            JsonSerializer serializer = new JsonSerializer();
 240
 241            DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
 242            serializer.Binder = customBinder;
 243            Assert.AreEqual(customBinder, serializer.Binder);
 244
 245            serializer.CheckAdditionalContent = true;
 246            Assert.AreEqual(true, serializer.CheckAdditionalContent);
 247
 248            serializer.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
 249            Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, serializer.ConstructorHandling);
 250
 251#if !NETFX_CORE
 252            serializer.Context = new StreamingContext(StreamingContextStates.Other);
 253            Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), serializer.Context);
 254#endif
 255
 256            CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
 257            serializer.ContractResolver = resolver;
 258            Assert.AreEqual(resolver, serializer.ContractResolver);
 259
 260            serializer.Converters.Add(new StringEnumConverter());
 261            Assert.AreEqual(1, serializer.Converters.Count);
 262
 263            serializer.Culture = new CultureInfo("en-nz");
 264            Assert.AreEqual("en-NZ", serializer.Culture.ToString());
 265
 266            serializer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
 267            Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, serializer.DateFormatHandling);
 268
 269            serializer.DateFormatString = "yyyy";
 270            Assert.AreEqual("yyyy", serializer.DateFormatString);
 271
 272            serializer.DateParseHandling = DateParseHandling.None;
 273            Assert.AreEqual(DateParseHandling.None, serializer.DateParseHandling);
 274
 275            serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
 276            Assert.AreEqual(DateTimeZoneHandling.Utc, serializer.DateTimeZoneHandling);
 277
 278            serializer.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
 279            Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, serializer.DefaultValueHandling);
 280
 281            serializer.FloatFormatHandling = FloatFormatHandling.Symbol;
 282            Assert.AreEqual(FloatFormatHandling.Symbol, serializer.FloatFormatHandling);
 283
 284            serializer.FloatParseHandling = FloatParseHandling.Decimal;
 285            Assert.AreEqual(FloatParseHandling.Decimal, serializer.FloatParseHandling);
 286
 287            serializer.Formatting = Formatting.Indented;
 288            Assert.AreEqual(Formatting.Indented, serializer.Formatting);
 289
 290            serializer.MaxDepth = 9001;
 291            Assert.AreEqual(9001, serializer.MaxDepth);
 292
 293            serializer.MissingMemberHandling = MissingMemberHandling.Error;
 294            Assert.AreEqual(MissingMemberHandling.Error, serializer.MissingMemberHandling);
 295
 296            serializer.NullValueHandling = NullValueHandling.Ignore;
 297            Assert.AreEqual(NullValueHandling.Ignore, serializer.NullValueHandling);
 298
 299            serializer.ObjectCreationHandling = ObjectCreationHandling.Replace;
 300            Assert.AreEqual(ObjectCreationHandling.Replace, serializer.ObjectCreationHandling);
 301
 302            serializer.PreserveReferencesHandling = PreserveReferencesHandling.All;
 303            Assert.AreEqual(PreserveReferencesHandling.All, serializer.PreserveReferencesHandling);
 304
 305            serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
 306            Assert.AreEqual(ReferenceLoopHandling.Ignore, serializer.ReferenceLoopHandling);
 307
 308            IdReferenceResolver referenceResolver = new IdReferenceResolver();
 309            serializer.ReferenceResolver = referenceResolver;
 310            Assert.AreEqual(referenceResolver, serializer.ReferenceResolver);
 311
 312            serializer.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
 313            Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, serializer.StringEscapeHandling);
 314
 315            MemoryTraceWriter traceWriter = new MemoryTraceWriter();
 316            serializer.TraceWriter = traceWriter;
 317            Assert.AreEqual(traceWriter, serializer.TraceWriter);
 318
 319#if !(PORTABLE || PORTABLE40 || NETFX_CORE || NET20)
 320            serializer.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
 321            Assert.AreEqual(FormatterAssemblyStyle.Full, serializer.TypeNameAssemblyFormat);
 322#endif
 323
 324            serializer.TypeNameHandling = TypeNameHandling.All;
 325            Assert.AreEqual(TypeNameHandling.All, serializer.TypeNameHandling);
 326        }
 327
 328        [Test]
 329        public void JsonSerializerSettingsProperties()
 330        {
 331            JsonSerializerSettings settings = new JsonSerializerSettings();
 332
 333            DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
 334            settings.Binder = customBinder;
 335            Assert.AreEqual(customBinder, settings.Binder);
 336
 337            settings.CheckAdditionalContent = true;
 338            Assert.AreEqual(true, settings.CheckAdditionalContent);
 339
 340            settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
 341            Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, settings.ConstructorHandling);
 342
 343#if !NETFX_CORE
 344            settings.Context = new StreamingContext(StreamingContextStates.Other);
 345            Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), settings.Context);
 346#endif
 347
 348            CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
 349            settings.ContractResolver = resolver;
 350            Assert.AreEqual(resolver, settings.ContractResolver);
 351
 352            settings.Converters.Add(new StringEnumConverter());
 353            Assert.AreEqual(1, settings.Converters.Count);
 354
 355            settings.Culture = new CultureInfo("en-nz");
 356            Assert.AreEqual("en-NZ", settings.Culture.ToString());
 357
 358            settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
 359            Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, settings.DateFormatHandling);
 360
 361            settings.DateFormatString = "yyyy";
 362            Assert.AreEqual("yyyy", settings.DateFormatString);
 363
 364            settings.DateParseHandling = DateParseHandling.None;
 365            Assert.AreEqual(DateParseHandling.None, settings.DateParseHandling);
 366
 367            settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
 368            Assert.AreEqual(DateTimeZoneHandling.Utc, settings.DateTimeZoneHandling);
 369
 370            settings.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
 371            Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, settings.DefaultValueHandling);
 372
 373            settings.FloatFormatHandling = FloatFormatHandling.Symbol;
 374            Assert.AreEqual(FloatFormatHandling.Symbol, settings.FloatFormatHandling);
 375
 376            settings.FloatParseHandling = FloatParseHandling.Decimal;
 377            Assert.AreEqual(FloatParseHandling.Decimal, settings.FloatParseHandling);
 378
 379            settings.Formatting = Formatting.Indented;
 380            Assert.AreEqual(Formatting.Indented, settings.Formatting);
 381
 382            settings.MaxDepth = 9001;
 383            Assert.AreEqual(9001, settings.MaxDepth);
 384
 385            settings.MissingMemberHandling = MissingMemberHandling.Error;
 386            Assert.AreEqual(MissingMemberHandling.Error, settings.MissingMemberHandling);
 387
 388            settings.NullValueHandling = NullValueHandling.Ignore;
 389            Assert.AreEqual(NullValueHandling.Ignore, settings.NullValueHandling);
 390
 391            settings.ObjectCreationHandling = ObjectCreationHandling.Replace;
 392            Assert.AreEqual(ObjectCreationHandling.Replace, settings.ObjectCreationHandling);
 393
 394            settings.PreserveReferencesHandling = PreserveReferencesHandling.All;
 395            Assert.AreEqual(PreserveReferencesHandling.All, settings.PreserveReferencesHandling);
 396
 397            settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
 398            Assert.AreEqual(ReferenceLoopHandling.Ignore, settings.ReferenceLoopHandling);
 399
 400            IdReferenceResolver referenceResolver = new IdReferenceResolver();
 401            settings.ReferenceResolver = referenceResolver;
 402            Assert.AreEqual(referenceResolver, settings.ReferenceResolver);
 403
 404            settings.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
 405            Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, settings.StringEscapeHandling);
 406
 407            MemoryTraceWriter traceWriter = new MemoryTraceWriter();
 408            settings.TraceWriter = traceWriter;
 409            Assert.AreEqual(traceWriter, settings.TraceWriter);
 410
 411#if !(PORTABLE || PORTABLE40 || NETFX_CORE || NET20)
 412            settings.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
 413            Assert.AreEqual(FormatterAssemblyStyle.Full, settings.TypeNameAssemblyFormat);
 414#endif
 415
 416            settings.TypeNameHandling = TypeNameHandling.All;
 417            Assert.AreEqual(TypeNameHandling.All, settings.TypeNameHandling);
 418        }
 419
 420        [Test]
 421        public void JsonSerializerProxyProperties()
 422        {
 423            JsonSerializerProxy serializerProxy = new JsonSerializerProxy(new JsonSerializerInternalReader(new JsonSerializer()));
 424
 425            DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
 426            serializerProxy.Binder = customBinder;
 427            Assert.AreEqual(customBinder, serializerProxy.Binder);
 428
 429            serializerProxy.CheckAdditionalContent = true;
 430            Assert.AreEqual(true, serializerProxy.CheckAdditionalContent);
 431
 432            serializerProxy.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
 433            Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, serializerProxy.ConstructorHandling);
 434
 435#if !NETFX_CORE
 436            serializerProxy.Context = new StreamingContext(StreamingContextStates.Other);
 437            Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), serializerProxy.Context);
 438#endif
 439
 440            CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
 441            serializerProxy.ContractResolver = resolver;
 442            Assert.AreEqual(resolver, serializerProxy.ContractResolver);
 443
 444            serializerProxy.Converters.Add(new StringEnumConverter());
 445            Assert.AreEqual(1, serializerProxy.Converters.Count);
 446
 447            serializerProxy.Culture = new CultureInfo("en-nz");
 448            Assert.AreEqual("en-NZ", serializerProxy.Culture.ToString());
 449
 450            serializerProxy.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
 451            Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, serializerProxy.DateFormatHandling);
 452
 453            serializerProxy.DateFormatString = "yyyy";
 454            Assert.AreEqual("yyyy", serializerProxy.DateFormatString);
 455
 456            serializerProxy.DateParseHandling = DateParseHandling.None;
 457            Assert.AreEqual(DateParseHandling.None, serializerProxy.DateParseHandling);
 458
 459            serializerProxy.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
 460            Assert.AreEqual(DateTimeZoneHandling.Utc, serializerProxy.DateTimeZoneHandling);
 461
 462            serializerProxy.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
 463            Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, serializerProxy.DefaultValueHandling);
 464
 465            serializerProxy.FloatFormatHandling = FloatFormatHandling.Symbol;
 466            Assert.AreEqual(FloatFormatHandling.Symbol, serializerProxy.FloatFormatHandling);
 467
 468            serializerProxy.FloatParseHandling = FloatParseHandling.Decimal;
 469            Assert.AreEqual(FloatParseHandling.Decimal, serializerProxy.FloatParseHandling);
 470
 471            serializerProxy.Formatting = Formatting.Indented;
 472            Assert.AreEqual(Formatting.Indented, serializerProxy.Formatting);
 473
 474            serializerProxy.MaxDepth = 9001;
 475            Assert.AreEqual(9001, serializerProxy.MaxDepth);
 476
 477            serializerProxy.MissingMemberHandling = MissingMemberHandling.Error;
 478            Assert.AreEqual(MissingMemberHandling.Error, serializerProxy.MissingMemberHandling);
 479
 480            serializerProxy.NullValueHandling = NullValueHandling.Ignore;
 481            Assert.AreEqual(NullValueHandling.Ignore, serializerProxy.NullValueHandling);
 482
 483            serializerProxy.ObjectCreationHandling = ObjectCreationHandling.Replace;
 484            Assert.AreEqual(ObjectCreationHandling.Replace, serializerProxy.ObjectCreationHandling);
 485
 486            serializerProxy.PreserveReferencesHandling = PreserveReferencesHandling.All;
 487            Assert.AreEqual(PreserveReferencesHandling.All, serializerProxy.PreserveReferencesHandling);
 488
 489            serializerProxy.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
 490            Assert.AreEqual(ReferenceLoopHandling.Ignore, serializerProxy.ReferenceLoopHandling);
 491
 492            IdReferenceResolver referenceResolver = new IdReferenceResolver();
 493            serializerProxy.ReferenceResolver = referenceResolver;
 494            Assert.AreEqual(referenceResolver, serializerProxy.ReferenceResolver);
 495
 496            serializerProxy.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
 497            Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, serializerProxy.StringEscapeHandling);
 498
 499            MemoryTraceWriter traceWriter = new MemoryTraceWriter();
 500            serializerProxy.TraceWriter = traceWriter;
 501            Assert.AreEqual(traceWriter, serializerProxy.TraceWriter);
 502
 503#if !(PORTABLE || PORTABLE40 || NETFX_CORE || NET20)
 504            serializerProxy.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
 505            Assert.AreEqual(FormatterAssemblyStyle.Full, serializerProxy.TypeNameAssemblyFormat);
 506#endif
 507
 508            serializerProxy.TypeNameHandling = TypeNameHandling.All;
 509            Assert.AreEqual(TypeNameHandling.All, serializerProxy.TypeNameHandling);
 510        }
 511
 512#if !(NETFX_CORE || PORTABLE || PORTABLE40)
 513        [Test]
 514        public void DeserializeISerializableIConvertible()
 515        {
 516            Ratio ratio = new Ratio(2, 1);
 517            string json = JsonConvert.SerializeObject(ratio);
 518
 519            Assert.AreEqual(@"{""n"":2,""d"":1}", json);
 520
 521            Ratio ratio2 = JsonConvert.DeserializeObject<Ratio>(json);
 522
 523            Assert.AreEqual(ratio.Denominator, ratio2.Denominator);
 524            Assert.AreEqual(ratio.Numerator, ratio2.Numerator);
 525        }
 526#endif
 527
 528        [Test]
 529        public void DeserializeLargeFloat()
 530        {
 531            object o = JsonConvert.DeserializeObject("100000000000000000000000000000000000000.0");
 532
 533            CustomAssert.IsInstanceOfType(typeof(double), o);
 534
 535            Assert.IsTrue(MathUtils.ApproxEquals(1E+38, (double)o));
 536        }
 537
 538        [Test]
 539        public void SerializeDeserializeRegex()
 540        {
 541            Regex regex = new Regex("(hi)", RegexOptions.CultureInvariant);
 542
 543            string json = JsonConvert.SerializeObject(regex, Formatting.Indented);
 544
 545            Regex r2 = JsonConvert.DeserializeObject<Regex>(json);
 546
 547            Assert.AreEqual("(hi)", r2.ToString());
 548            Assert.AreEqual(RegexOptions.CultureInvariant, r2.Options);
 549        }
 550
 551        [Test]
 552        public void EmbedJValueStringInNewJObject()
 553        {
 554            string s = null;
 555            var v = new JValue(s);
 556            var o = JObject.FromObject(new { title = v });
 557
 558            JObject oo = new JObject
 559            {
 560                {"title", v}
 561            };
 562
 563            string output = o.ToString();
 564
 565            Assert.AreEqual(null, v.Value);
 566            Assert.AreEqual(JTokenType.String, v.Type);
 567            
 568            Assert.AreEqual(@"{
 569  ""title"": null
 570}", output);
 571        }
 572
 573        // bug: the generic member (T) that hides the base member will not
 574        // be used when serializing and deserializing the object,
 575        // resulting in unexpected behavior during serialization and deserialization.
 576
 577        public class Foo1
 578        {
 579            public object foo { get; set; }
 580        }
 581
 582        public class Bar1
 583        {
 584            public object bar { get; set; }
 585        }
 586
 587        public class Foo1<T> : Foo1
 588        {
 589            public new T foo { get; set; }
 590
 591            public T foo2 { get; set; }
 592        }
 593
 594        public class FooBar1 : Foo1
 595        {
 596            public new Bar1 foo { get; set; }
 597        }
 598
 599        [Test]
 600        public void BaseClassSerializesAsExpected()
 601        {
 602            var original = new Foo1 { foo = "value" };
 603            var json = JsonConvert.SerializeObject(original);
 604            var expectedJson = @"{""foo"":""value""}";
 605            Assert.AreEqual(expectedJson, json); // passes
 606        }
 607
 608        [Test]
 609        public void BaseClassDeserializesAsExpected()
 610        {
 611            var json = @"{""foo"":""value""}";
 612            var deserialized = JsonConvert.DeserializeObject<Foo1>(json);
 613            Assert.AreEqual("value", deserialized.foo); // passes
 614        }
 615
 616        [Test]
 617        public void DerivedClassHidingBasePropertySerializesAsExpected()
 618        {
 619            var original = new FooBar1 { foo = new Bar1 { bar = "value" } };
 620            var json = JsonConvert.SerializeObject(original);
 621            var expectedJson = @"{""foo"":{""bar"":""value""}}";
 622            Assert.AreEqual(expectedJson, json); // passes
 623        }
 624
 625        [Test]
 626        public void DerivedClassHidingBasePropertyDeserializesAsExpected()
 627        {
 628            var json = @"{""foo"":{""bar"":""value""}}";
 629            var deserialized = JsonConvert.DeserializeObject<FooBar1>(json);
 630            Assert.IsNotNull(deserialized.foo); // passes
 631            Assert.AreEqual("value", deserialized.foo.bar); // passes
 632        }
 633
 634        [Test]
 635        public void DerivedGenericClassHidingBasePropertySerializesAsExpected()
 636        {
 637            var original = new Foo1<Bar1> { foo = new Bar1 { bar = "value" }, foo2 = new Bar1 { bar = "value2" } };
 638            var json = JsonConvert.SerializeObject(original);
 639            var expectedJson = @"{""foo"":{""bar"":""value""},""foo2"":{""bar"":""value2""}}";
 640            Assert.AreEqual(expectedJson, json);
 641        }
 642
 643        [Test]
 644        public void DerivedGenericClassHidingBasePropertyDeserializesAsExpected()
 645        {
 646            var json = @"{""foo"":{""bar"":""value""},""foo2"":{""bar"":""value2""}}";
 647            var deserialized = JsonConvert.DeserializeObject<Foo1<Bar1>>(json);
 648            Assert.IsNotNull(deserialized.foo2); // passes (bug only occurs for generics that /hide/ another property)
 649            Assert.AreEqual("value2", deserialized.foo2.bar); // also passes, with no issue
 650            Assert.IsNotNull(deserialized.foo);
 651            Assert.AreEqual("value", deserialized.foo.bar);
 652        }
 653
 654#if !NETFX_CORE
 655        [Test]
 656        public void ConversionOperator()
 657        {
 658            // Creating a simple dictionary that has a non-string key
 659            var dictStore = new Dictionary<DictionaryKeyCast, int>();
 660            for (var i = 0; i < 800; i++)
 661            {
 662                dictStore.Add(new DictionaryKeyCast(i.ToString(CultureInfo.InvariantCulture), i), i);
 663            }
 664            var settings = new JsonSerializerSettings { Formatting = Formatting.Indented };
 665            var jsonSerializer = JsonSerializer.Create(settings);
 666            var ms = new MemoryStream();
 667
 668            var streamWriter = new StreamWriter(ms);
 669            jsonSerializer.Serialize(streamWriter, dictStore);
 670            streamWriter.Flush();
 671
 672            ms.Seek(0, SeekOrigin.Begin);
 673
 674            var stopWatch = Stopwatch.StartNew();
 675            var deserialize = jsonSerializer.Deserialize(new StreamReader(ms), typeof(Dictionary<DictionaryKeyCast, int>));
 676            stopWatch.Stop();
 677
 678            Console.WriteLine("Time elapsed: " + stopWatch.ElapsedMilliseconds);
 679        }
 680#endif
 681
 682        internal class DictionaryKeyCast
 683        {
 684            private String _name;
 685            private int _number;
 686
 687            public DictionaryKeyCast(String name, int number)
 688            {
 689                _name = name;
 690                _number = number;
 691            }
 692
 693            public override string ToString()
 694            {
 695                return _name + " " + _number;
 696            }
 697
 698            public static implicit operator DictionaryKeyCast(string dictionaryKey)
 699            {
 700                var strings = dictionaryKey.Split(' ');
 701                return new DictionaryKeyCast(strings[0], Convert.ToInt32(strings[1]));
 702            }
 703        }
 704
 705#if !NET20
 706        [DataContract]
 707        public class BaseDataContractWithHidden
 708        {
 709            [DataMember(Name = "virtualMember")]
 710            public virtual string VirtualMember { get; set; }
 711
 712            [DataMember(Name = "nonVirtualMember")]
 713            public string NonVirtualMember { get; set; }
 714
 715            public virtual object NewMember { get; set; }
 716        }
 717
 718        public class ChildDataContractWithHidden : BaseDataContractWithHidden
 719        {
 720            [DataMember(Name = "NewMember")]
 721            public new virtual string NewMember { get; set; }
 722
 723            public override string VirtualMember { get; set; }
 724            public string AddedMember { get; set; }
 725        }
 726
 727        [Test]
 728        public void ChildDataContractTestWithHidden()
 729        {
 730            var cc = new ChildDataContractWithHidden
 731            {
 732                VirtualMember = "VirtualMember!",
 733                NonVirtualMember = "NonVirtualMember!",
 734                NewMember = "NewMember!"
 735            };
 736
 737            string result = JsonConvert.SerializeObject(cc);
 738            Assert.AreEqual(@"{""NewMember"":""NewMember!"",""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
 739        }
 740
 741        // ignore hiding members compiler warning
 742#pragma warning disable 108,114
 743        [DataContract]
 744        public class BaseWithContract
 745        {
 746            [DataMember(Name = "VirtualWithDataMemberBase")]
 747            public virtual string VirtualWithDataMember { get; set; }
 748
 749            [DataMember]
 750            public virtual string Virtual { get; set; }
 751
 752            [DataMember(Name = "WithDataMemberBase")]
 753            public string WithDataMember { get; set; }
 754
 755            [DataMember]
 756            public string JustAProperty { get; set; }
 757        }
 758
 759        [DataContract]
 760        public class BaseWithoutContract
 761        {
 762            [DataMember(Name = "VirtualWithDataMemberBase")]
 763            public virtual string VirtualWithDataMember { get; set; }
 764
 765            [DataMember]
 766            public virtual string Virtual { get; set; }
 767
 768            [DataMember(Name = "WithDataMemberBase")]
 769            public string WithDataMember { get; set; }
 770
 771            [DataMember]
 772            public string JustAProperty { get; set; }
 773        }
 774
 775        [DataContract]
 776        public class SubWithoutContractNewProperties : BaseWithContract
 777        {
 778            [DataMember(Name = "VirtualWithDataMemberSub")]
 779            public string VirtualWithDataMember { get; set; }
 780
 781            public string Virtual { get; set; }
 782
 783            [DataMember(Name = "WithDataMemberSub")]
 784            public string WithDataMember { get; set; }
 785
 786            public string JustAProperty { get; set; }
 787        }
 788
 789        [DataContract]
 790        public class SubWithoutContractVirtualProperties : BaseWithContract
 791        {
 792            public override string VirtualWithDataMember { get; set; }
 793
 794            [DataMember(Name = "VirtualSub")]
 795            public override string Virtual { get; set; }
 796        }
 797
 798        [DataContract]
 799        public class SubWithContractNewProperties : BaseWithContract
 800        {
 801            [DataMember(Name = "VirtualWithDataMemberSub")]
 802            public string VirtualWithDataMember { get; set; }
 803
 804            [DataMember(Name = "Virtual2")]
 805            public string Virtual { get; set; }
 806
 807            [DataMember(Name = "WithDataMemberSub")]
 808            public string WithDataMember { get; set; }
 809
 810            [DataMember(Name = "JustAProperty2")]
 811            public string JustAProperty { get; set; }
 812        }
 813
 814        [DataContract]
 815        public class SubWithContractVirtualProperties : BaseWithContract
 816        {
 817            [DataMember(Name = "VirtualWithDataMemberSub")]
 818            public virtual string VirtualWithDataMember { get; set; }
 819        }
 820#pragma warning restore 108,114
 821
 822        [Test]
 823        public void SubWithoutContractNewPropertiesTest()
 824        {
 825            BaseWithContract baseWith = new SubWithoutContractNewProperties
 826            {
 827                JustAProperty = "JustAProperty!",
 828                Virtual = "Virtual!",
 829                VirtualWithDataMember = "VirtualWithDataMember!",
 830                WithDataMember = "WithDataMember!"
 831            };
 832
 833            baseWith.JustAProperty = "JustAProperty2!";
 834            baseWith.Virtual = "Virtual2!";
 835            baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
 836            baseWith.WithDataMember = "WithDataMember2!";
 837
 838            string json = AssertSerializeDeserializeEqual(baseWith);
 839
 840            Assert.AreEqual(@"{
 841  ""JustAProperty"": ""JustAProperty2!"",
 842  ""Virtual"": ""Virtual2!"",
 843  ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
 844  ""VirtualWithDataMemberSub"": ""VirtualWithDataMember!"",
 845  ""WithDataMemberBase"": ""WithDataMember2!"",
 846  ""WithDataMemberSub"": ""WithDataMember!""
 847}", json);
 848        }
 849
 850        [Test]
 851        public void SubWithoutContractVirtualPropertiesTest()
 852        {
 853            BaseWithContract baseWith = new SubWithoutContractVirtualProperties
 854            {
 855                JustAProperty = "JustAProperty!",
 856                Virtual = "Virtual!",
 857                VirtualWithDataMember = "VirtualWithDataMember!",
 858                WithDataMember = "WithDataMember!"
 859            };
 860
 861            baseWith.JustAProperty = "JustAProperty2!";
 862            baseWith.Virtual = "Virtual2!";
 863            baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
 864            baseWith.WithDataMember = "WithDataMember2!";
 865
 866            string json = JsonConvert.SerializeObject(baseWith, Formatting.Indented);
 867
 868            Console.WriteLine(json);
 869
 870            Assert.AreEqual(@"{
 871  ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
 872  ""VirtualSub"": ""Virtual2!"",
 873  ""WithDataMemberBase"": ""WithDataMember2!"",
 874  ""JustAProperty"": ""JustAProperty2!""
 875}", json);
 876        }
 877
 878        [Test]
 879        public void SubWithContractNewPropertiesTest()
 880        {
 881            BaseWithContract baseWith = new SubWithContractNewProperties
 882            {
 883                JustAProperty = "JustAProperty!",
 884                Virtual = "Virtual!",
 885                VirtualWithDataMember = "VirtualWithDataMember!",
 886                WithDataMember = "WithDataMember!"
 887            };
 888
 889            baseWith.JustAProperty = "JustAProperty2!";
 890            baseWith.Virtual = "Virtual2!";
 891            baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
 892            baseWith.WithDataMember = "WithDataMember2!";
 893
 894            string json = AssertSerializeDeserializeEqual(baseWith);
 895
 896            Assert.AreEqual(@"{
 897  ""JustAProperty"": ""JustAProperty2!"",
 898  ""JustAProperty2"": ""JustAProperty!"",
 899  ""Virtual"": ""Virtual2!"",
 900  ""Virtual2"": ""Virtual!"",
 901  ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
 902  ""VirtualWithDataMemberSub"": ""VirtualWithDataMember!"",
 903  ""WithDataMemberBase"": ""WithDataMember2!"",
 904  ""WithDataMemberSub"": ""WithDataMember!""
 905}", json);
 906        }
 907
 908        [Test]
 909        public void SubWithContractVirtualPropertiesTest()
 910        {
 911            BaseWithContract baseWith = new SubWithContractVirtualProperties
 912            {
 913                JustAProperty = "JustAProperty!",
 914                Virtual = "Virtual!",
 915                VirtualWithDataMember = "VirtualWithDataMember!",
 916                WithDataMember = "WithDataMember!"
 917            };
 918
 919            baseWith.JustAProperty = "JustAProperty2!";
 920            baseWith.Virtual = "Virtual2!";
 921            baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
 922            baseWith.WithDataMember = "WithDataMember2!";
 923
 924            string json = AssertSerializeDeserializeEqual(baseWith);
 925
 926            Assert.AreEqual(@"{
 927  ""JustAProperty"": ""JustAProperty2!"",
 928  ""Virtual"": ""Virtual2!"",
 929  ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
 930  ""VirtualWithDataMemberSub"": ""VirtualWithDataMember!"",
 931  ""WithDataMemberBase"": ""WithDataMember2!""
 932}", json);
 933        }
 934
 935        private string AssertSerializeDeserializeEqual(object o)
 936        {
 937            MemoryStream ms = new MemoryStream();
 938            DataContractJsonSerializer s = new DataContractJsonSerializer(o.GetType());
 939            s.WriteObject(ms, o);
 940
 941            var data = ms.ToArray();
 942            JObject dataContractJson = JObject.Parse(Encoding.UTF8.GetString(data, 0, data.Length));
 943            dataContractJson = new JObject(dataContractJson.Properties().OrderBy(p => p.Name));
 944
 945            JObject jsonNetJson = JObject.Parse(JsonConvert.SerializeObject(o));
 946            jsonNetJson = new JObject(jsonNetJson.Properties().OrderBy(p => p.Name));
 947
 948            Console.WriteLine("Results for " + o.GetType().Name);
 949            Console.WriteLine("DataContractJsonSerializer: " + dataContractJson);
 950            Console.WriteLine("JsonDotNetSerializer      : " + jsonNetJson);
 951
 952            Assert.AreEqual(dataContractJson.Count, jsonNetJson.Count);
 953            foreach (KeyValuePair<string, JToken> property in dataContractJson)
 954            {
 955                Assert.IsTrue(JToken.DeepEquals(jsonNetJson[property.Key], property.Value), "Property not equal: " + property.Key);
 956            }
 957
 958            return jsonNetJson.ToString();
 959        }
 960#endif
 961
 962        [Test]
 963        public void PersonTypedObjectDeserialization()
 964        {
 965            Store store = new Store();
 966
 967            string jsonText = JsonConvert.SerializeObject(store);
 968
 969            Store deserializedStore = (Store)JsonConvert.DeserializeObject(jsonText, typeof(Store));
 970
 971            Assert.AreEqual(store.Establised, deserializedStore.Establised);
 972            Assert.AreEqual(store.product.Count, deserializedStore.product.Count);
 973
 974            Console.WriteLine(jsonText);
 975        }
 976
 977        [Test]
 978        public void TypedObjectDeserialization()
 979        {
 980            Product product = new Product();
 981
 982            product.Name = "Apple";
 983            product.ExpiryDate = new DateTime(2008, 12, 28);
 984            product.Price = 3.99M;
 985            product.Sizes = new string[] { "Small", "Medium", "Large" };
 986
 987            string output = JsonConvert.SerializeObject(product);
 988            //{
 989            //  "Name": "Apple",
 990            //  "ExpiryDate": "\/Date(1230375600000+1300)\/",
 991            //  "Price": 3.99,
 992            //  "Sizes": [
 993            //    "Small",
 994            //    "Medium",
 995            //    "Large"
 996            //  ]
 997            //}
 998
 999            Product deserializedProduct = (Product)JsonConvert.DeserializeObject(output, typeof(Product));
1000
1001            Assert.AreEqual("Apple", deserializedProduct.Name);
1002            Assert.AreEqual(new DateTime(2008, 12, 28), deserializedProduct.ExpiryDate);
1003            Assert.AreEqual(3.99m, deserializedProduct.Price);
1004            Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
1005            Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
1006            Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
1007        }
1008
1009        //[Test]
1010        //public void Advanced()
1011        //{
1012        //  Product product = new Product();
1013        //  product.ExpiryDate = new DateTime(2008, 12, 28);
1014
1015        //  JsonSerializer serializer = new JsonSerializer();
1016        //  serializer.Converters.Add(new JavaScriptDateTimeConverter());
1017        //  serializer.NullValueHandling = NullValueHandling.Ignore;
1018
1019        //  using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
1020        //  using (JsonWriter writer = new JsonTextWriter(sw))
1021        //  {
1022        //    serializer.Serialize(writer, product);
1023        //    // {"ExpiryDate":new Date(1230375600000),"Price":0}
1024        //  }
1025        //}
1026
1027        [Test]
1028        public void JsonConvertSerializer()
1029        {
1030            string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
1031
1032            Product p = JsonConvert.DeserializeObject(value, typeof(Product)) as Product;
1033
1034            Assert.AreEqual("Orange", p.Name);
1035            Assert.AreEqual(new DateTime(2010, 1, 24, 12, 0, 0), p.ExpiryDate);
1036            Assert.AreEqual(3.99m, p.Price);
1037        }
1038
1039        [Test]
1040        public void DeserializeJavaScriptDate()
1041        {
1042            DateTime dateValue = new DateTime(2010, 3, 30);
1043            Dictionary<string, object> testDictionary = new Dictionary<string, object>();
1044            testDictionary["date"] = dateValue;
1045
1046            string jsonText = JsonConvert.SerializeObject(testDictionary);
1047
1048#if !NET20
1049            MemoryStream ms = new MemoryStream();
1050            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<string, object>));
1051            serializer.WriteObject(ms, testDictionary);
1052
1053            byte[] data = ms.ToArray();
1054            string output = Encoding.UTF8.GetString(data, 0, data.Length);
1055#endif
1056
1057            Dictionary<string, object> deserializedDictionary = (Dictionary<string, object>)JsonConvert.DeserializeObject(jsonText, typeof(Dictionary<string, object>));
1058            DateTime deserializedDate = (DateTime)deserializedDictionary["date"];
1059
1060            Assert.AreEqual(dateValue, deserializedDate);
1061        }
1062
1063        [Test]
1064        public void TestMethodExecutorObject()
1065        {
1066            MethodExecutorObject executorObject = new MethodExecutorObject();
1067            executorObject.serverClassName = "BanSubs";
1068            executorObject.serverMethodParams = new object[] { "21321546", "101", "1236", "D:\\1.txt" };
1069            executorObject.clientGetResultFunction = "ClientBanSubsCB";
1070
1071            string output = JsonConvert.SerializeObject(executorObject);
1072
1073            MethodExecutorObject executorObject2 = JsonConvert.DeserializeObject(output, typeof(MethodExecutorObject)) as MethodExecutorObject;
1074
1075            Assert.AreNotSame(executorObject, executorObject2);
1076            Assert.AreEqual(executorObject2.serverClassName, "BanSubs");
1077            Assert.AreEqual(executorObject2.serverMethodParams.Length, 4);
1078            CustomAssert.Contains(executorObject2.serverMethodParams, "101");
1079            Assert.AreEqual(executorObject2.clientGetResultFunction, "ClientBanSubsCB");
1080        }
1081
1082#if !NETFX_CORE
1083        [Test]
1084        public void HashtableDeserialization()
1085        {
1086            string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
1087
1088            Hashtable p = JsonConvert.DeserializeObject(value, typeof(Hashtable)) as Hashtable;
1089
1090            Assert.AreEqual("Orange", p["Name"].ToString());
1091        }
1092
1093        [Test]
1094        public void TypedHashtableDeserialization()
1095        {
1096            string value = @"{""Name"":""Orange"", ""Hash"":{""ExpiryDate"":""01/24/2010 12:00:00"",""UntypedArray"":[""01/24/2010 12:00:00""]}}";
1097
1098            TypedSubHashtable p = JsonConvert.DeserializeObject(value, typeof(TypedSubHashtable)) as TypedSubHashtable;
1099
1100            Assert.AreEqual("01/24/2010 12:00:00", p.Hash["ExpiryDate"].ToString());
1101            Assert.AreEqual(@"[
1102  ""01/24/2010 12:00:00""
1103]", p.Hash["UntypedArray"].ToString());
1104        }
1105#endif
1106
1107        [Test]
1108        public void SerializeDeserializeGetOnlyProperty()
1109        {
1110            string value = JsonConvert.SerializeObject(new GetOnlyPropertyClass());
1111
1112            GetOnlyPropertyClass c = JsonConvert.DeserializeObject<GetOnlyPropertyClass>(value);
1113
1114            Assert.AreEqual(c.Field, "Field");
1115            Assert.AreEqual(c.GetOnlyProperty, "GetOnlyProperty");
1116        }
1117
1118        [Test]
1119        public void SerializeDeserializeSetOnlyProperty()
1120        {
1121            string value = JsonConvert.SerializeObject(new SetOnlyPropertyClass());
1122
1123            SetOnlyPropertyClass c = JsonConvert.DeserializeObject<SetOnlyPropertyClass>(value);
1124
1125            Assert.AreEqual(c.Field, "Field");
1126        }
1127
1128        [Test]
1129        public void JsonIgnoreAttributeTest()
1130        {
1131            string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeTestClass());
1132
1133            Assert.AreEqual(@"{""Field"":0,""Property"":21}", json);
1134
1135            JsonIgnoreAttributeTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeTestClass>(@"{""Field"":99,""Property"":-1,""IgnoredField"":-1,""IgnoredObject"":[1,2,3,4,5]}");
1136
1137            Assert.AreEqual(0, c.IgnoredField);
1138            Assert.AreEqual(99, c.Field);
1139        }
1140
1141        [Test]
1142        public void GoogleSearchAPI()
1143        {
1144            string json = @"{
1145    results:
1146        [
1147            {
1148                GsearchResultClass:""GwebSearch"",
1149                unescapedUrl : ""http://www.google.com/"",
1150                url : ""http://www.google.com/"",
1151                visibleUrl : ""www.google.com"",
1152                cacheUrl : 
1153""http://www.google.com/search?q=cache:zhool8dxBV4J:www.google.com"",
1154                title : ""Google"",
1155                titleNoFormatting : ""Google"",
1156                content : ""Enables users to search the Web, Usenet, and 
1157images. Features include PageRank,   caching and translation of 
1158results, and an option to find similar pages.""
1159            },
1160            {
1161                GsearchResultClass:""GwebSearch"",
1162                unescapedUrl : ""http://news.google.com/"",
1163                url : ""http://news.google.com/"",
1164                visibleUrl : ""news.google.com"",
1165                cacheUrl : 
1166""http://www.google.com/search?q=cache:Va_XShOz_twJ:news.google.com"",
1167                title : ""Google News"",
1168                titleNoFormatting : ""Google News"",
1169                content : ""Aggregated headlines and a search engine of many of the world's news sources.""
1170            },
1171            
1172            {
1173                GsearchResultClass:""GwebSearch"",
1174                unescapedUrl : ""http://groups.google.com/"",
1175                url : ""http://groups.google.com/"",
1176                visibleUrl : ""groups.google.com"",
1177                cacheUrl : 
1178""http://www.google.com/search?q=cache:x2uPD3hfkn0J:groups.google.com"",
1179                title : ""Google Groups"",
1180                titleNoFormatting : ""Google Groups"",
1181                content : ""Enables users to search and browse the Usenet 
1182archives which consist of over 700   million messages, and post new 
1183comments.""
1184            },
1185            
1186            {
1187                GsearchResultClass:""GwebSearch"",
1188                unescapedUrl : ""http://maps.google.com/"",
1189                url : ""http://maps.google.com/"",
1190                visibleUrl : ""maps.google.com"",
1191                cacheUrl : 
1192""http://www.google.com/search?q=cache:dkf5u2twBXIJ:maps.google.com"",
1193                title : ""Google Maps"",
1194                titleNoFormatting : ""Google Maps"",
1195                content : ""Provides directions, interactive maps, and 
1196satellite/aerial imagery of the United   States. Can also search by 
1197keyword such as type of business.""
1198            }
1199        ],
1200        
1201    adResults:
1202        [
1203            {
1204                GsearchResultClass:""GwebSearch.ad"",
1205                title : ""Gartner Symposium/ITxpo"",
1206                content1 : ""Meet brilliant Gartner IT analysts"",
1207                content2 : ""20-23 May 2007- Barcelona, Spain"",
1208                url : 
1209""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="", 
1210
1211                impressionUrl : 
1212""http://www.google.com/uds/css/ad-indicator-on.gif?ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB"", 
1213
1214                unescapedUrl : 
1215""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="", 
1216
1217                visibleUrl : ""www.gartner.com""
1218            }
1219        ]
1220}
1221";
1222            object o = JsonConvert.DeserializeObject(json);
1223            string s = string.Empty;
1224            s += s;
1225        }
1226
1227        [Test]
1228        public void TorrentDeserializeTest()
1229        {
1230            string jsonText = @"{
1231"""":"""",
1232""label"": [
1233       [""SomeName"",6]
1234],
1235""torrents"": [
1236       [""192D99A5C943555CB7F00A852821CF6D6DB3008A"",201,""filename.avi"",178311826,1000,178311826,72815250,408,1603,7,121430,""NameOfLabelPrevioslyDefined"",3,6,0,8,128954,-1,0],
1237],
1238""torrentc"": ""1816000723""
1239}";
1240
1241            JObject o = (JObject)JsonConvert.DeserializeObject(jsonText);
1242            Assert.AreEqual(4, o.Children().Count());
1243
1244            JToken torrentsArray = (JToken)o["torrents"];
1245            JToken nestedTorrentsArray = (JToken)torrentsArray[0];
1246            Assert.AreEqual(nestedTorrentsArray.Children().Count(), 19);
1247        }
1248
1249        [Test]
1250        public void JsonPropertyClassSerialize()
1251        {
1252            JsonPropertyClass test = new JsonPropertyClass();
1253            test.Pie = "Delicious";
1254            test.SweetCakesCount = int.MaxValue;
1255
1256            string jsonText = JsonConvert.SerializeObject(test);
1257
1258            Assert.AreEqual(@"{""pie"":""Delicious"",""pie1"":""PieChart!"",""sweet_cakes_count"":2147483647}", jsonText);
1259
1260            JsonPropertyClass test2 = JsonConvert.DeserializeObject<JsonPropertyClass>(jsonText);
1261
1262            Assert.AreEqual(test.Pie, test2.Pie);
1263            Assert.AreEqual(test.SweetCakesCount, test2.SweetCakesCount);
1264        }
1265
1266        [Test]
1267        public void BadJsonPropertyClassSerialize()
1268        {
1269            ExceptionAssert.Throws<JsonSerializationException>(
1270                @"A member with the name 'p…

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