PageRenderTime 90ms CodeModel.GetById 7ms app.highlight 61ms RepoModel.GetById 1ms app.codeStats 2ms

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

https://github.com/advancedrei/Newtonsoft.Json
C# | 7906 lines | 7136 code | 636 blank | 134 comment | 68 complexity | 85ec14f216654ad3a49e7b98baf6f63d 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;
  27#if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE)
  28using System.Collections.Concurrent;
  29#endif
  30using System.Collections.Generic;
  31#if !SILVERLIGHT && !NET20 && !NETFX_CORE
  32using System.ComponentModel.DataAnnotations;
  33using System.Configuration;
  34using System.Runtime.CompilerServices;
  35using System.Runtime.Serialization.Formatters;
  36using System.Threading;
  37using System.Web.Script.Serialization;
  38#endif
  39using System.Text;
  40#if !NETFX_CORE
  41using NUnit.Framework;
  42#else
  43using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
  44using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
  45using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
  46#endif
  47using Newtonsoft.Json;
  48using System.IO;
  49using System.Collections;
  50using System.Xml;
  51using System.Xml.Serialization;
  52using System.Collections.ObjectModel;
  53using Newtonsoft.Json.Bson;
  54using Newtonsoft.Json.Linq;
  55using Newtonsoft.Json.Converters;
  56#if !NET20 && !WINDOWS_PHONE
  57using System.Runtime.Serialization.Json;
  58#endif
  59using Newtonsoft.Json.Serialization;
  60using Newtonsoft.Json.Tests.Linq;
  61using Newtonsoft.Json.Tests.TestObjects;
  62using System.Runtime.Serialization;
  63using System.Globalization;
  64using Newtonsoft.Json.Utilities;
  65using System.Reflection;
  66#if !NET20 && !SILVERLIGHT
  67using System.Xml.Linq;
  68using System.Text.RegularExpressions;
  69using System.Collections.Specialized;
  70using System.Linq.Expressions;
  71#endif
  72#if !(NET35 || NET20 || WINDOWS_PHONE)
  73using System.Dynamic;
  74using System.ComponentModel;
  75#endif
  76#if NET20
  77using Newtonsoft.Json.Utilities.LinqBridge;
  78#else
  79using System.Linq;
  80#endif
  81#if !(SILVERLIGHT || NETFX_CORE)
  82using System.Drawing;
  83#endif
  84
  85namespace Newtonsoft.Json.Tests.Serialization
  86{
  87  [TestFixture]
  88  public class JsonSerializerTest : TestFixtureBase
  89  {
  90    [Test]
  91    public void PersonTypedObjectDeserialization()
  92    {
  93      Store store = new Store();
  94
  95      string jsonText = JsonConvert.SerializeObject(store);
  96
  97      Store deserializedStore = (Store)JsonConvert.DeserializeObject(jsonText, typeof(Store));
  98
  99      Assert.AreEqual(store.Establised, deserializedStore.Establised);
 100      Assert.AreEqual(store.product.Count, deserializedStore.product.Count);
 101
 102      Console.WriteLine(jsonText);
 103    }
 104
 105    [Test]
 106    public void TypedObjectDeserialization()
 107    {
 108      Product product = new Product();
 109
 110      product.Name = "Apple";
 111      product.ExpiryDate = new DateTime(2008, 12, 28);
 112      product.Price = 3.99M;
 113      product.Sizes = new string[] { "Small", "Medium", "Large" };
 114
 115      string output = JsonConvert.SerializeObject(product);
 116      //{
 117      //  "Name": "Apple",
 118      //  "ExpiryDate": "\/Date(1230375600000+1300)\/",
 119      //  "Price": 3.99,
 120      //  "Sizes": [
 121      //    "Small",
 122      //    "Medium",
 123      //    "Large"
 124      //  ]
 125      //}
 126
 127      Product deserializedProduct = (Product)JsonConvert.DeserializeObject(output, typeof(Product));
 128
 129      Assert.AreEqual("Apple", deserializedProduct.Name);
 130      Assert.AreEqual(new DateTime(2008, 12, 28), deserializedProduct.ExpiryDate);
 131      Assert.AreEqual(3.99m, deserializedProduct.Price);
 132      Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
 133      Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
 134      Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
 135    }
 136
 137    //[Test]
 138    //public void Advanced()
 139    //{
 140    //  Product product = new Product();
 141    //  product.ExpiryDate = new DateTime(2008, 12, 28);
 142
 143    //  JsonSerializer serializer = new JsonSerializer();
 144    //  serializer.Converters.Add(new JavaScriptDateTimeConverter());
 145    //  serializer.NullValueHandling = NullValueHandling.Ignore;
 146
 147    //  using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
 148    //  using (JsonWriter writer = new JsonTextWriter(sw))
 149    //  {
 150    //    serializer.Serialize(writer, product);
 151    //    // {"ExpiryDate":new Date(1230375600000),"Price":0}
 152    //  }
 153    //}
 154
 155    [Test]
 156    public void JsonConvertSerializer()
 157    {
 158      string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
 159
 160      Product p = JsonConvert.DeserializeObject(value, typeof(Product)) as Product;
 161
 162      Assert.AreEqual("Orange", p.Name);
 163      Assert.AreEqual(new DateTime(2010, 1, 24, 12, 0, 0), p.ExpiryDate);
 164      Assert.AreEqual(3.99m, p.Price);
 165    }
 166
 167    [Test]
 168    public void DeserializeJavaScriptDate()
 169    {
 170      DateTime dateValue = new DateTime(2010, 3, 30);
 171      Dictionary<string, object> testDictionary = new Dictionary<string, object>();
 172      testDictionary["date"] = dateValue;
 173
 174      string jsonText = JsonConvert.SerializeObject(testDictionary);
 175
 176#if !NET20 && !WINDOWS_PHONE
 177      MemoryStream ms = new MemoryStream();
 178      DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<string, object>));
 179      serializer.WriteObject(ms, testDictionary);
 180
 181      byte[] data = ms.ToArray();
 182      string output = Encoding.UTF8.GetString(data, 0, data.Length);
 183#endif
 184
 185      Dictionary<string, object> deserializedDictionary = (Dictionary<string, object>)JsonConvert.DeserializeObject(jsonText, typeof(Dictionary<string, object>));
 186      DateTime deserializedDate = (DateTime)deserializedDictionary["date"];
 187
 188      Assert.AreEqual(dateValue, deserializedDate);
 189    }
 190
 191    [Test]
 192    public void TestMethodExecutorObject()
 193    {
 194      MethodExecutorObject executorObject = new MethodExecutorObject();
 195      executorObject.serverClassName = "BanSubs";
 196      executorObject.serverMethodParams = new object[] { "21321546", "101", "1236", "D:\\1.txt" };
 197      executorObject.clientGetResultFunction = "ClientBanSubsCB";
 198
 199      string output = JsonConvert.SerializeObject(executorObject);
 200
 201      MethodExecutorObject executorObject2 = JsonConvert.DeserializeObject(output, typeof(MethodExecutorObject)) as MethodExecutorObject;
 202
 203      Assert.AreNotSame(executorObject, executorObject2);
 204      Assert.AreEqual(executorObject2.serverClassName, "BanSubs");
 205      Assert.AreEqual(executorObject2.serverMethodParams.Length, 4);
 206      CustomAssert.Contains(executorObject2.serverMethodParams, "101");
 207      Assert.AreEqual(executorObject2.clientGetResultFunction, "ClientBanSubsCB");
 208    }
 209
 210#if !SILVERLIGHT && !NETFX_CORE
 211    [Test]
 212    public void HashtableDeserialization()
 213    {
 214      string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
 215
 216      Hashtable p = JsonConvert.DeserializeObject(value, typeof(Hashtable)) as Hashtable;
 217
 218      Assert.AreEqual("Orange", p["Name"].ToString());
 219    }
 220
 221    [Test]
 222    public void TypedHashtableDeserialization()
 223    {
 224      string value = @"{""Name"":""Orange"", ""Hash"":{""ExpiryDate"":""01/24/2010 12:00:00"",""UntypedArray"":[""01/24/2010 12:00:00""]}}";
 225
 226      TypedSubHashtable p = JsonConvert.DeserializeObject(value, typeof(TypedSubHashtable)) as TypedSubHashtable;
 227
 228      Assert.AreEqual("01/24/2010 12:00:00", p.Hash["ExpiryDate"].ToString());
 229      Assert.AreEqual(@"[
 230  ""01/24/2010 12:00:00""
 231]", p.Hash["UntypedArray"].ToString());
 232    }
 233#endif
 234
 235    [Test]
 236    public void SerializeDeserializeGetOnlyProperty()
 237    {
 238      string value = JsonConvert.SerializeObject(new GetOnlyPropertyClass());
 239
 240      GetOnlyPropertyClass c = JsonConvert.DeserializeObject<GetOnlyPropertyClass>(value);
 241
 242      Assert.AreEqual(c.Field, "Field");
 243      Assert.AreEqual(c.GetOnlyProperty, "GetOnlyProperty");
 244    }
 245
 246    [Test]
 247    public void SerializeDeserializeSetOnlyProperty()
 248    {
 249      string value = JsonConvert.SerializeObject(new SetOnlyPropertyClass());
 250
 251      SetOnlyPropertyClass c = JsonConvert.DeserializeObject<SetOnlyPropertyClass>(value);
 252
 253      Assert.AreEqual(c.Field, "Field");
 254    }
 255
 256    [Test]
 257    public void JsonIgnoreAttributeTest()
 258    {
 259      string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeTestClass());
 260
 261      Assert.AreEqual(@"{""Field"":0,""Property"":21}", json);
 262
 263      JsonIgnoreAttributeTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeTestClass>(@"{""Field"":99,""Property"":-1,""IgnoredField"":-1,""IgnoredObject"":[1,2,3,4,5]}");
 264
 265      Assert.AreEqual(0, c.IgnoredField);
 266      Assert.AreEqual(99, c.Field);
 267    }
 268
 269    [Test]
 270    public void GoogleSearchAPI()
 271    {
 272      string json = @"{
 273    results:
 274        [
 275            {
 276                GsearchResultClass:""GwebSearch"",
 277                unescapedUrl : ""http://www.google.com/"",
 278                url : ""http://www.google.com/"",
 279                visibleUrl : ""www.google.com"",
 280                cacheUrl : 
 281""http://www.google.com/search?q=cache:zhool8dxBV4J:www.google.com"",
 282                title : ""Google"",
 283                titleNoFormatting : ""Google"",
 284                content : ""Enables users to search the Web, Usenet, and 
 285images. Features include PageRank,   caching and translation of 
 286results, and an option to find similar pages.""
 287            },
 288            {
 289                GsearchResultClass:""GwebSearch"",
 290                unescapedUrl : ""http://news.google.com/"",
 291                url : ""http://news.google.com/"",
 292                visibleUrl : ""news.google.com"",
 293                cacheUrl : 
 294""http://www.google.com/search?q=cache:Va_XShOz_twJ:news.google.com"",
 295                title : ""Google News"",
 296                titleNoFormatting : ""Google News"",
 297                content : ""Aggregated headlines and a search engine of many of the world's news sources.""
 298            },
 299            
 300            {
 301                GsearchResultClass:""GwebSearch"",
 302                unescapedUrl : ""http://groups.google.com/"",
 303                url : ""http://groups.google.com/"",
 304                visibleUrl : ""groups.google.com"",
 305                cacheUrl : 
 306""http://www.google.com/search?q=cache:x2uPD3hfkn0J:groups.google.com"",
 307                title : ""Google Groups"",
 308                titleNoFormatting : ""Google Groups"",
 309                content : ""Enables users to search and browse the Usenet 
 310archives which consist of over 700   million messages, and post new 
 311comments.""
 312            },
 313            
 314            {
 315                GsearchResultClass:""GwebSearch"",
 316                unescapedUrl : ""http://maps.google.com/"",
 317                url : ""http://maps.google.com/"",
 318                visibleUrl : ""maps.google.com"",
 319                cacheUrl : 
 320""http://www.google.com/search?q=cache:dkf5u2twBXIJ:maps.google.com"",
 321                title : ""Google Maps"",
 322                titleNoFormatting : ""Google Maps"",
 323                content : ""Provides directions, interactive maps, and 
 324satellite/aerial imagery of the United   States. Can also search by 
 325keyword such as type of business.""
 326            }
 327        ],
 328        
 329    adResults:
 330        [
 331            {
 332                GsearchResultClass:""GwebSearch.ad"",
 333                title : ""Gartner Symposium/ITxpo"",
 334                content1 : ""Meet brilliant Gartner IT analysts"",
 335                content2 : ""20-23 May 2007- Barcelona, Spain"",
 336                url : 
 337""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="", 
 338
 339                impressionUrl : 
 340""http://www.google.com/uds/css/ad-indicator-on.gif?ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB"", 
 341
 342                unescapedUrl : 
 343""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="", 
 344
 345                visibleUrl : ""www.gartner.com""
 346            }
 347        ]
 348}
 349";
 350      object o = JsonConvert.DeserializeObject(json);
 351      string s = string.Empty;
 352      s += s;
 353    }
 354
 355    [Test]
 356    public void TorrentDeserializeTest()
 357    {
 358      string jsonText = @"{
 359"""":"""",
 360""label"": [
 361       [""SomeName"",6]
 362],
 363""torrents"": [
 364       [""192D99A5C943555CB7F00A852821CF6D6DB3008A"",201,""filename.avi"",178311826,1000,178311826,72815250,408,1603,7,121430,""NameOfLabelPrevioslyDefined"",3,6,0,8,128954,-1,0],
 365],
 366""torrentc"": ""1816000723""
 367}";
 368
 369      JObject o = (JObject)JsonConvert.DeserializeObject(jsonText);
 370      Assert.AreEqual(4, o.Children().Count());
 371
 372      JToken torrentsArray = (JToken)o["torrents"];
 373      JToken nestedTorrentsArray = (JToken)torrentsArray[0];
 374      Assert.AreEqual(nestedTorrentsArray.Children().Count(), 19);
 375    }
 376
 377    [Test]
 378    public void JsonPropertyClassSerialize()
 379    {
 380      JsonPropertyClass test = new JsonPropertyClass();
 381      test.Pie = "Delicious";
 382      test.SweetCakesCount = int.MaxValue;
 383
 384      string jsonText = JsonConvert.SerializeObject(test);
 385
 386      Assert.AreEqual(@"{""pie"":""Delicious"",""pie1"":""PieChart!"",""sweet_cakes_count"":2147483647}", jsonText);
 387
 388      JsonPropertyClass test2 = JsonConvert.DeserializeObject<JsonPropertyClass>(jsonText);
 389
 390      Assert.AreEqual(test.Pie, test2.Pie);
 391      Assert.AreEqual(test.SweetCakesCount, test2.SweetCakesCount);
 392    }
 393
 394    [Test]
 395    public void BadJsonPropertyClassSerialize()
 396    {
 397      ExceptionAssert.Throws<JsonSerializationException>(
 398        @"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name.",
 399        () =>
 400        {
 401          JsonConvert.SerializeObject(new BadJsonPropertyClass());
 402        });
 403    }
 404
 405    [Test]
 406    public void InheritedListSerialize()
 407    {
 408      Article a1 = new Article("a1");
 409      Article a2 = new Article("a2");
 410
 411      ArticleCollection articles1 = new ArticleCollection();
 412      articles1.Add(a1);
 413      articles1.Add(a2);
 414
 415      string jsonText = JsonConvert.SerializeObject(articles1);
 416
 417      ArticleCollection articles2 = JsonConvert.DeserializeObject<ArticleCollection>(jsonText);
 418
 419      Assert.AreEqual(articles1.Count, articles2.Count);
 420      Assert.AreEqual(articles1[0].Name, articles2[0].Name);
 421    }
 422
 423    [Test]
 424    public void ReadOnlyCollectionSerialize()
 425    {
 426      ReadOnlyCollection<int> r1 = new ReadOnlyCollection<int>(new int[] { 0, 1, 2, 3, 4 });
 427
 428      string jsonText = JsonConvert.SerializeObject(r1);
 429
 430      ReadOnlyCollection<int> r2 = JsonConvert.DeserializeObject<ReadOnlyCollection<int>>(jsonText);
 431
 432      CollectionAssert.AreEqual(r1, r2);
 433    }
 434
 435#if !NET20 && !WINDOWS_PHONE
 436    [Test]
 437    public void Unicode()
 438    {
 439      string json = @"[""PRE\u003cPOST""]";
 440
 441      DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<string>));
 442      List<string> dataContractResult = (List<string>)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
 443
 444      List<string> jsonNetResult = JsonConvert.DeserializeObject<List<string>>(json);
 445
 446      Assert.AreEqual(1, jsonNetResult.Count);
 447      Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
 448    }
 449
 450    [Test]
 451    public void BackslashEqivilence()
 452    {
 453      string json = @"[""vvv\/vvv\tvvv\""vvv\bvvv\nvvv\rvvv\\vvv\fvvv""]";
 454
 455#if !SILVERLIGHT && !NETFX_CORE
 456      JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
 457      List<string> javaScriptSerializerResult = javaScriptSerializer.Deserialize<List<string>>(json);
 458#endif
 459
 460      DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<string>));
 461      List<string> dataContractResult = (List<string>)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
 462
 463      List<string> jsonNetResult = JsonConvert.DeserializeObject<List<string>>(json);
 464
 465      Assert.AreEqual(1, jsonNetResult.Count);
 466      Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
 467#if !SILVERLIGHT && !NETFX_CORE
 468      Assert.AreEqual(javaScriptSerializerResult[0], jsonNetResult[0]);
 469#endif
 470    }
 471
 472    [Test]
 473    public void InvalidBackslash()
 474    {
 475      string json = @"[""vvv\jvvv""]";
 476
 477      ExceptionAssert.Throws<JsonReaderException>(
 478        @"Bad JSON escape sequence: \j. Path '', line 1, position 7.",
 479        () =>
 480        {
 481          JsonConvert.DeserializeObject<List<string>>(json);
 482        });
 483    }
 484
 485    [Test]
 486    public void DateTimeTest()
 487    {
 488      List<DateTime> testDates = new List<DateTime>
 489        {
 490          new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Local),
 491          new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
 492          new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc),
 493          new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local),
 494          new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
 495          new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc),
 496        };
 497
 498      MemoryStream ms = new MemoryStream();
 499      DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<DateTime>));
 500      s.WriteObject(ms, testDates);
 501      ms.Seek(0, SeekOrigin.Begin);
 502      StreamReader sr = new StreamReader(ms);
 503
 504      string expected = sr.ReadToEnd();
 505
 506      string result = JsonConvert.SerializeObject(testDates, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
 507      Assert.AreEqual(expected, result);
 508    }
 509
 510    [Test]
 511    public void DateTimeOffsetIso()
 512    {
 513      List<DateTimeOffset> testDates = new List<DateTimeOffset>
 514        {
 515          new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
 516          new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
 517          new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
 518          new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
 519        };
 520
 521      string result = JsonConvert.SerializeObject(testDates);
 522      Assert.AreEqual(@"[""0100-01-01T01:01:01+00:00"",""2000-01-01T01:01:01+00:00"",""2000-01-01T01:01:01+13:00"",""2000-01-01T01:01:01-03:30""]", result);
 523    }
 524
 525    [Test]
 526    public void DateTimeOffsetMsAjax()
 527    {
 528      List<DateTimeOffset> testDates = new List<DateTimeOffset>
 529        {
 530          new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
 531          new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
 532          new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
 533          new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
 534        };
 535
 536      string result = JsonConvert.SerializeObject(testDates, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
 537      Assert.AreEqual(@"[""\/Date(-59011455539000+0000)\/"",""\/Date(946688461000+0000)\/"",""\/Date(946641661000+1300)\/"",""\/Date(946701061000-0330)\/""]", result);
 538    }
 539#endif
 540
 541    [Test]
 542    public void NonStringKeyDictionary()
 543    {
 544      Dictionary<int, int> values = new Dictionary<int, int>();
 545      values.Add(-5, 6);
 546      values.Add(int.MinValue, int.MaxValue);
 547
 548      string json = JsonConvert.SerializeObject(values);
 549
 550      Assert.AreEqual(@"{""-5"":6,""-2147483648"":2147483647}", json);
 551
 552      Dictionary<int, int> newValues = JsonConvert.DeserializeObject<Dictionary<int, int>>(json);
 553
 554      CollectionAssert.AreEqual(values, newValues);
 555    }
 556
 557    [Test]
 558    public void AnonymousObjectSerialization()
 559    {
 560      var anonymous =
 561        new
 562          {
 563            StringValue = "I am a string",
 564            IntValue = int.MaxValue,
 565            NestedAnonymous = new { NestedValue = byte.MaxValue },
 566            NestedArray = new[] { 1, 2 },
 567            Product = new Product() { Name = "TestProduct" }
 568          };
 569
 570      string json = JsonConvert.SerializeObject(anonymous);
 571      Assert.AreEqual(@"{""StringValue"":""I am a string"",""IntValue"":2147483647,""NestedAnonymous"":{""NestedValue"":255},""NestedArray"":[1,2],""Product"":{""Name"":""TestProduct"",""ExpiryDate"":""2000-01-01T00:00:00Z"",""Price"":0.0,""Sizes"":null}}", json);
 572
 573      anonymous = JsonConvert.DeserializeAnonymousType(json, anonymous);
 574      Assert.AreEqual("I am a string", anonymous.StringValue);
 575      Assert.AreEqual(int.MaxValue, anonymous.IntValue);
 576      Assert.AreEqual(255, anonymous.NestedAnonymous.NestedValue);
 577      Assert.AreEqual(2, anonymous.NestedArray.Length);
 578      Assert.AreEqual(1, anonymous.NestedArray[0]);
 579      Assert.AreEqual(2, anonymous.NestedArray[1]);
 580      Assert.AreEqual("TestProduct", anonymous.Product.Name);
 581    }
 582
 583    [Test]
 584    public void CustomCollectionSerialization()
 585    {
 586      ProductCollection collection = new ProductCollection()
 587        {
 588          new Product() {Name = "Test1"},
 589          new Product() {Name = "Test2"},
 590          new Product() {Name = "Test3"}
 591        };
 592
 593      JsonSerializer jsonSerializer = new JsonSerializer();
 594      jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
 595
 596      StringWriter sw = new StringWriter();
 597
 598      jsonSerializer.Serialize(sw, collection);
 599
 600      Assert.AreEqual(@"[{""Name"":""Test1"",""ExpiryDate"":""2000-01-01T00:00:00Z"",""Price"":0.0,""Sizes"":null},{""Name"":""Test2"",""ExpiryDate"":""2000-01-01T00:00:00Z"",""Price"":0.0,""Sizes"":null},{""Name"":""Test3"",""ExpiryDate"":""2000-01-01T00:00:00Z"",""Price"":0.0,""Sizes"":null}]",
 601                      sw.GetStringBuilder().ToString());
 602
 603      ProductCollection collectionNew = (ProductCollection)jsonSerializer.Deserialize(new JsonTextReader(new StringReader(sw.GetStringBuilder().ToString())), typeof(ProductCollection));
 604
 605      CollectionAssert.AreEqual(collection, collectionNew);
 606    }
 607
 608    [Test]
 609    public void SerializeObject()
 610    {
 611      string json = JsonConvert.SerializeObject(new object());
 612      Assert.AreEqual("{}", json);
 613    }
 614
 615    [Test]
 616    public void SerializeNull()
 617    {
 618      string json = JsonConvert.SerializeObject(null);
 619      Assert.AreEqual("null", json);
 620    }
 621
 622    [Test]
 623    public void CanDeserializeIntArrayWhenNotFirstPropertyInJson()
 624    {
 625      string json = "{foo:'hello',bar:[1,2,3]}";
 626      ClassWithArray wibble = JsonConvert.DeserializeObject<ClassWithArray>(json);
 627      Assert.AreEqual("hello", wibble.Foo);
 628
 629      Assert.AreEqual(4, wibble.Bar.Count);
 630      Assert.AreEqual(int.MaxValue, wibble.Bar[0]);
 631      Assert.AreEqual(1, wibble.Bar[1]);
 632      Assert.AreEqual(2, wibble.Bar[2]);
 633      Assert.AreEqual(3, wibble.Bar[3]);
 634    }
 635
 636    [Test]
 637    public void CanDeserializeIntArray_WhenArrayIsFirstPropertyInJson()
 638    {
 639      string json = "{bar:[1,2,3], foo:'hello'}";
 640      ClassWithArray wibble = JsonConvert.DeserializeObject<ClassWithArray>(json);
 641      Assert.AreEqual("hello", wibble.Foo);
 642
 643      Assert.AreEqual(4, wibble.Bar.Count);
 644      Assert.AreEqual(int.MaxValue, wibble.Bar[0]);
 645      Assert.AreEqual(1, wibble.Bar[1]);
 646      Assert.AreEqual(2, wibble.Bar[2]);
 647      Assert.AreEqual(3, wibble.Bar[3]);
 648    }
 649
 650    [Test]
 651    public void ObjectCreationHandlingReplace()
 652    {
 653      string json = "{bar:[1,2,3], foo:'hello'}";
 654
 655      JsonSerializer s = new JsonSerializer();
 656      s.ObjectCreationHandling = ObjectCreationHandling.Replace;
 657
 658      ClassWithArray wibble = (ClassWithArray)s.Deserialize(new StringReader(json), typeof(ClassWithArray));
 659
 660      Assert.AreEqual("hello", wibble.Foo);
 661
 662      Assert.AreEqual(1, wibble.Bar.Count);
 663    }
 664
 665    [Test]
 666    public void CanDeserializeSerializedJson()
 667    {
 668      ClassWithArray wibble = new ClassWithArray();
 669      wibble.Foo = "hello";
 670      wibble.Bar.Add(1);
 671      wibble.Bar.Add(2);
 672      wibble.Bar.Add(3);
 673      string json = JsonConvert.SerializeObject(wibble);
 674
 675      ClassWithArray wibbleOut = JsonConvert.DeserializeObject<ClassWithArray>(json);
 676      Assert.AreEqual("hello", wibbleOut.Foo);
 677
 678      Assert.AreEqual(5, wibbleOut.Bar.Count);
 679      Assert.AreEqual(int.MaxValue, wibbleOut.Bar[0]);
 680      Assert.AreEqual(int.MaxValue, wibbleOut.Bar[1]);
 681      Assert.AreEqual(1, wibbleOut.Bar[2]);
 682      Assert.AreEqual(2, wibbleOut.Bar[3]);
 683      Assert.AreEqual(3, wibbleOut.Bar[4]);
 684    }
 685
 686    [Test]
 687    public void SerializeConverableObjects()
 688    {
 689      string json = JsonConvert.SerializeObject(new ConverableMembers(), Formatting.Indented);
 690
 691      string expected = null;
 692#if !(NETFX_CORE || PORTABLE)
 693      expected = @"{
 694  ""String"": ""string"",
 695  ""Int32"": 2147483647,
 696  ""UInt32"": 4294967295,
 697  ""Byte"": 255,
 698  ""SByte"": 127,
 699  ""Short"": 32767,
 700  ""UShort"": 65535,
 701  ""Long"": 9223372036854775807,
 702  ""ULong"": 9223372036854775807,
 703  ""Double"": 1.7976931348623157E+308,
 704  ""Float"": 3.40282347E+38,
 705  ""DBNull"": null,
 706  ""Bool"": true,
 707  ""Char"": ""\u0000""
 708}";
 709#else
 710      expected = @"{
 711  ""String"": ""string"",
 712  ""Int32"": 2147483647,
 713  ""UInt32"": 4294967295,
 714  ""Byte"": 255,
 715  ""SByte"": 127,
 716  ""Short"": 32767,
 717  ""UShort"": 65535,
 718  ""Long"": 9223372036854775807,
 719  ""ULong"": 9223372036854775807,
 720  ""Double"": 1.7976931348623157E+308,
 721  ""Float"": 3.40282347E+38,
 722  ""Bool"": true,
 723  ""Char"": ""\u0000""
 724}";
 725#endif
 726
 727      Assert.AreEqual(expected, json);
 728
 729      ConverableMembers c = JsonConvert.DeserializeObject<ConverableMembers>(json);
 730      Assert.AreEqual("string", c.String);
 731      Assert.AreEqual(double.MaxValue, c.Double);
 732#if !(NETFX_CORE || PORTABLE)
 733      Assert.AreEqual(DBNull.Value, c.DBNull);
 734#endif
 735    }
 736
 737    [Test]
 738    public void SerializeStack()
 739    {
 740      Stack<object> s = new Stack<object>();
 741      s.Push(1);
 742      s.Push(2);
 743      s.Push(3);
 744
 745      string json = JsonConvert.SerializeObject(s);
 746      Assert.AreEqual("[3,2,1]", json);
 747    }
 748
 749    [Test]
 750    public void GuidTest()
 751    {
 752      Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
 753
 754      string json = JsonConvert.SerializeObject(new ClassWithGuid { GuidField = guid });
 755      Assert.AreEqual(@"{""GuidField"":""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""}", json);
 756
 757      ClassWithGuid c = JsonConvert.DeserializeObject<ClassWithGuid>(json);
 758      Assert.AreEqual(guid, c.GuidField);
 759    }
 760
 761    [Test]
 762    public void EnumTest()
 763    {
 764      string json = JsonConvert.SerializeObject(StringComparison.CurrentCultureIgnoreCase);
 765      Assert.AreEqual(@"1", json);
 766
 767      StringComparison s = JsonConvert.DeserializeObject<StringComparison>(json);
 768      Assert.AreEqual(StringComparison.CurrentCultureIgnoreCase, s);
 769    }
 770
 771    public class ClassWithTimeSpan
 772    {
 773      public TimeSpan TimeSpanField;
 774    }
 775
 776    [Test]
 777    public void TimeSpanTest()
 778    {
 779      TimeSpan ts = new TimeSpan(00, 23, 59, 1);
 780
 781      string json = JsonConvert.SerializeObject(new ClassWithTimeSpan { TimeSpanField = ts }, Formatting.Indented);
 782      Assert.AreEqual(@"{
 783  ""TimeSpanField"": ""23:59:01""
 784}", json);
 785
 786      ClassWithTimeSpan c = JsonConvert.DeserializeObject<ClassWithTimeSpan>(json);
 787      Assert.AreEqual(ts, c.TimeSpanField);
 788    }
 789
 790    [Test]
 791    public void JsonIgnoreAttributeOnClassTest()
 792    {
 793      string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeOnClassTestClass());
 794
 795      Assert.AreEqual(@"{""TheField"":0,""Property"":21}", json);
 796
 797      JsonIgnoreAttributeOnClassTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeOnClassTestClass>(@"{""TheField"":99,""Property"":-1,""IgnoredField"":-1}");
 798
 799      Assert.AreEqual(0, c.IgnoredField);
 800      Assert.AreEqual(99, c.Field);
 801    }
 802
 803#if !SILVERLIGHT && !NETFX_CORE
 804    [Test]
 805    public void SerializeArrayAsArrayList()
 806    {
 807      string jsonText = @"[3, ""somestring"",[1,2,3],{}]";
 808      ArrayList o = JsonConvert.DeserializeObject<ArrayList>(jsonText);
 809
 810      Assert.AreEqual(4, o.Count);
 811      Assert.AreEqual(3, ((JArray)o[2]).Count);
 812      Assert.AreEqual(0, ((JObject)o[3]).Count);
 813    }
 814#endif
 815
 816    [Test]
 817    public void SerializeMemberGenericList()
 818    {
 819      Name name = new Name("The Idiot in Next To Me");
 820
 821      PhoneNumber p1 = new PhoneNumber("555-1212");
 822      PhoneNumber p2 = new PhoneNumber("444-1212");
 823
 824      name.pNumbers.Add(p1);
 825      name.pNumbers.Add(p2);
 826
 827      string json = JsonConvert.SerializeObject(name, Formatting.Indented);
 828
 829      Assert.AreEqual(@"{
 830  ""personsName"": ""The Idiot in Next To Me"",
 831  ""pNumbers"": [
 832    {
 833      ""phoneNumber"": ""555-1212""
 834    },
 835    {
 836      ""phoneNumber"": ""444-1212""
 837    }
 838  ]
 839}", json);
 840
 841      Name newName = JsonConvert.DeserializeObject<Name>(json);
 842
 843      Assert.AreEqual("The Idiot in Next To Me", newName.personsName);
 844
 845      // not passed in as part of the constructor but assigned to pNumbers property
 846      Assert.AreEqual(2, newName.pNumbers.Count);
 847      Assert.AreEqual("555-1212", newName.pNumbers[0].phoneNumber);
 848      Assert.AreEqual("444-1212", newName.pNumbers[1].phoneNumber);
 849    }
 850
 851    [Test]
 852    public void ConstructorCaseSensitivity()
 853    {
 854      ConstructorCaseSensitivityClass c = new ConstructorCaseSensitivityClass("param1", "Param1", "Param2");
 855
 856      string json = JsonConvert.SerializeObject(c);
 857
 858      ConstructorCaseSensitivityClass deserialized = JsonConvert.DeserializeObject<ConstructorCaseSensitivityClass>(json);
 859
 860      Assert.AreEqual("param1", deserialized.param1);
 861      Assert.AreEqual("Param1", deserialized.Param1);
 862      Assert.AreEqual("Param2", deserialized.Param2);
 863    }
 864
 865    [Test]
 866    public void SerializerShouldUseClassConverter()
 867    {
 868      ConverterPrecedenceClass c1 = new ConverterPrecedenceClass("!Test!");
 869
 870      string json = JsonConvert.SerializeObject(c1);
 871      Assert.AreEqual(@"[""Class"",""!Test!""]", json);
 872
 873      ConverterPrecedenceClass c2 = JsonConvert.DeserializeObject<ConverterPrecedenceClass>(json);
 874
 875      Assert.AreEqual("!Test!", c2.TestValue);
 876    }
 877
 878    [Test]
 879    public void SerializerShouldUseClassConverterOverArgumentConverter()
 880    {
 881      ConverterPrecedenceClass c1 = new ConverterPrecedenceClass("!Test!");
 882
 883      string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
 884      Assert.AreEqual(@"[""Class"",""!Test!""]", json);
 885
 886      ConverterPrecedenceClass c2 = JsonConvert.DeserializeObject<ConverterPrecedenceClass>(json, new ArgumentConverterPrecedenceClassConverter());
 887
 888      Assert.AreEqual("!Test!", c2.TestValue);
 889    }
 890
 891    [Test]
 892    public void SerializerShouldUseMemberConverter_IsoDate()
 893    {
 894      DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
 895      MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
 896
 897      string json = JsonConvert.SerializeObject(m1);
 898      Assert.AreEqual(@"{""DefaultConverter"":""1970-01-01T00:00:00Z"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
 899
 900      MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
 901
 902      Assert.AreEqual(testDate, m2.DefaultConverter);
 903      Assert.AreEqual(testDate, m2.MemberConverter);
 904    }
 905
 906    [Test]
 907    public void SerializerShouldUseMemberConverter_MsDate()
 908    {
 909      DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
 910      MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
 911
 912      string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
 913        {
 914          DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
 915        });
 916      Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
 917
 918      MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
 919
 920      Assert.AreEqual(testDate, m2.DefaultConverter);
 921      Assert.AreEqual(testDate, m2.MemberConverter);
 922    }
 923
 924    [Test]
 925    public void SerializerShouldUseMemberConverter_MsDate_DateParseNone()
 926    {
 927      DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
 928      MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
 929
 930      string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
 931      {
 932        DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
 933      });
 934      Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
 935
 936      ExceptionAssert.Throws<JsonReaderException>(
 937       "Could not convert string to DateTime: /Date(0)/. Path 'DefaultConverter', line 1, position 33.",
 938       () =>
 939       {
 940         JsonConvert.DeserializeObject<MemberConverterClass>(json, new JsonSerializerSettings
 941         {
 942           DateParseHandling = DateParseHandling.None
 943         });
 944       });
 945    }
 946
 947    [Test]
 948    public void SerializerShouldUseMemberConverter_IsoDate_DateParseNone()
 949    {
 950      DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
 951      MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
 952
 953      string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
 954      {
 955        DateFormatHandling = DateFormatHandling.IsoDateFormat,
 956      });
 957      Assert.AreEqual(@"{""DefaultConverter"":""1970-01-01T00:00:00Z"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
 958
 959      MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
 960
 961      Assert.AreEqual(testDate, m2.DefaultConverter);
 962      Assert.AreEqual(testDate, m2.MemberConverter);
 963    }
 964
 965    [Test]
 966    public void SerializerShouldUseMemberConverterOverArgumentConverter()
 967    {
 968      DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
 969      MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
 970
 971      string json = JsonConvert.SerializeObject(m1, new JavaScriptDateTimeConverter());
 972      Assert.AreEqual(@"{""DefaultConverter"":new Date(0),""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
 973
 974      MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json, new JavaScriptDateTimeConverter());
 975
 976      Assert.AreEqual(testDate, m2.DefaultConverter);
 977      Assert.AreEqual(testDate, m2.MemberConverter);
 978    }
 979
 980    [Test]
 981    public void ConverterAttributeExample()
 982    {
 983      DateTime date = Convert.ToDateTime("1970-01-01T00:00:00Z").ToUniversalTime();
 984
 985      MemberConverterClass c = new MemberConverterClass
 986        {
 987          DefaultConverter = date,
 988          MemberConverter = date
 989        };
 990
 991      string json = JsonConvert.SerializeObject(c, Formatting.Indented);
 992
 993      Console.WriteLine(json);
 994      //{
 995      //  "DefaultConverter": "\/Date(0)\/",
 996      //  "MemberConverter": "1970-01-01T00:00:00Z"
 997      //}
 998    }
 999
1000    [Test]
1001    public void SerializerShouldUseMemberConverterOverClassAndArgumentConverter()
1002    {
1003      ClassAndMemberConverterClass c1 = new ClassAndMemberConverterClass();
1004      c1.DefaultConverter = new ConverterPrecedenceClass("DefaultConverterValue");
1005      c1.MemberConverter = new ConverterPrecedenceClass("MemberConverterValue");
1006
1007      string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
1008      Assert.AreEqual(@"{""DefaultConverter"":[""Class"",""DefaultConverterValue""],""MemberConverter"":[""Member"",""MemberConverterValue""]}", json);
1009
1010      ClassAndMemberConverterClass c2 = JsonConvert.DeserializeObject<ClassAndMemberConverterClass>(json, new ArgumentConverterPrecedenceClassConverter());
1011
1012      Assert.AreEqual("DefaultConverterValue", c2.DefaultConverter.TestValue);
1013      Assert.AreEqual("MemberConverterValue", c2.MemberConverter.TestValue);
1014    }
1015
1016    [Test]
1017    public void IncompatibleJsonAttributeShouldThrow()
1018    {
1019      ExceptionAssert.Throws<JsonSerializationException>(
1020        "Unexpected value when converting date. Expected DateTime or DateTimeOffset, got Newtonsoft.Json.Tests.TestObjects.IncompatibleJsonAttributeClass.",
1021        () =>
1022        {
1023          IncompatibleJsonAttributeClass c = new IncompatibleJsonAttributeClass();
1024          JsonConvert.SerializeObject(c);
1025        });
1026    }
1027
1028    [Test]
1029    public void GenericAbstractProperty()
1030    {
1031      string json = JsonConvert.SerializeObject(new GenericImpl());
1032      Assert.AreEqual(@"{""Id"":0}", json);
1033    }
1034
1035    [Test]
1036    public void DeserializeNullable()
1037    {
1038      string json;
1039
1040      json = JsonConvert.SerializeObject((int?)null);
1041      Assert.AreEqual("null", json);
1042
1043      json = JsonConvert.SerializeObject((int?)1);
1044      Assert.AreEqual("1", json);
1045    }
1046
1047    [Test]
1048    public void SerializeJsonRaw()
1049    {
1050      PersonRaw personRaw = new PersonRaw
1051        {
1052          FirstName = "FirstNameValue",
1053          RawContent = new JRaw("[1,2,3,4,5]"),
1054          LastName = "LastNameValue"
1055        };
1056
1057      string json;
1058
1059      json = JsonConvert.SerializeObject(personRaw);
1060      Assert.AreEqual(@"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}", json);
1061    }
1062
1063    [Test]
1064    public void DeserializeJsonRaw()
1065    {
1066      string json = @"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}";
1067
1068      PersonRaw personRaw = JsonConvert.DeserializeObject<PersonRaw>(json);
1069
1070      Assert.AreEqual("FirstNameValue", personRaw.FirstName);
1071      Assert.AreEqual("[1,2,3,4,5]", personRaw.RawContent.ToString());
1072      Assert.AreEqual("LastNameValue", personRaw.LastName);
1073    }
1074
1075
1076    [Test]
1077    public void DeserializeNullableMember()
1078    {
1079      UserNullable userNullablle = new UserNullable
1080        {
1081          Id = new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"),
1082          FName = "FirstValue",
1083          LName = "LastValue",
1084          RoleId = 5,
1085          NullableRoleId = 6,
1086          NullRoleId = null,
1087          Active = true
1088        };
1089
1090      string json = JsonConvert.SerializeObject(userNullablle);
1091
1092      Assert.AreEqual(@"{""Id"":""ad6205e8-0df4-465d-aea6-8ba18e93a7e7"",""FName"":""FirstValue"",""LName"":""LastValue"",""RoleId"":5,""NullableRoleId"":6,""NullRoleId"":null,""Active"":true}", json);
1093
1094      UserNullable userNullablleDeserialized = JsonConvert.DeserializeObject<UserNullable>(json);
1095
1096      Assert.AreEqual(new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"), userNullablleDeserialized.Id);
1097      Assert.AreEqual("FirstValue", userNullablleDeserialized.FName);
1098      Assert.AreEqual("LastValue", userNullablleDeserialized.LName);
1099      Assert.AreEqual(5, userNullablleDeserialized.RoleId);
1100      Assert.AreEqual(6, userNullablleDeserialized.NullableRoleId);
1101      Assert.AreEqual(null, userNullablleDeserialized.NullRoleId);
1102      Assert.AreEqual(true, userNullablleDeserialized.Active);
1103    }
1104
1105    [Test]
1106    public void DeserializeInt64ToNullableDouble()
1107    {
1108      string json = @"{""Height"":1}";
1109
1110      DoubleClass c = JsonConvert.DeserializeObject<DoubleClass>(json);
1111      Assert.AreEqual(1, c.Height);
1112    }
1113
1114    [Test]
1115    public void SerializeTypeProperty()
1116    {
1117      string boolRef = typeof(bool).AssemblyQualifiedName;
1118      TypeClass typeClass = new TypeClass { TypeProperty = typeof(bool) };
1119
1120      string json = JsonConvert.SerializeObject(typeClass);
1121      Assert.AreEqual(@"{""TypeProperty"":""" + boolRef + @"""}", json);
1122
1123      TypeClass typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
1124      Assert.AreEqual(typeof(bool), typeClass2.TypeProperty);
1125
1126      string jsonSerializerTestRef = typeof(JsonSerializerTest).AssemblyQualifiedName;
1127      typeClass = new TypeClass { TypeProperty = typeof(JsonSerializerTest) };
1128
1129      json = JsonConvert.SerializeObject(typeClass);
1130      Assert.AreEqual(@"{""TypeProperty"":""" + jsonSerializerTestRef + @"""}", json);
1131
1132      typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
1133      Assert.AreEqual(typeof(JsonSerializerTest), typeClass2.TypeProperty);
1134    }
1135
1136    [Test]
1137    public void RequiredMembersClass()
1138    {
1139      RequiredMembersClass c = new RequiredMembersClass()
1140        {
1141          BirthDate = new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc),
1142          FirstName = "Bob",
1143          LastName = "Smith",
1144          MiddleName = "Cosmo"
1145        };
1146
1147      string json = JsonConvert.SerializeObject(c, Formatting.Indented);
1148
1149      Assert.AreEqual(@"{
1150  ""FirstName"": ""Bob"",
1151  ""MiddleName"": ""Cosmo"",
1152  ""LastName"": ""Smith"",
1153  ""BirthDate"": ""2000-12-20T10:55:55Z""
1154}", json);
1155
1156      RequiredMembersClass c2 = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
1157
1158      Assert.AreEqual("Bob", c2.FirstName);
1159      Assert.AreEqual(new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc), c2.BirthDate);
1160    }
1161
1162    [Test]
1163    public void DeserializeRequiredMembersClassWithNullValues()
1164    {
1165      string json = @"{
1166  ""FirstName"": ""I can't be null bro!"",
1167  ""MiddleName"": null,
1168  ""LastName"": null,
1169  ""BirthDate"": ""\/Date(977309755000)\/""
1170}";
1171
1172      RequiredMembersClass c = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
1173
1174      Assert.AreEqual("I can't be null bro!", c.FirstName);
1175      Assert.AreEqual(null, c.MiddleName);
1176      Assert.AreEqual(null, c.LastName);
1177    }
1178
1179    [Test]
1180    public void DeserializeRequiredMembersClassNullRequiredValueProperty()
1181    {
1182      ExceptionAssert.Throws<JsonSerializationException>(
1183        "Required property 'FirstName' expects a value but got null. Path '', line 6, position 2.",
1184        () =>
1185        {
1186          string json = @"{
1187  ""FirstName"": null,
1188  ""MiddleName"": null,
1189  ""LastName"": null,
1190  ""BirthDate"": ""\/Date(977309755000)\/""
1191}";
1192
1193          JsonConvert.DeserializeObject<RequiredMembersClass>(json);
1194        });
1195    }
1196
1197    [Test]
1198    public void SerializeRequiredMembersClassNullRequiredValueProperty()
1199    {
1200      ExceptionAssert.Throws<JsonSerializationException>(
1201        "Cannot write a null value for property 'FirstName'. Property requires a value. Path ''.",
1202        () =>
1203        {
1204          RequiredMembersClass requiredMembersClass = new RequiredMembersClass
1205            {
1206              FirstName = null,
1207              BirthDate = new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc),
1208              LastName = null,
1209              MiddleName = null
1210            };
1211
1212          string json = JsonConvert.SerializeObject(requiredMembersClass);
1213          Console.WriteLine(json);
1214        });
1215    }
1216
1217    [Test]
1218    public void RequiredMembersClassMissingRequiredProperty()
1219    {
1220      ExceptionAssert.Throws<JsonSerializationException>(
1221        "Required property 'LastName' not found in JSON. Path '', line 3, position 2.",
1222        () =>
1223        {
1224          string json = @"{
1225  ""FirstName"": ""Bob""
1226}";
1227
1228          JsonConvert.DeserializeObject<RequiredMembersClass>(json);
1229        });
1230    }
1231
1232    [Test]
1233    public void SerializeJaggedArray()
1234    {
1235      JaggedArray aa = new JaggedArray();
1236      aa.Before = "Before!";
1237      aa.After = "After!";
1238      aa.Coordinates = new[] { new[] { 1, 1 }, new[] { 1, 2 }, new[] { 2, 1 }, new[] { 2, 2 } };
1239
1240      string json = JsonConvert.SerializeObject(aa);
1241
1242      Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}", json);
1243    }
1244
1245    [Test]
1246    public void DeserializeJaggedArray()
1247    {
1248      string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}";
1249
1250      JaggedArray aa = JsonConvert.DeserializeObject<JaggedArray>(json);
1251
1252      Assert.AreEqual("Before!", aa.Before);
1253      Assert.AreEqual("After!", aa.After);
1254      Assert.AreEqual(4, aa.Coordinates.Length);
1255      Assert.AreEqual(2, aa.Coordinates[0].Length);
1256      Assert.AreEqual(1, aa.Coordinates[0][0]);
1257      Assert.AreEqual(2, aa.Coordinates[1][1]);
1258
1259      string after = JsonConvert.SerializeObject(aa);
1260
1261      Assert.AreEqual(json, after);
1262    }
1263
1264    [Test]
1265    public void DeserializeGoogleGeoCode()
1266    {
1267      string json = @"{
1268  ""name"": ""1600 Amphitheatre Parkway, Mountain View, CA, USA"",
1269  ""Status"": {
1270    ""code"": 200,
1271    ""request"": ""geocode""
1272  },
1273  ""Placemark"": [
1274    {
1275      ""address"": ""1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"",
1276      ""AddressDetails"": {
1277        ""Country"": {
1278          ""CountryNameCode"": ""US"",
1279          ""AdministrativeArea"": {
1280            ""AdministrativeAreaName"": ""CA"",
1281            ""SubAdministrativeArea"": {
1282              ""SubAdministrativeAreaName"": ""Santa Clara"",
1283              ""Locality"": {
1284                ""LocalityName"": ""Mountain View"",
1285                ""Thoroughfare"": {
1286                  ""ThoroughfareName"": ""1600 Amphitheatre Pkwy""
1287                },
1288                ""PostalCode"": {
1289                  ""PostalCodeNumber"": ""94043""
1290                }
1291              }
1292            }
1293          }
1294        },
1295        ""Accuracy"": 8
1296      },
1297      ""Point"": {
1298        ""coordinates"": [-122.083739, 37.423021, 0]
1299      }
1300    }
1301  ]
1302}";
1303
1304      GoogleMapGeocoderStructure jsonGoogleMapGeocoder = JsonConvert.DeserializeObject<GoogleMapGeocoderStructure>(json);
1305    }
1306
1307    [Test]
1308    public void DeserializeInterfaceProperty()
1309    {
1310      InterfacePropertyTestClass testClass = new InterfacePropertyTestClass();
1311      testClass.co = new Co();
1312      String strFromTest = JsonConvert.SerializeObject(testClass);
1313
1314      ExceptionAssert.Throws<JsonSerializationException>(
1315        @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantiated. Path 'co.Name', line 1, position 14.",
1316        () =>
1317        {
1318          InterfacePropertyTestClass testFromDe = (InterfacePropertyTestClass)JsonConvert.DeserializeObject(strFromTest, typeof(InterfacePropertyTestClass));
1319        });
1320    }
1321
1322    private Person GetPerson()
1323    {
1324      Person person = new Person
1325        {
1326          Name = "Mike Manager",
1327          BirthDate = new DateTime(1983, 8, 3, 0, 0, 0, DateTimeKind.Utc),
1328          Department = "IT",
1329          LastModified = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc)
1330        };
1331      return person;
1332    }
1333
1334    [Test]
1335    public void WriteJsonDates()
1336    {
1337      LogEntry entry = new LogEntry
1338        {
1339          LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
1340          Details = "Application started."
1341        };
1342
1343      string defaultJson = JsonConvert.SerializeObject(entry);
1344      // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}
1345
1346      string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
1347      // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00.0000000Z"}
1348
1349      string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
1350      // {"Details":"Application started.","LogDate":new Date(1234656000000)}
1351
1352      Console.WriteLine(defaultJson);
1353      Console.WriteLine(isoJson);
1354      Console.WriteLine(javascriptJson);
1355    }
1356
1357    public void GenericListAndDictionaryInterfaceProperties()
1358    {
1359      GenericListAndDictionaryInterfaceProperties o = new GenericListAndDictionaryInterfaceProperties();
1360      o.IDictionaryProperty = new Dictionary<string, int>
1361        {
1362          {"one", 1},
1363          {"two", 2},
1364          {"three", 3}
1365        };
1366      o.IListProperty = new List<int>
1367        {
1368          1, 2, 3
1369        };
1370      o.IEnumerableProperty = new List<int>
1371        {
1372          4, 5, 6
1373        };
1374
1375      string json = JsonConvert.SerializeObject(o, Formatting.Indented);
1376
1377      Assert.AreEqual(@"{
1378  ""IEnumerableProperty"": [
1379    4,
1380    5,
1381    6
1382  ],
1383  ""IListProperty"": [
1384    1,
1385    2,
1386    3
1387  ],
1388  ""IDictionaryProperty"": {
1389    ""one"": 1,
1390    ""two"": 2,
1391    ""three"": 3
1392  }
1393}", json);
1394
1395      GenericListAndDictionaryInterfaceProperties deserializedObject = JsonConvert.DeserializeObject<GenericListAndDictionaryInterfaceProperties>(json);
1396      Assert.IsNotNull(deserializedObject);
1397
1398      CollectionAssert.AreEqual(o.IListProperty.ToArray(), deserializedObject.IListProperty.ToArray());
1399      CollectionAssert.AreEqual(o.IEnumerableProperty.ToArray(), deserializedObject.IEnumerableProperty.ToArray());
1400      CollectionAssert.AreEqual(o.IDictionaryProperty.ToArray(), deserializedObject.IDictionaryProperty.ToArray());
1401    }
1402
1403    [Test]
1404    public void DeserializeBestMatchPropertyCase()
1405    {
1406      string json = @"{
1407  ""firstName"": ""firstName"",
1408  ""FirstName"": ""FirstName"",
1409  ""LastName"": ""LastName"",
1410  ""lastName"": ""lastName"",
1411}";
1412
1413      PropertyCase o = JsonConvert.DeserializeObject<PropertyCase>(json);
1414      Assert.IsNotNull(o);
1415
1416      Assert.AreEqual("firstName", o.firstName);
1417      Assert.AreEqual("FirstName", o.FirstName);
1418      Assert.AreEqual("LastName", o.LastName);
1419      Assert.AreEqual("lastName", o.lastName);
1420    }
1421
1422    [Test]
1423    public void DeserializePropertiesOnToNonDefaultConstructor()
1424    {
1425      SubKlass i = new SubKlass("my subprop");
1426      i.SuperProp = "overrided superprop";
1427
1428      string json = JsonConvert.SerializeObject(i);
1429      Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", json);
1430
1431      SubKlass ii = JsonConvert.DeserializeObject<SubKlass>(json);
1432
1433      string newJson = JsonConvert.SerializeObject(ii)

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