PageRenderTime 63ms CodeModel.GetById 5ms app.highlight 39ms RepoModel.GetById 1ms app.codeStats 1ms

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

https://github.com/buddydvd/Newtonsoft.Json
C# | 6113 lines | 5379 code | 607 blank | 127 comment | 64 complexity | 6af5dbc4728ea9c755b24f51ba98c337 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    [ExpectedException(typeof (JsonSerializationException)
 395#if !NETFX_CORE
 396      , ExpectedMessage = @"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name."
 397#endif
 398      )]
 399    public void BadJsonPropertyClassSerialize()
 400    {
 401      JsonConvert.SerializeObject(new BadJsonPropertyClass());
 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    [ExpectedException(typeof (JsonReaderException)
 473#if !NETFX_CORE
 474      , ExpectedMessage = @"Bad JSON escape sequence: \j. Line 1, position 7."
 475#endif
 476      )]
 477    public void InvalidBackslash()
 478    {
 479      string json = @"[""vvv\jvvv""]";
 480
 481      JsonConvert.DeserializeObject<List<string>>(json);
 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
 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
 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 SerializerShouldUseMemberConverterOverArgumentConverter()
 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 JavaScriptDateTimeConverter());
 930      Assert.AreEqual(@"{""DefaultConverter"":new Date(0),""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
 931
 932      MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json, new JavaScriptDateTimeConverter());
 933
 934      Assert.AreEqual(testDate, m2.DefaultConverter);
 935      Assert.AreEqual(testDate, m2.MemberConverter);
 936    }
 937
 938    [Test]
 939    public void ConverterAttributeExample()
 940    {
 941      DateTime date = Convert.ToDateTime("1970-01-01T00:00:00Z").ToUniversalTime();
 942
 943      MemberConverterClass c = new MemberConverterClass
 944        {
 945          DefaultConverter = date,
 946          MemberConverter = date
 947        };
 948
 949      string json = JsonConvert.SerializeObject(c, Formatting.Indented);
 950
 951      Console.WriteLine(json);
 952      //{
 953      //  "DefaultConverter": "\/Date(0)\/",
 954      //  "MemberConverter": "1970-01-01T00:00:00Z"
 955      //}
 956    }
 957
 958    [Test]
 959    public void SerializerShouldUseMemberConverterOverClassAndArgumentConverter()
 960    {
 961      ClassAndMemberConverterClass c1 = new ClassAndMemberConverterClass();
 962      c1.DefaultConverter = new ConverterPrecedenceClass("DefaultConverterValue");
 963      c1.MemberConverter = new ConverterPrecedenceClass("MemberConverterValue");
 964
 965      string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
 966      Assert.AreEqual(@"{""DefaultConverter"":[""Class"",""DefaultConverterValue""],""MemberConverter"":[""Member"",""MemberConverterValue""]}", json);
 967
 968      ClassAndMemberConverterClass c2 = JsonConvert.DeserializeObject<ClassAndMemberConverterClass>(json, new ArgumentConverterPrecedenceClassConverter());
 969
 970      Assert.AreEqual("DefaultConverterValue", c2.DefaultConverter.TestValue);
 971      Assert.AreEqual("MemberConverterValue", c2.MemberConverter.TestValue);
 972    }
 973
 974    [Test]
 975    public void IncompatibleJsonAttributeShouldThrow()
 976    {
 977      ExceptionAssert.Throws<JsonSerializationException>(
 978        "JsonConverter IsoDateTimeConverter on Newtonsoft.Json.Tests.TestObjects.IncompatibleJsonAttributeClass is not compatible with member type IncompatibleJsonAttributeClass.",
 979        () =>
 980        {
 981          IncompatibleJsonAttributeClass c = new IncompatibleJsonAttributeClass();
 982          JsonConvert.SerializeObject(c);
 983        });
 984    }
 985
 986    [Test]
 987    public void GenericAbstractProperty()
 988    {
 989      string json = JsonConvert.SerializeObject(new GenericImpl());
 990      Assert.AreEqual(@"{""Id"":0}", json);
 991    }
 992
 993    [Test]
 994    public void DeserializeNullable()
 995    {
 996      string json;
 997
 998      json = JsonConvert.SerializeObject((int?) null);
 999      Assert.AreEqual("null", json);
1000
1001      json = JsonConvert.SerializeObject((int?) 1);
1002      Assert.AreEqual("1", json);
1003    }
1004
1005    [Test]
1006    public void SerializeJsonRaw()
1007    {
1008      PersonRaw personRaw = new PersonRaw
1009        {
1010          FirstName = "FirstNameValue",
1011          RawContent = new JRaw("[1,2,3,4,5]"),
1012          LastName = "LastNameValue"
1013        };
1014
1015      string json;
1016
1017      json = JsonConvert.SerializeObject(personRaw);
1018      Assert.AreEqual(@"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}", json);
1019    }
1020
1021    [Test]
1022    public void DeserializeJsonRaw()
1023    {
1024      string json = @"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}";
1025
1026      PersonRaw personRaw = JsonConvert.DeserializeObject<PersonRaw>(json);
1027
1028      Assert.AreEqual("FirstNameValue", personRaw.FirstName);
1029      Assert.AreEqual("[1,2,3,4,5]", personRaw.RawContent.ToString());
1030      Assert.AreEqual("LastNameValue", personRaw.LastName);
1031    }
1032
1033
1034    [Test]
1035    public void DeserializeNullableMember()
1036    {
1037      UserNullable userNullablle = new UserNullable
1038        {
1039          Id = new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"),
1040          FName = "FirstValue",
1041          LName = "LastValue",
1042          RoleId = 5,
1043          NullableRoleId = 6,
1044          NullRoleId = null,
1045          Active = true
1046        };
1047
1048      string json = JsonConvert.SerializeObject(userNullablle);
1049
1050      Assert.AreEqual(@"{""Id"":""ad6205e8-0df4-465d-aea6-8ba18e93a7e7"",""FName"":""FirstValue"",""LName"":""LastValue"",""RoleId"":5,""NullableRoleId"":6,""NullRoleId"":null,""Active"":true}", json);
1051
1052      UserNullable userNullablleDeserialized = JsonConvert.DeserializeObject<UserNullable>(json);
1053
1054      Assert.AreEqual(new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"), userNullablleDeserialized.Id);
1055      Assert.AreEqual("FirstValue", userNullablleDeserialized.FName);
1056      Assert.AreEqual("LastValue", userNullablleDeserialized.LName);
1057      Assert.AreEqual(5, userNullablleDeserialized.RoleId);
1058      Assert.AreEqual(6, userNullablleDeserialized.NullableRoleId);
1059      Assert.AreEqual(null, userNullablleDeserialized.NullRoleId);
1060      Assert.AreEqual(true, userNullablleDeserialized.Active);
1061    }
1062
1063    [Test]
1064    public void DeserializeInt64ToNullableDouble()
1065    {
1066      string json = @"{""Height"":1}";
1067
1068      DoubleClass c = JsonConvert.DeserializeObject<DoubleClass>(json);
1069      Assert.AreEqual(1, c.Height);
1070    }
1071
1072    [Test]
1073    public void SerializeTypeProperty()
1074    {
1075      string boolRef = typeof (bool).AssemblyQualifiedName;
1076      TypeClass typeClass = new TypeClass {TypeProperty = typeof (bool)};
1077
1078      string json = JsonConvert.SerializeObject(typeClass);
1079      Assert.AreEqual(@"{""TypeProperty"":""" + boolRef + @"""}", json);
1080
1081      TypeClass typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
1082      Assert.AreEqual(typeof (bool), typeClass2.TypeProperty);
1083
1084      string jsonSerializerTestRef = typeof (JsonSerializerTest).AssemblyQualifiedName;
1085      typeClass = new TypeClass {TypeProperty = typeof (JsonSerializerTest)};
1086
1087      json = JsonConvert.SerializeObject(typeClass);
1088      Assert.AreEqual(@"{""TypeProperty"":""" + jsonSerializerTestRef + @"""}", json);
1089
1090      typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
1091      Assert.AreEqual(typeof (JsonSerializerTest), typeClass2.TypeProperty);
1092    }
1093
1094    [Test]
1095    public void RequiredMembersClass()
1096    {
1097      RequiredMembersClass c = new RequiredMembersClass()
1098        {
1099          BirthDate = new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc),
1100          FirstName = "Bob",
1101          LastName = "Smith",
1102          MiddleName = "Cosmo"
1103        };
1104
1105      string json = JsonConvert.SerializeObject(c, Formatting.Indented);
1106
1107      Assert.AreEqual(@"{
1108  ""FirstName"": ""Bob"",
1109  ""MiddleName"": ""Cosmo"",
1110  ""LastName"": ""Smith"",
1111  ""BirthDate"": ""2000-12-20T10:55:55Z""
1112}", json);
1113
1114      RequiredMembersClass c2 = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
1115
1116      Assert.AreEqual("Bob", c2.FirstName);
1117      Assert.AreEqual(new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc), c2.BirthDate);
1118    }
1119
1120    [Test]
1121    public void DeserializeRequiredMembersClassWithNullValues()
1122    {
1123      string json = @"{
1124  ""FirstName"": ""I can't be null bro!"",
1125  ""MiddleName"": null,
1126  ""LastName"": null,
1127  ""BirthDate"": ""\/Date(977309755000)\/""
1128}";
1129
1130      RequiredMembersClass c = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
1131
1132      Assert.AreEqual("I can't be null bro!", c.FirstName);
1133      Assert.AreEqual(null, c.MiddleName);
1134      Assert.AreEqual(null, c.LastName);
1135    }
1136
1137    [Test]
1138    public void DeserializeRequiredMembersClassNullRequiredValueProperty()
1139    {
1140      ExceptionAssert.Throws<JsonSerializationException>("Required property 'FirstName' expects a value but got null. Line 6, position 2.",
1141        () =>
1142        {
1143          string json = @"{
1144  ""FirstName"": null,
1145  ""MiddleName"": null,
1146  ""LastName"": null,
1147  ""BirthDate"": ""\/Date(977309755000)\/""
1148}";
1149
1150          JsonConvert.DeserializeObject<RequiredMembersClass>(json);
1151        });
1152    }
1153
1154    [Test]
1155    public void SerializeRequiredMembersClassNullRequiredValueProperty()
1156    {
1157      ExceptionAssert.Throws<JsonSerializationException>("Cannot write a null value for property 'FirstName'. Property requires a value.",
1158      () =>
1159      {
1160        RequiredMembersClass requiredMembersClass = new RequiredMembersClass
1161        {
1162          FirstName = null,
1163          BirthDate = new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc),
1164          LastName = null,
1165          MiddleName = null
1166        };
1167
1168        string json = JsonConvert.SerializeObject(requiredMembersClass);
1169        Console.WriteLine(json);
1170      });
1171    }
1172
1173    [Test]
1174    public void RequiredMembersClassMissingRequiredProperty()
1175    {
1176      ExceptionAssert.Throws<JsonSerializationException>("Required property 'LastName' not found in JSON. Line 3, position 2.",
1177      () =>
1178      {
1179        string json = @"{
1180  ""FirstName"": ""Bob""
1181}";
1182
1183        JsonConvert.DeserializeObject<RequiredMembersClass>(json);
1184      }); 
1185    }
1186
1187    [Test]
1188    public void SerializeJaggedArray()
1189    {
1190      JaggedArray aa = new JaggedArray();
1191      aa.Before = "Before!";
1192      aa.After = "After!";
1193      aa.Coordinates = new[] {new[] {1, 1}, new[] {1, 2}, new[] {2, 1}, new[] {2, 2}};
1194
1195      string json = JsonConvert.SerializeObject(aa);
1196
1197      Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}", json);
1198    }
1199
1200    [Test]
1201    public void DeserializeJaggedArray()
1202    {
1203      string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}";
1204
1205      JaggedArray aa = JsonConvert.DeserializeObject<JaggedArray>(json);
1206
1207      Assert.AreEqual("Before!", aa.Before);
1208      Assert.AreEqual("After!", aa.After);
1209      Assert.AreEqual(4, aa.Coordinates.Length);
1210      Assert.AreEqual(2, aa.Coordinates[0].Length);
1211      Assert.AreEqual(1, aa.Coordinates[0][0]);
1212      Assert.AreEqual(2, aa.Coordinates[1][1]);
1213
1214      string after = JsonConvert.SerializeObject(aa);
1215
1216      Assert.AreEqual(json, after);
1217    }
1218
1219    [Test]
1220    public void DeserializeGoogleGeoCode()
1221    {
1222      string json = @"{
1223  ""name"": ""1600 Amphitheatre Parkway, Mountain View, CA, USA"",
1224  ""Status"": {
1225    ""code"": 200,
1226    ""request"": ""geocode""
1227  },
1228  ""Placemark"": [
1229    {
1230      ""address"": ""1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"",
1231      ""AddressDetails"": {
1232        ""Country"": {
1233          ""CountryNameCode"": ""US"",
1234          ""AdministrativeArea"": {
1235            ""AdministrativeAreaName"": ""CA"",
1236            ""SubAdministrativeArea"": {
1237              ""SubAdministrativeAreaName"": ""Santa Clara"",
1238              ""Locality"": {
1239                ""LocalityName"": ""Mountain View"",
1240                ""Thoroughfare"": {
1241                  ""ThoroughfareName"": ""1600 Amphitheatre Pkwy""
1242                },
1243                ""PostalCode"": {
1244                  ""PostalCodeNumber"": ""94043""
1245                }
1246              }
1247            }
1248          }
1249        },
1250        ""Accuracy"": 8
1251      },
1252      ""Point"": {
1253        ""coordinates"": [-122.083739, 37.423021, 0]
1254      }
1255    }
1256  ]
1257}";
1258
1259      GoogleMapGeocoderStructure jsonGoogleMapGeocoder = JsonConvert.DeserializeObject<GoogleMapGeocoderStructure>(json);
1260    }
1261
1262    [Test]
1263    [ExpectedException(typeof (JsonSerializationException)
1264#if !NETFX_CORE
1265      , ExpectedMessage = @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantated. Line 1, position 14."
1266#endif
1267      )]
1268    public void DeserializeInterfaceProperty()
1269    {
1270      InterfacePropertyTestClass testClass = new InterfacePropertyTestClass();
1271      testClass.co = new Co();
1272      String strFromTest = JsonConvert.SerializeObject(testClass);
1273      InterfacePropertyTestClass testFromDe = (InterfacePropertyTestClass) JsonConvert.DeserializeObject(strFromTest, typeof (InterfacePropertyTestClass));
1274    }
1275
1276    private Person GetPerson()
1277    {
1278      Person person = new Person
1279        {
1280          Name = "Mike Manager",
1281          BirthDate = new DateTime(1983, 8, 3, 0, 0, 0, DateTimeKind.Utc),
1282          Department = "IT",
1283          LastModified = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc)
1284        };
1285      return person;
1286    }
1287
1288    [Test]
1289    public void WriteJsonDates()
1290    {
1291      LogEntry entry = new LogEntry
1292        {
1293          LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
1294          Details = "Application started."
1295        };
1296
1297      string defaultJson = JsonConvert.SerializeObject(entry);
1298      // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}
1299
1300      string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
1301      // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00.0000000Z"}
1302
1303      string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
1304      // {"Details":"Application started.","LogDate":new Date(1234656000000)}
1305
1306      Console.WriteLine(defaultJson);
1307      Console.WriteLine(isoJson);
1308      Console.WriteLine(javascriptJson);
1309    }
1310
1311    public void GenericListAndDictionaryInterfaceProperties()
1312    {
1313      GenericListAndDictionaryInterfaceProperties o = new GenericListAndDictionaryInterfaceProperties();
1314      o.IDictionaryProperty = new Dictionary<string, int>
1315        {
1316          {"one", 1},
1317          {"two", 2},
1318          {"three", 3}
1319        };
1320      o.IListProperty = new List<int>
1321        {
1322          1, 2, 3
1323        };
1324      o.IEnumerableProperty = new List<int>
1325        {
1326          4, 5, 6
1327        };
1328
1329      string json = JsonConvert.SerializeObject(o, Formatting.Indented);
1330
1331      Assert.AreEqual(@"{
1332  ""IEnumerableProperty"": [
1333    4,
1334    5,
1335    6
1336  ],
1337  ""IListProperty"": [
1338    1,
1339    2,
1340    3
1341  ],
1342  ""IDictionaryProperty"": {
1343    ""one"": 1,
1344    ""two"": 2,
1345    ""three"": 3
1346  }
1347}", json);
1348
1349      GenericListAndDictionaryInterfaceProperties deserializedObject = JsonConvert.DeserializeObject<GenericListAndDictionaryInterfaceProperties>(json);
1350      Assert.IsNotNull(deserializedObject);
1351
1352      CollectionAssert.AreEqual(o.IListProperty.ToArray(), deserializedObject.IListProperty.ToArray());
1353      CollectionAssert.AreEqual(o.IEnumerableProperty.ToArray(), deserializedObject.IEnumerableProperty.ToArray());
1354      CollectionAssert.AreEqual(o.IDictionaryProperty.ToArray(), deserializedObject.IDictionaryProperty.ToArray());
1355    }
1356
1357    [Test]
1358    public void DeserializeBestMatchPropertyCase()
1359    {
1360      string json = @"{
1361  ""firstName"": ""firstName"",
1362  ""FirstName"": ""FirstName"",
1363  ""LastName"": ""LastName"",
1364  ""lastName"": ""lastName"",
1365}";
1366
1367      PropertyCase o = JsonConvert.DeserializeObject<PropertyCase>(json);
1368      Assert.IsNotNull(o);
1369
1370      Assert.AreEqual("firstName", o.firstName);
1371      Assert.AreEqual("FirstName", o.FirstName);
1372      Assert.AreEqual("LastName", o.LastName);
1373      Assert.AreEqual("lastName", o.lastName);
1374    }
1375
1376    [Test]
1377    public void DeserializePropertiesOnToNonDefaultConstructor()
1378    {
1379      SubKlass i = new SubKlass("my subprop");
1380      i.SuperProp = "overrided superprop";
1381
1382      string json = JsonConvert.SerializeObject(i);
1383      Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", json);
1384
1385      SubKlass ii = JsonConvert.DeserializeObject<SubKlass>(json);
1386
1387      string newJson = JsonConvert.SerializeObject(ii);
1388      Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", newJson);
1389    }
1390
1391    [Test]
1392    public void SerializeJsonPropertyWithHandlingValues()
1393    {
1394      JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
1395      o.DefaultValueHandlingIgnoreProperty = "Default!";
1396      o.DefaultValueHandlingIncludeProperty = "Default!";
1397      o.DefaultValueHandlingPopulateProperty = "Default!";
1398      o.DefaultValueHandlingIgnoreAndPopulateProperty = "Default!";
1399
1400      string json = JsonConvert.SerializeObject(o, Formatting.Indented);
1401
1402      Assert.AreEqual(@"{
1403  ""DefaultValueHandlingIncludeProperty"": ""Default!"",
1404  ""DefaultValueHandlingPopulateProperty"": ""Default!"",
1405  ""NullValueHandlingIncludeProperty"": null,
1406  ""ReferenceLoopHandlingErrorProperty"": null,
1407  ""ReferenceLoopHandlingIgnoreProperty"": null,
1408  ""ReferenceLoopHandlingSerializeProperty"": null
1409}", json);
1410
1411      json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});
1412
1413      Assert.AreEqual(@"{
1414  ""DefaultValueHandlingIncludeProperty"": ""Default!"",
1415  ""DefaultValueHandlingPopulateProperty"": ""Default!"",
1416  ""NullValueHandlingIncludeProperty"": null
1417}", json);
1418    }
1419
1420    [Test]
1421    public void DeserializeJsonPropertyWithHandlingValues()
1422    {
1423      string json = "{}";
1424
1425      JsonPropertyWithHandlingValues o = JsonConvert.DeserializeObject<JsonPropertyWithHandlingValues>(json);
1426      Assert.AreEqual("Default!", o.DefaultValueHandlingIgnoreAndPopulateProperty);
1427      Assert.AreEqual("Default!", o.DefaultValueHandlingPopulateProperty);
1428      Assert.AreEqual(null, o.DefaultValueHandlingIgnoreProperty);
1429      Assert.AreEqual(null, o.DefaultValueHandlingIncludeProperty);
1430    }
1431
1432    [Test]
1433    [ExpectedException(typeof (JsonSerializationException))]
1434    pu

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