PageRenderTime 12ms CodeModel.GetById 6ms app.highlight 70ms RepoModel.GetById 2ms app.codeStats 1ms

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

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

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