2
// Copyright (c) 2007 James Newton-King
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
13
// The above copyright notice and this permission notice shall be
14
// included in all copies or substantial portions of the Software.
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.
27
#if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE)
28
using System.Collections.Concurrent;
30
using System.Collections.Generic;
31
#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE
32
using System.ComponentModel.DataAnnotations;
33
using System.Configuration;
34
using System.Runtime.CompilerServices;
35
using System.Runtime.Serialization.Formatters;
36
using System.Threading;
37
using System.Web.Script.Serialization;
41
using NUnit.Framework;
43
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
44
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
45
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
47
using Newtonsoft.Json;
49
using System.Collections;
51
using System.Xml.Serialization;
52
using System.Collections.ObjectModel;
53
using Newtonsoft.Json.Bson;
54
using Newtonsoft.Json.Linq;
55
using Newtonsoft.Json.Converters;
56
#if !PocketPC && !NET20 && !WINDOWS_PHONE
57
using System.Runtime.Serialization.Json;
59
using Newtonsoft.Json.Serialization;
60
using Newtonsoft.Json.Tests.Linq;
61
using Newtonsoft.Json.Tests.TestObjects;
62
using System.Runtime.Serialization;
63
using System.Globalization;
64
using Newtonsoft.Json.Utilities;
65
using System.Reflection;
66
#if !NET20 && !SILVERLIGHT
67
using System.Xml.Linq;
68
using System.Text.RegularExpressions;
69
using System.Collections.Specialized;
70
using System.Linq.Expressions;
72
#if !(NET35 || NET20 || WINDOWS_PHONE)
74
using System.ComponentModel;
77
using Newtonsoft.Json.Utilities.LinqBridge;
81
#if !(SILVERLIGHT || NETFX_CORE)
85
namespace Newtonsoft.Json.Tests.Serialization
88
public class JsonSerializerTest : TestFixtureBase
91
public void PersonTypedObjectDeserialization()
93
Store store = new Store();
95
string jsonText = JsonConvert.SerializeObject(store);
97
Store deserializedStore = (Store)JsonConvert.DeserializeObject(jsonText, typeof(Store));
99
Assert.AreEqual(store.Establised, deserializedStore.Establised);
100
Assert.AreEqual(store.product.Count, deserializedStore.product.Count);
102
Console.WriteLine(jsonText);
106
public void TypedObjectDeserialization()
108
Product product = new Product();
110
product.Name = "Apple";
111
product.ExpiryDate = new DateTime(2008, 12, 28);
112
product.Price = 3.99M;
113
product.Sizes = new string[] { "Small", "Medium", "Large" };
115
string output = JsonConvert.SerializeObject(product);
118
// "ExpiryDate": "\/Date(1230375600000+1300)\/",
127
Product deserializedProduct = (Product)JsonConvert.DeserializeObject(output, typeof(Product));
129
Assert.AreEqual("Apple", deserializedProduct.Name);
130
Assert.AreEqual(new DateTime(2008, 12, 28), deserializedProduct.ExpiryDate);
131
Assert.AreEqual(3.99m, deserializedProduct.Price);
132
Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
133
Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
134
Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
138
//public void Advanced()
140
// Product product = new Product();
141
// product.ExpiryDate = new DateTime(2008, 12, 28);
143
// JsonSerializer serializer = new JsonSerializer();
144
// serializer.Converters.Add(new JavaScriptDateTimeConverter());
145
// serializer.NullValueHandling = NullValueHandling.Ignore;
147
// using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
148
// using (JsonWriter writer = new JsonTextWriter(sw))
150
// serializer.Serialize(writer, product);
151
// // {"ExpiryDate":new Date(1230375600000),"Price":0}
156
public void JsonConvertSerializer()
158
string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
160
Product p = JsonConvert.DeserializeObject(value, typeof(Product)) as Product;
162
Assert.AreEqual("Orange", p.Name);
163
Assert.AreEqual(new DateTime(2010, 1, 24, 12, 0, 0), p.ExpiryDate);
164
Assert.AreEqual(3.99m, p.Price);
168
public void DeserializeJavaScriptDate()
170
DateTime dateValue = new DateTime(2010, 3, 30);
171
Dictionary<string, object> testDictionary = new Dictionary<string, object>();
172
testDictionary["date"] = dateValue;
174
string jsonText = JsonConvert.SerializeObject(testDictionary);
176
#if !PocketPC && !NET20 && !WINDOWS_PHONE
177
MemoryStream ms = new MemoryStream();
178
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<string, object>));
179
serializer.WriteObject(ms, testDictionary);
181
byte[] data = ms.ToArray();
182
string output = Encoding.UTF8.GetString(data, 0, data.Length);
185
Dictionary<string, object> deserializedDictionary = (Dictionary<string, object>)JsonConvert.DeserializeObject(jsonText, typeof(Dictionary<string, object>));
186
DateTime deserializedDate = (DateTime)deserializedDictionary["date"];
188
Assert.AreEqual(dateValue, deserializedDate);
192
public void TestMethodExecutorObject()
194
MethodExecutorObject executorObject = new MethodExecutorObject();
195
executorObject.serverClassName = "BanSubs";
196
executorObject.serverMethodParams = new object[] { "21321546", "101", "1236", "D:\\1.txt" };
197
executorObject.clientGetResultFunction = "ClientBanSubsCB";
199
string output = JsonConvert.SerializeObject(executorObject);
201
MethodExecutorObject executorObject2 = JsonConvert.DeserializeObject(output, typeof(MethodExecutorObject)) as MethodExecutorObject;
203
Assert.AreNotSame(executorObject, executorObject2);
204
Assert.AreEqual(executorObject2.serverClassName, "BanSubs");
205
Assert.AreEqual(executorObject2.serverMethodParams.Length, 4);
206
CustomAssert.Contains(executorObject2.serverMethodParams, "101");
207
Assert.AreEqual(executorObject2.clientGetResultFunction, "ClientBanSubsCB");
210
#if !SILVERLIGHT && !NETFX_CORE
212
public void HashtableDeserialization()
214
string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
216
Hashtable p = JsonConvert.DeserializeObject(value, typeof(Hashtable)) as Hashtable;
218
Assert.AreEqual("Orange", p["Name"].ToString());
222
public void TypedHashtableDeserialization()
224
string value = @"{""Name"":""Orange"", ""Hash"":{""ExpiryDate"":""01/24/2010 12:00:00"",""UntypedArray"":[""01/24/2010 12:00:00""]}}";
226
TypedSubHashtable p = JsonConvert.DeserializeObject(value, typeof(TypedSubHashtable)) as TypedSubHashtable;
228
Assert.AreEqual("01/24/2010 12:00:00", p.Hash["ExpiryDate"].ToString());
230
""01/24/2010 12:00:00""
231
]", p.Hash["UntypedArray"].ToString());
236
public void SerializeDeserializeGetOnlyProperty()
238
string value = JsonConvert.SerializeObject(new GetOnlyPropertyClass());
240
GetOnlyPropertyClass c = JsonConvert.DeserializeObject<GetOnlyPropertyClass>(value);
242
Assert.AreEqual(c.Field, "Field");
243
Assert.AreEqual(c.GetOnlyProperty, "GetOnlyProperty");
247
public void SerializeDeserializeSetOnlyProperty()
249
string value = JsonConvert.SerializeObject(new SetOnlyPropertyClass());
251
SetOnlyPropertyClass c = JsonConvert.DeserializeObject<SetOnlyPropertyClass>(value);
253
Assert.AreEqual(c.Field, "Field");
257
public void JsonIgnoreAttributeTest()
259
string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeTestClass());
261
Assert.AreEqual(@"{""Field"":0,""Property"":21}", json);
263
JsonIgnoreAttributeTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeTestClass>(@"{""Field"":99,""Property"":-1,""IgnoredField"":-1,""IgnoredObject"":[1,2,3,4,5]}");
265
Assert.AreEqual(0, c.IgnoredField);
266
Assert.AreEqual(99, c.Field);
270
public void GoogleSearchAPI()
276
GsearchResultClass:""GwebSearch"",
277
unescapedUrl : ""http://www.google.com/"",
278
url : ""http://www.google.com/"",
279
visibleUrl : ""www.google.com"",
281
""http://www.google.com/search?q=cache:zhool8dxBV4J:www.google.com"",
283
titleNoFormatting : ""Google"",
284
content : ""Enables users to search the Web, Usenet, and
285
images. Features include PageRank, caching and translation of
286
results, and an option to find similar pages.""
289
GsearchResultClass:""GwebSearch"",
290
unescapedUrl : ""http://news.google.com/"",
291
url : ""http://news.google.com/"",
292
visibleUrl : ""news.google.com"",
294
""http://www.google.com/search?q=cache:Va_XShOz_twJ:news.google.com"",
295
title : ""Google News"",
296
titleNoFormatting : ""Google News"",
297
content : ""Aggregated headlines and a search engine of many of the world's news sources.""
301
GsearchResultClass:""GwebSearch"",
302
unescapedUrl : ""http://groups.google.com/"",
303
url : ""http://groups.google.com/"",
304
visibleUrl : ""groups.google.com"",
306
""http://www.google.com/search?q=cache:x2uPD3hfkn0J:groups.google.com"",
307
title : ""Google Groups"",
308
titleNoFormatting : ""Google Groups"",
309
content : ""Enables users to search and browse the Usenet
310
archives which consist of over 700 million messages, and post new
315
GsearchResultClass:""GwebSearch"",
316
unescapedUrl : ""http://maps.google.com/"",
317
url : ""http://maps.google.com/"",
318
visibleUrl : ""maps.google.com"",
320
""http://www.google.com/search?q=cache:dkf5u2twBXIJ:maps.google.com"",
321
title : ""Google Maps"",
322
titleNoFormatting : ""Google Maps"",
323
content : ""Provides directions, interactive maps, and
324
satellite/aerial imagery of the United States. Can also search by
325
keyword such as type of business.""
332
GsearchResultClass:""GwebSearch.ad"",
333
title : ""Gartner Symposium/ITxpo"",
334
content1 : ""Meet brilliant Gartner IT analysts"",
335
content2 : ""20-23 May 2007- Barcelona, Spain"",
337
""http://www.google.com/url?sa=L&ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB&num=1&q=http://www.gartner.com/it/sym/2007/spr8/spr8.jsp%3Fsrc%3D_spain_07_%26WT.srch%3D1&usg=__CxRH06E4Xvm9Muq13S4MgMtnziY="",
340
""http://www.google.com/uds/css/ad-indicator-on.gif?ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB"",
343
""http://www.google.com/url?sa=L&ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB&num=1&q=http://www.gartner.com/it/sym/2007/spr8/spr8.jsp%3Fsrc%3D_spain_07_%26WT.srch%3D1&usg=__CxRH06E4Xvm9Muq13S4MgMtnziY="",
345
visibleUrl : ""www.gartner.com""
350
object o = JsonConvert.DeserializeObject(json);
351
string s = string.Empty;
356
public void TorrentDeserializeTest()
358
string jsonText = @"{
364
[""192D99A5C943555CB7F00A852821CF6D6DB3008A"",201,""filename.avi"",178311826,1000,178311826,72815250,408,1603,7,121430,""NameOfLabelPrevioslyDefined"",3,6,0,8,128954,-1,0],
366
""torrentc"": ""1816000723""
369
JObject o = (JObject)JsonConvert.DeserializeObject(jsonText);
370
Assert.AreEqual(4, o.Children().Count());
372
JToken torrentsArray = (JToken)o["torrents"];
373
JToken nestedTorrentsArray = (JToken)torrentsArray[0];
374
Assert.AreEqual(nestedTorrentsArray.Children().Count(), 19);
378
public void JsonPropertyClassSerialize()
380
JsonPropertyClass test = new JsonPropertyClass();
381
test.Pie = "Delicious";
382
test.SweetCakesCount = int.MaxValue;
384
string jsonText = JsonConvert.SerializeObject(test);
386
Assert.AreEqual(@"{""pie"":""Delicious"",""pie1"":""PieChart!"",""sweet_cakes_count"":2147483647}", jsonText);
388
JsonPropertyClass test2 = JsonConvert.DeserializeObject<JsonPropertyClass>(jsonText);
390
Assert.AreEqual(test.Pie, test2.Pie);
391
Assert.AreEqual(test.SweetCakesCount, test2.SweetCakesCount);
395
public void BadJsonPropertyClassSerialize()
397
ExceptionAssert.Throws<JsonSerializationException>(
398
@"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name.",
401
JsonConvert.SerializeObject(new BadJsonPropertyClass());
406
public void InheritedListSerialize()
408
Article a1 = new Article("a1");
409
Article a2 = new Article("a2");
411
ArticleCollection articles1 = new ArticleCollection();
415
string jsonText = JsonConvert.SerializeObject(articles1);
417
ArticleCollection articles2 = JsonConvert.DeserializeObject<ArticleCollection>(jsonText);
419
Assert.AreEqual(articles1.Count, articles2.Count);
420
Assert.AreEqual(articles1[0].Name, articles2[0].Name);
424
public void ReadOnlyCollectionSerialize()
426
ReadOnlyCollection<int> r1 = new ReadOnlyCollection<int>(new int[] { 0, 1, 2, 3, 4 });
428
string jsonText = JsonConvert.SerializeObject(r1);
430
ReadOnlyCollection<int> r2 = JsonConvert.DeserializeObject<ReadOnlyCollection<int>>(jsonText);
432
CollectionAssert.AreEqual(r1, r2);
435
#if !PocketPC && !NET20 && !WINDOWS_PHONE
437
public void Unicode()
439
string json = @"[""PRE\u003cPOST""]";
441
DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<string>));
442
List<string> dataContractResult = (List<string>)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
444
List<string> jsonNetResult = JsonConvert.DeserializeObject<List<string>>(json);
446
Assert.AreEqual(1, jsonNetResult.Count);
447
Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
451
public void BackslashEqivilence()
453
string json = @"[""vvv\/vvv\tvvv\""vvv\bvvv\nvvv\rvvv\\vvv\fvvv""]";
455
#if !SILVERLIGHT && !NETFX_CORE
456
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
457
List<string> javaScriptSerializerResult = javaScriptSerializer.Deserialize<List<string>>(json);
460
DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<string>));
461
List<string> dataContractResult = (List<string>)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
463
List<string> jsonNetResult = JsonConvert.DeserializeObject<List<string>>(json);
465
Assert.AreEqual(1, jsonNetResult.Count);
466
Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
467
#if !SILVERLIGHT && !NETFX_CORE
468
Assert.AreEqual(javaScriptSerializerResult[0], jsonNetResult[0]);
473
public void InvalidBackslash()
475
string json = @"[""vvv\jvvv""]";
477
ExceptionAssert.Throws<JsonReaderException>(
478
@"Bad JSON escape sequence: \j. Path '', line 1, position 7.",
481
JsonConvert.DeserializeObject<List<string>>(json);
486
public void DateTimeTest()
488
List<DateTime> testDates = new List<DateTime>
490
new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Local),
491
new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
492
new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc),
493
new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local),
494
new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
495
new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc),
498
MemoryStream ms = new MemoryStream();
499
DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<DateTime>));
500
s.WriteObject(ms, testDates);
501
ms.Seek(0, SeekOrigin.Begin);
502
StreamReader sr = new StreamReader(ms);
504
string expected = sr.ReadToEnd();
506
string result = JsonConvert.SerializeObject(testDates, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
507
Assert.AreEqual(expected, result);
511
public void DateTimeOffsetIso()
513
List<DateTimeOffset> testDates = new List<DateTimeOffset>
515
new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
516
new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
517
new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
518
new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
521
string result = JsonConvert.SerializeObject(testDates);
522
Assert.AreEqual(@"[""0100-01-01T01:01:01+00:00"",""2000-01-01T01:01:01+00:00"",""2000-01-01T01:01:01+13:00"",""2000-01-01T01:01:01-03:30""]", result);
526
public void DateTimeOffsetMsAjax()
528
List<DateTimeOffset> testDates = new List<DateTimeOffset>
530
new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
531
new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
532
new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
533
new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
536
string result = JsonConvert.SerializeObject(testDates, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
537
Assert.AreEqual(@"[""\/Date(-59011455539000+0000)\/"",""\/Date(946688461000+0000)\/"",""\/Date(946641661000+1300)\/"",""\/Date(946701061000-0330)\/""]", result);
542
public void NonStringKeyDictionary()
544
Dictionary<int, int> values = new Dictionary<int, int>();
546
values.Add(int.MinValue, int.MaxValue);
548
string json = JsonConvert.SerializeObject(values);
550
Assert.AreEqual(@"{""-5"":6,""-2147483648"":2147483647}", json);
552
Dictionary<int, int> newValues = JsonConvert.DeserializeObject<Dictionary<int, int>>(json);
554
CollectionAssert.AreEqual(values, newValues);
558
public void AnonymousObjectSerialization()
563
StringValue = "I am a string",
564
IntValue = int.MaxValue,
565
NestedAnonymous = new { NestedValue = byte.MaxValue },
566
NestedArray = new[] { 1, 2 },
567
Product = new Product() { Name = "TestProduct" }
570
string json = JsonConvert.SerializeObject(anonymous);
571
Assert.AreEqual(@"{""StringValue"":""I am a string"",""IntValue"":2147483647,""NestedAnonymous"":{""NestedValue"":255},""NestedArray"":[1,2],""Product"":{""Name"":""TestProduct"",""ExpiryDate"":""2000-01-01T00:00:00Z"",""Price"":0.0,""Sizes"":null}}", json);
573
anonymous = JsonConvert.DeserializeAnonymousType(json, anonymous);
574
Assert.AreEqual("I am a string", anonymous.StringValue);
575
Assert.AreEqual(int.MaxValue, anonymous.IntValue);
576
Assert.AreEqual(255, anonymous.NestedAnonymous.NestedValue);
577
Assert.AreEqual(2, anonymous.NestedArray.Length);
578
Assert.AreEqual(1, anonymous.NestedArray[0]);
579
Assert.AreEqual(2, anonymous.NestedArray[1]);
580
Assert.AreEqual("TestProduct", anonymous.Product.Name);
584
public void CustomCollectionSerialization()
586
ProductCollection collection = new ProductCollection()
588
new Product() {Name = "Test1"},
589
new Product() {Name = "Test2"},
590
new Product() {Name = "Test3"}
593
JsonSerializer jsonSerializer = new JsonSerializer();
594
jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
596
StringWriter sw = new StringWriter();
598
jsonSerializer.Serialize(sw, collection);
600
Assert.AreEqual(@"[{""Name"":""Test1"",""ExpiryDate"":""2000-01-01T00:00:00Z"",""Price"":0.0,""Sizes"":null},{""Name"":""Test2"",""ExpiryDate"":""2000-01-01T00:00:00Z"",""Price"":0.0,""Sizes"":null},{""Name"":""Test3"",""ExpiryDate"":""2000-01-01T00:00:00Z"",""Price"":0.0,""Sizes"":null}]",
601
sw.GetStringBuilder().ToString());
603
ProductCollection collectionNew = (ProductCollection)jsonSerializer.Deserialize(new JsonTextReader(new StringReader(sw.GetStringBuilder().ToString())), typeof(ProductCollection));
605
CollectionAssert.AreEqual(collection, collectionNew);
609
public void SerializeObject()
611
string json = JsonConvert.SerializeObject(new object());
612
Assert.AreEqual("{}", json);
616
public void SerializeNull()
618
string json = JsonConvert.SerializeObject(null);
619
Assert.AreEqual("null", json);
623
public void CanDeserializeIntArrayWhenNotFirstPropertyInJson()
625
string json = "{foo:'hello',bar:[1,2,3]}";
626
ClassWithArray wibble = JsonConvert.DeserializeObject<ClassWithArray>(json);
627
Assert.AreEqual("hello", wibble.Foo);
629
Assert.AreEqual(4, wibble.Bar.Count);
630
Assert.AreEqual(int.MaxValue, wibble.Bar[0]);
631
Assert.AreEqual(1, wibble.Bar[1]);
632
Assert.AreEqual(2, wibble.Bar[2]);
633
Assert.AreEqual(3, wibble.Bar[3]);
637
public void CanDeserializeIntArray_WhenArrayIsFirstPropertyInJson()
639
string json = "{bar:[1,2,3], foo:'hello'}";
640
ClassWithArray wibble = JsonConvert.DeserializeObject<ClassWithArray>(json);
641
Assert.AreEqual("hello", wibble.Foo);
643
Assert.AreEqual(4, wibble.Bar.Count);
644
Assert.AreEqual(int.MaxValue, wibble.Bar[0]);
645
Assert.AreEqual(1, wibble.Bar[1]);
646
Assert.AreEqual(2, wibble.Bar[2]);
647
Assert.AreEqual(3, wibble.Bar[3]);
651
public void ObjectCreationHandlingReplace()
653
string json = "{bar:[1,2,3], foo:'hello'}";
655
JsonSerializer s = new JsonSerializer();
656
s.ObjectCreationHandling = ObjectCreationHandling.Replace;
658
ClassWithArray wibble = (ClassWithArray)s.Deserialize(new StringReader(json), typeof(ClassWithArray));
660
Assert.AreEqual("hello", wibble.Foo);
662
Assert.AreEqual(1, wibble.Bar.Count);
666
public void CanDeserializeSerializedJson()
668
ClassWithArray wibble = new ClassWithArray();
669
wibble.Foo = "hello";
673
string json = JsonConvert.SerializeObject(wibble);
675
ClassWithArray wibbleOut = JsonConvert.DeserializeObject<ClassWithArray>(json);
676
Assert.AreEqual("hello", wibbleOut.Foo);
678
Assert.AreEqual(5, wibbleOut.Bar.Count);
679
Assert.AreEqual(int.MaxValue, wibbleOut.Bar[0]);
680
Assert.AreEqual(int.MaxValue, wibbleOut.Bar[1]);
681
Assert.AreEqual(1, wibbleOut.Bar[2]);
682
Assert.AreEqual(2, wibbleOut.Bar[3]);
683
Assert.AreEqual(3, wibbleOut.Bar[4]);
687
public void SerializeConverableObjects()
689
string json = JsonConvert.SerializeObject(new ConverableMembers(), Formatting.Indented);
691
string expected = null;
692
#if !(NETFX_CORE || PORTABLE)
694
""String"": ""string"",
695
""Int32"": 2147483647,
696
""UInt32"": 4294967295,
701
""Long"": 9223372036854775807,
702
""ULong"": 9223372036854775807,
703
""Double"": 1.7976931348623157E+308,
704
""Float"": 3.40282347E+38,
711
""String"": ""string"",
712
""Int32"": 2147483647,
713
""UInt32"": 4294967295,
718
""Long"": 9223372036854775807,
719
""ULong"": 9223372036854775807,
720
""Double"": 1.7976931348623157E+308,
721
""Float"": 3.40282347E+38,
727
Assert.AreEqual(expected, json);
729
ConverableMembers c = JsonConvert.DeserializeObject<ConverableMembers>(json);
730
Assert.AreEqual("string", c.String);
731
Assert.AreEqual(double.MaxValue, c.Double);
732
#if !(NETFX_CORE || PORTABLE)
733
Assert.AreEqual(DBNull.Value, c.DBNull);
738
public void SerializeStack()
740
Stack<object> s = new Stack<object>();
745
string json = JsonConvert.SerializeObject(s);
746
Assert.AreEqual("[3,2,1]", json);
750
public void GuidTest()
752
Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
754
string json = JsonConvert.SerializeObject(new ClassWithGuid { GuidField = guid });
755
Assert.AreEqual(@"{""GuidField"":""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""}", json);
757
ClassWithGuid c = JsonConvert.DeserializeObject<ClassWithGuid>(json);
758
Assert.AreEqual(guid, c.GuidField);
762
public void EnumTest()
764
string json = JsonConvert.SerializeObject(StringComparison.CurrentCultureIgnoreCase);
765
Assert.AreEqual(@"1", json);
767
StringComparison s = JsonConvert.DeserializeObject<StringComparison>(json);
768
Assert.AreEqual(StringComparison.CurrentCultureIgnoreCase, s);
771
public class ClassWithTimeSpan
773
public TimeSpan TimeSpanField;
777
public void TimeSpanTest()
779
TimeSpan ts = new TimeSpan(00, 23, 59, 1);
781
string json = JsonConvert.SerializeObject(new ClassWithTimeSpan { TimeSpanField = ts }, Formatting.Indented);
783
""TimeSpanField"": ""23:59:01""
786
ClassWithTimeSpan c = JsonConvert.DeserializeObject<ClassWithTimeSpan>(json);
787
Assert.AreEqual(ts, c.TimeSpanField);
791
public void JsonIgnoreAttributeOnClassTest()
793
string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeOnClassTestClass());
795
Assert.AreEqual(@"{""TheField"":0,""Property"":21}", json);
797
JsonIgnoreAttributeOnClassTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeOnClassTestClass>(@"{""TheField"":99,""Property"":-1,""IgnoredField"":-1}");
799
Assert.AreEqual(0, c.IgnoredField);
800
Assert.AreEqual(99, c.Field);
803
#if !SILVERLIGHT && !NETFX_CORE
805
public void SerializeArrayAsArrayList()
807
string jsonText = @"[3, ""somestring"",[1,2,3],{}]";
808
ArrayList o = JsonConvert.DeserializeObject<ArrayList>(jsonText);
810
Assert.AreEqual(4, o.Count);
811
Assert.AreEqual(3, ((JArray)o[2]).Count);
812
Assert.AreEqual(0, ((JObject)o[3]).Count);
817
public void SerializeMemberGenericList()
819
Name name = new Name("The Idiot in Next To Me");
821
PhoneNumber p1 = new PhoneNumber("555-1212");
822
PhoneNumber p2 = new PhoneNumber("444-1212");
824
name.pNumbers.Add(p1);
825
name.pNumbers.Add(p2);
827
string json = JsonConvert.SerializeObject(name, Formatting.Indented);
830
""personsName"": ""The Idiot in Next To Me"",
833
""phoneNumber"": ""555-1212""
836
""phoneNumber"": ""444-1212""
841
Name newName = JsonConvert.DeserializeObject<Name>(json);
843
Assert.AreEqual("The Idiot in Next To Me", newName.personsName);
845
// not passed in as part of the constructor but assigned to pNumbers property
846
Assert.AreEqual(2, newName.pNumbers.Count);
847
Assert.AreEqual("555-1212", newName.pNumbers[0].phoneNumber);
848
Assert.AreEqual("444-1212", newName.pNumbers[1].phoneNumber);
852
public void ConstructorCaseSensitivity()
854
ConstructorCaseSensitivityClass c = new ConstructorCaseSensitivityClass("param1", "Param1", "Param2");
856
string json = JsonConvert.SerializeObject(c);
858
ConstructorCaseSensitivityClass deserialized = JsonConvert.DeserializeObject<ConstructorCaseSensitivityClass>(json);
860
Assert.AreEqual("param1", deserialized.param1);
861
Assert.AreEqual("Param1", deserialized.Param1);
862
Assert.AreEqual("Param2", deserialized.Param2);
866
public void SerializerShouldUseClassConverter()
868
ConverterPrecedenceClass c1 = new ConverterPrecedenceClass("!Test!");
870
string json = JsonConvert.SerializeObject(c1);
871
Assert.AreEqual(@"[""Class"",""!Test!""]", json);
873
ConverterPrecedenceClass c2 = JsonConvert.DeserializeObject<ConverterPrecedenceClass>(json);
875
Assert.AreEqual("!Test!", c2.TestValue);
879
public void SerializerShouldUseClassConverterOverArgumentConverter()
881
ConverterPrecedenceClass c1 = new ConverterPrecedenceClass("!Test!");
883
string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
884
Assert.AreEqual(@"[""Class"",""!Test!""]", json);
886
ConverterPrecedenceClass c2 = JsonConvert.DeserializeObject<ConverterPrecedenceClass>(json, new ArgumentConverterPrecedenceClassConverter());
888
Assert.AreEqual("!Test!", c2.TestValue);
892
public void SerializerShouldUseMemberConverter_IsoDate()
894
DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
895
MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
897
string json = JsonConvert.SerializeObject(m1);
898
Assert.AreEqual(@"{""DefaultConverter"":""1970-01-01T00:00:00Z"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
900
MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
902
Assert.AreEqual(testDate, m2.DefaultConverter);
903
Assert.AreEqual(testDate, m2.MemberConverter);
907
public void SerializerShouldUseMemberConverter_MsDate()
909
DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
910
MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
912
string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
914
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
916
Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
918
MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
920
Assert.AreEqual(testDate, m2.DefaultConverter);
921
Assert.AreEqual(testDate, m2.MemberConverter);
925
public void SerializerShouldUseMemberConverter_MsDate_DateParseNone()
927
DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
928
MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
930
string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
932
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
934
Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
936
ExceptionAssert.Throws<JsonReaderException>(
937
"Could not convert string to DateTime: /Date(0)/. Path 'DefaultConverter', line 1, position 33.",
940
JsonConvert.DeserializeObject<MemberConverterClass>(json, new JsonSerializerSettings
942
DateParseHandling = DateParseHandling.None
948
public void SerializerShouldUseMemberConverter_IsoDate_DateParseNone()
950
DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
951
MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
953
string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
955
DateFormatHandling = DateFormatHandling.IsoDateFormat,
957
Assert.AreEqual(@"{""DefaultConverter"":""1970-01-01T00:00:00Z"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
959
MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
961
Assert.AreEqual(testDate, m2.DefaultConverter);
962
Assert.AreEqual(testDate, m2.MemberConverter);
966
public void SerializerShouldUseMemberConverterOverArgumentConverter()
968
DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
969
MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
971
string json = JsonConvert.SerializeObject(m1, new JavaScriptDateTimeConverter());
972
Assert.AreEqual(@"{""DefaultConverter"":new Date(0),""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
974
MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json, new JavaScriptDateTimeConverter());
976
Assert.AreEqual(testDate, m2.DefaultConverter);
977
Assert.AreEqual(testDate, m2.MemberConverter);
981
public void ConverterAttributeExample()
983
DateTime date = Convert.ToDateTime("1970-01-01T00:00:00Z").ToUniversalTime();
985
MemberConverterClass c = new MemberConverterClass
987
DefaultConverter = date,
988
MemberConverter = date
991
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
993
Console.WriteLine(json);
995
// "DefaultConverter": "\/Date(0)\/",
996
// "MemberConverter": "1970-01-01T00:00:00Z"
1001
public void SerializerShouldUseMemberConverterOverClassAndArgumentConverter()
1003
ClassAndMemberConverterClass c1 = new ClassAndMemberConverterClass();
1004
c1.DefaultConverter = new ConverterPrecedenceClass("DefaultConverterValue");
1005
c1.MemberConverter = new ConverterPrecedenceClass("MemberConverterValue");
1007
string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
1008
Assert.AreEqual(@"{""DefaultConverter"":[""Class"",""DefaultConverterValue""],""MemberConverter"":[""Member"",""MemberConverterValue""]}", json);
1010
ClassAndMemberConverterClass c2 = JsonConvert.DeserializeObject<ClassAndMemberConverterClass>(json, new ArgumentConverterPrecedenceClassConverter());
1012
Assert.AreEqual("DefaultConverterValue", c2.DefaultConverter.TestValue);
1013
Assert.AreEqual("MemberConverterValue", c2.MemberConverter.TestValue);
1017
public void IncompatibleJsonAttributeShouldThrow()
1019
ExceptionAssert.Throws<JsonSerializationException>(
1020
"Unexpected value when converting date. Expected DateTime or DateTimeOffset, got Newtonsoft.Json.Tests.TestObjects.IncompatibleJsonAttributeClass.",
1023
IncompatibleJsonAttributeClass c = new IncompatibleJsonAttributeClass();
1024
JsonConvert.SerializeObject(c);
1029
public void GenericAbstractProperty()
1031
string json = JsonConvert.SerializeObject(new GenericImpl());
1032
Assert.AreEqual(@"{""Id"":0}", json);
1036
public void DeserializeNullable()
1040
json = JsonConvert.SerializeObject((int?)null);
1041
Assert.AreEqual("null", json);
1043
json = JsonConvert.SerializeObject((int?)1);
1044
Assert.AreEqual("1", json);
1048
public void SerializeJsonRaw()
1050
PersonRaw personRaw = new PersonRaw
1052
FirstName = "FirstNameValue",
1053
RawContent = new JRaw("[1,2,3,4,5]"),
1054
LastName = "LastNameValue"
1059
json = JsonConvert.SerializeObject(personRaw);
1060
Assert.AreEqual(@"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}", json);
1064
public void DeserializeJsonRaw()
1066
string json = @"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}";
1068
PersonRaw personRaw = JsonConvert.DeserializeObject<PersonRaw>(json);
1070
Assert.AreEqual("FirstNameValue", personRaw.FirstName);
1071
Assert.AreEqual("[1,2,3,4,5]", personRaw.RawContent.ToString());
1072
Assert.AreEqual("LastNameValue", personRaw.LastName);
1077
public void DeserializeNullableMember()
1079
UserNullable userNullablle = new UserNullable
1081
Id = new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"),
1082
FName = "FirstValue",
1083
LName = "LastValue",
1090
string json = JsonConvert.SerializeObject(userNullablle);
1092
Assert.AreEqual(@"{""Id"":""ad6205e8-0df4-465d-aea6-8ba18e93a7e7"",""FName"":""FirstValue"",""LName"":""LastValue"",""RoleId"":5,""NullableRoleId"":6,""NullRoleId"":null,""Active"":true}", json);
1094
UserNullable userNullablleDeserialized = JsonConvert.DeserializeObject<UserNullable>(json);
1096
Assert.AreEqual(new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"), userNullablleDeserialized.Id);
1097
Assert.AreEqual("FirstValue", userNullablleDeserialized.FName);
1098
Assert.AreEqual("LastValue", userNullablleDeserialized.LName);
1099
Assert.AreEqual(5, userNullablleDeserialized.RoleId);
1100
Assert.AreEqual(6, userNullablleDeserialized.NullableRoleId);
1101
Assert.AreEqual(null, userNullablleDeserialized.NullRoleId);
1102
Assert.AreEqual(true, userNullablleDeserialized.Active);
1106
public void DeserializeInt64ToNullableDouble()
1108
string json = @"{""Height"":1}";
1110
DoubleClass c = JsonConvert.DeserializeObject<DoubleClass>(json);
1111
Assert.AreEqual(1, c.Height);
1115
public void SerializeTypeProperty()
1117
string boolRef = typeof(bool).AssemblyQualifiedName;
1118
TypeClass typeClass = new TypeClass { TypeProperty = typeof(bool) };
1120
string json = JsonConvert.SerializeObject(typeClass);
1121
Assert.AreEqual(@"{""TypeProperty"":""" + boolRef + @"""}", json);
1123
TypeClass typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
1124
Assert.AreEqual(typeof(bool), typeClass2.TypeProperty);
1126
string jsonSerializerTestRef = typeof(JsonSerializerTest).AssemblyQualifiedName;
1127
typeClass = new TypeClass { TypeProperty = typeof(JsonSerializerTest) };
1129
json = JsonConvert.SerializeObject(typeClass);
1130
Assert.AreEqual(@"{""TypeProperty"":""" + jsonSerializerTestRef + @"""}", json);
1132
typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
1133
Assert.AreEqual(typeof(JsonSerializerTest), typeClass2.TypeProperty);
1137
public void RequiredMembersClass()
1139
RequiredMembersClass c = new RequiredMembersClass()
1141
BirthDate = new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc),
1144
MiddleName = "Cosmo"
1147
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
1150
""FirstName"": ""Bob"",
1151
""MiddleName"": ""Cosmo"",
1152
""LastName"": ""Smith"",
1153
""BirthDate"": ""2000-12-20T10:55:55Z""
1156
RequiredMembersClass c2 = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
1158
Assert.AreEqual("Bob", c2.FirstName);
1159
Assert.AreEqual(new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc), c2.BirthDate);
1163
public void DeserializeRequiredMembersClassWithNullValues()
1166
""FirstName"": ""I can't be null bro!"",
1167
""MiddleName"": null,
1169
""BirthDate"": ""\/Date(977309755000)\/""
1172
RequiredMembersClass c = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
1174
Assert.AreEqual("I can't be null bro!", c.FirstName);
1175
Assert.AreEqual(null, c.MiddleName);
1176
Assert.AreEqual(null, c.LastName);
1180
public void DeserializeRequiredMembersClassNullRequiredValueProperty()
1182
ExceptionAssert.Throws<JsonSerializationException>(
1183
"Required property 'FirstName' expects a value but got null. Path '', line 6, position 2.",
1187
""FirstName"": null,
1188
""MiddleName"": null,
1190
""BirthDate"": ""\/Date(977309755000)\/""
1193
JsonConvert.DeserializeObject<RequiredMembersClass>(json);
1198
public void SerializeRequiredMembersClassNullRequiredValueProperty()
1200
ExceptionAssert.Throws<JsonSerializationException>(
1201
"Cannot write a null value for property 'FirstName'. Property requires a value. Path ''.",
1204
RequiredMembersClass requiredMembersClass = new RequiredMembersClass
1207
BirthDate = new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc),
1212
string json = JsonConvert.SerializeObject(requiredMembersClass);
1213
Console.WriteLine(json);
1218
public void RequiredMembersClassMissingRequiredProperty()
1220
ExceptionAssert.Throws<JsonSerializationException>(
1221
"Required property 'LastName' not found in JSON. Path '', line 3, position 2.",
1225
""FirstName"": ""Bob""
1228
JsonConvert.DeserializeObject<RequiredMembersClass>(json);
1233
public void SerializeJaggedArray()
1235
JaggedArray aa = new JaggedArray();
1236
aa.Before = "Before!";
1237
aa.After = "After!";
1238
aa.Coordinates = new[] { new[] { 1, 1 }, new[] { 1, 2 }, new[] { 2, 1 }, new[] { 2, 2 } };
1240
string json = JsonConvert.SerializeObject(aa);
1242
Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}", json);
1246
public void DeserializeJaggedArray()
1248
string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}";
1250
JaggedArray aa = JsonConvert.DeserializeObject<JaggedArray>(json);
1252
Assert.AreEqual("Before!", aa.Before);
1253
Assert.AreEqual("After!", aa.After);
1254
Assert.AreEqual(4, aa.Coordinates.Length);
1255
Assert.AreEqual(2, aa.Coordinates[0].Length);
1256
Assert.AreEqual(1, aa.Coordinates[0][0]);
1257
Assert.AreEqual(2, aa.Coordinates[1][1]);
1259
string after = JsonConvert.SerializeObject(aa);
1261
Assert.AreEqual(json, after);
1265
public void DeserializeGoogleGeoCode()
1268
""name"": ""1600 Amphitheatre Parkway, Mountain View, CA, USA"",
1271
""request"": ""geocode""
1275
""address"": ""1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"",
1276
""AddressDetails"": {
1278
""CountryNameCode"": ""US"",
1279
""AdministrativeArea"": {
1280
""AdministrativeAreaName"": ""CA"",
1281
""SubAdministrativeArea"": {
1282
""SubAdministrativeAreaName"": ""Santa Clara"",
1284
""LocalityName"": ""Mountain View"",
1286
""ThoroughfareName"": ""1600 Amphitheatre Pkwy""
1289
""PostalCodeNumber"": ""94043""
1298
""coordinates"": [-122.083739, 37.423021, 0]
1304
GoogleMapGeocoderStructure jsonGoogleMapGeocoder = JsonConvert.DeserializeObject<GoogleMapGeocoderStructure>(json);
1308
public void DeserializeInterfaceProperty()
1310
InterfacePropertyTestClass testClass = new InterfacePropertyTestClass();
1311
testClass.co = new Co();
1312
String strFromTest = JsonConvert.SerializeObject(testClass);
1314
ExceptionAssert.Throws<JsonSerializationException>(
1315
@"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantiated. Path 'co.Name', line 1, position 14.",
1318
InterfacePropertyTestClass testFromDe = (InterfacePropertyTestClass)JsonConvert.DeserializeObject(strFromTest, typeof(InterfacePropertyTestClass));
1322
private Person GetPerson()
1324
Person person = new Person
1326
Name = "Mike Manager",
1327
BirthDate = new DateTime(1983, 8, 3, 0, 0, 0, DateTimeKind.Utc),
1329
LastModified = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc)
1335
public void WriteJsonDates()
1337
LogEntry entry = new LogEntry
1339
LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
1340
Details = "Application started."
1343
string defaultJson = JsonConvert.SerializeObject(entry);
1344
// {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}
1346
string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
1347
// {"Details":"Application started.","LogDate":"2009-02-15T00:00:00.0000000Z"}
1349
string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
1350
// {"Details":"Application started.","LogDate":new Date(1234656000000)}
1352
Console.WriteLine(defaultJson);
1353
Console.WriteLine(isoJson);
1354
Console.WriteLine(javascriptJson);
1357
public void GenericListAndDictionaryInterfaceProperties()
1359
GenericListAndDictionaryInterfaceProperties o = new GenericListAndDictionaryInterfaceProperties();
1360
o.IDictionaryProperty = new Dictionary<string, int>
1366
o.IListProperty = new List<int>
1370
o.IEnumerableProperty = new List<int>
1375
string json = JsonConvert.SerializeObject(o, Formatting.Indented);
1378
""IEnumerableProperty"": [
1383
""IListProperty"": [
1388
""IDictionaryProperty"": {
1395
GenericListAndDictionaryInterfaceProperties deserializedObject = JsonConvert.DeserializeObject<GenericListAndDictionaryInterfaceProperties>(json);
1396
Assert.IsNotNull(deserializedObject);
1398
CollectionAssert.AreEqual(o.IListProperty.ToArray(), deserializedObject.IListProperty.ToArray());
1399
CollectionAssert.AreEqual(o.IEnumerableProperty.ToArray(), deserializedObject.IEnumerableProperty.ToArray());
1400
CollectionAssert.AreEqual(o.IDictionaryProperty.ToArray(), deserializedObject.IDictionaryProperty.ToArray());
1404
public void DeserializeBestMatchPropertyCase()
1407
""firstName"": ""firstName"",
1408
""FirstName"": ""FirstName"",
1409
""LastName"": ""LastName"",
1410
""lastName"": ""lastName"",
1413
PropertyCase o = JsonConvert.DeserializeObject<PropertyCase>(json);
1414
Assert.IsNotNull(o);
1416
Assert.AreEqual("firstName", o.firstName);
1417
Assert.AreEqual("FirstName", o.FirstName);
1418
Assert.AreEqual("LastName", o.LastName);
1419
Assert.AreEqual("lastName", o.lastName);
1423
public void DeserializePropertiesOnToNonDefaultConstructor()
1425
SubKlass i = new SubKlass("my subprop");
1426
i.SuperProp = "overrided superprop";
1428
string json = JsonConvert.SerializeObject(i);
1429
Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", json);
1431
SubKlass ii = JsonConvert.DeserializeObject<SubKlass>(json);
1433
string newJson = JsonConvert.SerializeObject(ii);
1434
Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", newJson);
1438
public void DeserializePropertiesOnToNonDefaultConstructorWithReferenceTracking()
1440
SubKlass i = new SubKlass("my subprop");
1441
i.SuperProp = "overrided superprop";
1443
string json = JsonConvert.SerializeObject(i, new JsonSerializerSettings
1445
PreserveReferencesHandling = PreserveReferencesHandling.Objects
1448
Assert.AreEqual(@"{""$id"":""1"",""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", json);
1450
SubKlass ii = JsonConvert.DeserializeObject<SubKlass>(json, new JsonSerializerSettings
1452
PreserveReferencesHandling = PreserveReferencesHandling.Objects
1455
string newJson = JsonConvert.SerializeObject(ii, new JsonSerializerSettings
1457
PreserveReferencesHandling = PreserveReferencesHandling.Objects
1459
Assert.AreEqual(@"{""$id"":""1"",""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", newJson);
1463
public void SerializeJsonPropertyWithHandlingValues()
1465
JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
1466
o.DefaultValueHandlingIgnoreProperty = "Default!";
1467
o.DefaultValueHandlingIncludeProperty = "Default!";
1468
o.DefaultValueHandlingPopulateProperty = "Default!";
1469
o.DefaultValueHandlingIgnoreAndPopulateProperty = "Default!";
1471
string json = JsonConvert.SerializeObject(o, Formatting.Indented);
1474
""DefaultValueHandlingIncludeProperty"": ""Default!"",
1475
""DefaultValueHandlingPopulateProperty"": ""Default!"",
1476
""NullValueHandlingIncludeProperty"": null,
1477
""ReferenceLoopHandlingErrorProperty"": null,
1478
""ReferenceLoopHandlingIgnoreProperty"": null,
1479
""ReferenceLoopHandlingSerializeProperty"": null
1482
json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
1485
""DefaultValueHandlingIncludeProperty"": ""Default!"",
1486
""DefaultValueHandlingPopulateProperty"": ""Default!"",
1487
""NullValueHandlingIncludeProperty"": null
1492
public void DeserializeJsonPropertyWithHandlingValues()
1496
JsonPropertyWithHandlingValues o = JsonConvert.DeserializeObject<JsonPropertyWithHandlingValues>(json);
1497
Assert.AreEqual("Default!", o.DefaultValueHandlingIgnoreAndPopulateProperty);
1498
Assert.AreEqual("Default!", o.DefaultValueHandlingPopulateProperty);
1499
Assert.AreEqual(null, o.DefaultValueHandlingIgnoreProperty);
1500
Assert.AreEqual(null, o.DefaultValueHandlingIncludeProperty);
1504
public void JsonPropertyWithHandlingValues_ReferenceLoopError()
1506
string classRef = typeof(JsonPropertyWithHandlingValues).FullName;
1508
ExceptionAssert.Throws<JsonSerializationException>(
1509
"Self referencing loop detected for property 'ReferenceLoopHandlingErrorProperty' with type '" + classRef + "'. Path ''.",
1512
JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
1513
o.ReferenceLoopHandlingErrorProperty = o;
1515
JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
1520
public void PartialClassDeserialize()
1523
""request"": ""ux.settings.update"",
1524
""sid"": ""14c561bd-32a8-457e-b4e5-4bba0832897f"",
1525
""uid"": ""30c39065-0f31-de11-9442-001e3786a8ec"",
1530
""andytest_address"",
1536
""entityName"": ""Andy Test"",
1537
""setting"": ""entity.field.order""
1540
RequestOnly r = JsonConvert.DeserializeObject<RequestOnly>(json);
1541
Assert.AreEqual("ux.settings.update", r.Request);
1543
NonRequest n = JsonConvert.DeserializeObject<NonRequest>(json);
1544
Assert.AreEqual(new Guid("14c561bd-32a8-457e-b4e5-4bba0832897f"), n.Sid);
1545
Assert.AreEqual(new Guid("30c39065-0f31-de11-9442-001e3786a8ec"), n.Uid);
1546
Assert.AreEqual(8, n.FidOrder.Count);
1547
Assert.AreEqual("id", n.FidOrder[0]);
1548
Assert.AreEqual("titleId", n.FidOrder[n.FidOrder.Count - 1]);
1551
#if !(SILVERLIGHT || NET20 || NETFX_CORE || PORTABLE)
1552
[MetadataType(typeof(OptInClassMetadata))]
1553
public class OptInClass
1556
public class OptInClassMetadata
1559
public string Name { get; set; }
1562
public int Age { get; set; }
1564
public string NotIncluded { get; set; }
1567
public string Name { get; set; }
1568
public int Age { get; set; }
1569
public string NotIncluded { get; set; }
1573
public void OptInClassMetadataSerialization()
1575
OptInClass optInClass = new OptInClass();
1576
optInClass.Age = 26;
1577
optInClass.Name = "James NK";
1578
optInClass.NotIncluded = "Poor me :(";
1580
string json = JsonConvert.SerializeObject(optInClass, Formatting.Indented);
1583
""Name"": ""James NK"",
1587
OptInClass newOptInClass = JsonConvert.DeserializeObject<OptInClass>(@"{
1588
""Name"": ""James NK"",
1589
""NotIncluded"": ""Ignore me!"",
1592
Assert.AreEqual(26, newOptInClass.Age);
1593
Assert.AreEqual("James NK", newOptInClass.Name);
1594
Assert.AreEqual(null, newOptInClass.NotIncluded);
1598
#if !PocketPC && !NET20
1600
public class DataContractPrivateMembers
1602
public DataContractPrivateMembers()
1606
public DataContractPrivateMembers(string name, int age, int rank, string title)
1615
private string _name;
1617
[DataMember(Name = "_age")]
1618
private int Age { get; set; }
1621
private int Rank { get; set; }
1623
[JsonProperty(PropertyName = "JsonTitle")]
1624
[DataMember(Name = "DataTitle")]
1625
private string Title { get; set; }
1627
public string NotIncluded { get; set; }
1629
public override string ToString()
1631
return "_name: " + _name + ", _age: " + Age + ", Rank: " + Rank + ", JsonTitle: " + Title;
1636
public void SerializeDataContractPrivateMembers()
1638
DataContractPrivateMembers c = new DataContractPrivateMembers("Jeff", 26, 10, "Dr");
1639
c.NotIncluded = "Hi";
1640
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
1643
""_name"": ""Jeff"",
1646
""JsonTitle"": ""Dr""
1649
DataContractPrivateMembers cc = JsonConvert.DeserializeObject<DataContractPrivateMembers>(json);
1650
Assert.AreEqual("_name: Jeff, _age: 26, Rank: 10, JsonTitle: Dr", cc.ToString());
1655
public void DeserializeDictionaryInterface()
1658
""Name"": ""Name!"",
1664
DictionaryInterfaceClass c = JsonConvert.DeserializeObject<DictionaryInterfaceClass>(
1666
new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace });
1668
Assert.AreEqual("Name!", c.Name);
1669
Assert.AreEqual(1, c.Dictionary.Count);
1670
Assert.AreEqual(11, c.Dictionary["Item"]);
1674
public void DeserializeDictionaryInterfaceWithExistingValues()
1680
""Name"": ""Name!"",
1690
""Name"": ""ManagerName!""
1695
DictionaryInterfaceClass c = JsonConvert.DeserializeObject<DictionaryInterfaceClass>(json,
1696
new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Reuse });
1698
Assert.AreEqual("Name!", c.Name);
1699
Assert.AreEqual(3, c.Dictionary.Count);
1700
Assert.AreEqual(11, c.Dictionary["Item"]);
1701
Assert.AreEqual(1, c.Dictionary["existing"]);
1702
Assert.AreEqual(4, c.Collection.Count);
1703
Assert.AreEqual(1, c.Collection.ElementAt(0));
1704
Assert.AreEqual(999, c.Collection.ElementAt(3));
1705
Assert.AreEqual("EmployeeName!", c.Employee.Name);
1706
Assert.AreEqual("ManagerName!", c.Employee.Manager.Name);
1707
Assert.IsNotNull(c.Random);
1711
public void TypedObjectDeserializationWithComments()
1713
string json = @"/*comment*/ { /*comment*/
1714
""Name"": /*comment*/ ""Apple"" /*comment*/, /*comment*/
1715
""ExpiryDate"": ""\/Date(1230422400000)\/"",
1717
""Sizes"": /*comment*/ [ /*comment*/
1718
""Small"", /*comment*/
1719
""Medium"" /*comment*/,
1720
/*comment*/ ""Large""
1721
/*comment*/ ] /*comment*/
1724
Product deserializedProduct = (Product)JsonConvert.DeserializeObject(json, typeof(Product));
1726
Assert.AreEqual("Apple", deserializedProduct.Name);
1727
Assert.AreEqual(new DateTime(2008, 12, 28, 0, 0, 0, DateTimeKind.Utc), deserializedProduct.ExpiryDate);
1728
Assert.AreEqual(3.99m, deserializedProduct.Price);
1729
Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
1730
Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
1731
Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
1735
public void NestedInsideOuterObject()
1739
""original"": ""http://www.contrast.ie/blog/online-marketing-2009/"",
1740
""short"": ""m2sqc6"",
1741
""shortened"": ""http://short.ie/m2sqc6"",
1744
""msg"": ""No action taken""
1749
JObject o = JObject.Parse(json);
1751
Shortie s = JsonConvert.DeserializeObject<Shortie>(o["short"].ToString());
1752
Assert.IsNotNull(s);
1754
Assert.AreEqual(s.Original, "http://www.contrast.ie/blog/online-marketing-2009/");
1755
Assert.AreEqual(s.Short, "m2sqc6");
1756
Assert.AreEqual(s.Shortened, "http://short.ie/m2sqc6");
1760
public void UriSerialization()
1762
Uri uri = new Uri("http://codeplex.com");
1763
string json = JsonConvert.SerializeObject(uri);
1765
Assert.AreEqual("http://codeplex.com/", uri.ToString());
1767
Uri newUri = JsonConvert.DeserializeObject<Uri>(json);
1768
Assert.AreEqual(uri, newUri);
1772
public void AnonymousPlusLinqToSql()
1776
bar = new JObject(new JProperty("baz", 13))
1779
string json = JsonConvert.SerializeObject(value);
1781
Assert.AreEqual(@"{""bar"":{""baz"":13}}", json);
1785
public void SerializeEnumerableAsObject()
1787
Content content = new Content
1789
Text = "Blah, blah, blah",
1790
Children = new List<Content>
1792
new Content {Text = "First"},
1793
new Content {Text = "Second"}
1797
string json = JsonConvert.SerializeObject(content, Formatting.Indented);
1807
""Text"": ""Second""
1810
""Text"": ""Blah, blah, blah""
1815
public void DeserializeEnumerableAsObject()
1825
""Text"": ""Second""
1828
""Text"": ""Blah, blah, blah""
1831
Content content = JsonConvert.DeserializeObject<Content>(json);
1833
Assert.AreEqual("Blah, blah, blah", content.Text);
1834
Assert.AreEqual(2, content.Children.Count);
1835
Assert.AreEqual("First", content.Children[0].Text);
1836
Assert.AreEqual("Second", content.Children[1].Text);
1840
public void RoleTransferTest()
1842
string json = @"{""Operation"":""1"",""RoleName"":""Admin"",""Direction"":""0""}";
1844
RoleTransfer r = JsonConvert.DeserializeObject<RoleTransfer>(json);
1846
Assert.AreEqual(RoleTransferOperation.Second, r.Operation);
1847
Assert.AreEqual("Admin", r.RoleName);
1848
Assert.AreEqual(RoleTransferDirection.First, r.Direction);
1852
public void PrimitiveValuesInObjectArray()
1854
string json = @"{""action"":""Router"",""method"":""Navigate"",""data"":[""dashboard"",null],""type"":""rpc"",""tid"":2}";
1856
ObjectArrayPropertyTest o = JsonConvert.DeserializeObject<ObjectArrayPropertyTest>(json);
1858
Assert.AreEqual("Router", o.Action);
1859
Assert.AreEqual("Navigate", o.Method);
1860
Assert.AreEqual(2, o.Data.Length);
1861
Assert.AreEqual("dashboard", o.Data[0]);
1862
Assert.AreEqual(null, o.Data[1]);
1866
public void ComplexValuesInObjectArray()
1868
string json = @"{""action"":""Router"",""method"":""Navigate"",""data"":[""dashboard"",[""id"", 1, ""teststring"", ""test""],{""one"":1}],""type"":""rpc"",""tid"":2}";
1870
ObjectArrayPropertyTest o = JsonConvert.DeserializeObject<ObjectArrayPropertyTest>(json);
1872
Assert.AreEqual("Router", o.Action);
1873
Assert.AreEqual("Navigate", o.Method);
1874
Assert.AreEqual(3, o.Data.Length);
1875
Assert.AreEqual("dashboard", o.Data[0]);
1876
CustomAssert.IsInstanceOfType(typeof(JArray), o.Data[1]);
1877
Assert.AreEqual(4, ((JArray)o.Data[1]).Count);
1878
CustomAssert.IsInstanceOfType(typeof(JObject), o.Data[2]);
1879
Assert.AreEqual(1, ((JObject)o.Data[2]).Count);
1880
Assert.AreEqual(1, (int)((JObject)o.Data[2])["one"]);
1884
public void DeserializeGenericDictionary()
1886
string json = @"{""key1"":""value1"",""key2"":""value2""}";
1888
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
1890
Console.WriteLine(values.Count);
1893
Console.WriteLine(values["key1"]);
1896
Assert.AreEqual(2, values.Count);
1897
Assert.AreEqual("value1", values["key1"]);
1898
Assert.AreEqual("value2", values["key2"]);
1902
public void SerializeGenericList()
1904
Product p1 = new Product
1908
ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
1910
Product p2 = new Product
1914
ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
1917
List<Product> products = new List<Product>();
1921
string json = JsonConvert.SerializeObject(products, Formatting.Indented);
1924
// "Name": "Product 1",
1925
// "ExpiryDate": "\/Date(978048000000)\/",
1930
// "Name": "Product 2",
1931
// "ExpiryDate": "\/Date(1248998400000)\/",
1939
""Name"": ""Product 1"",
1940
""ExpiryDate"": ""2000-12-29T00:00:00Z"",
1945
""Name"": ""Product 2"",
1946
""ExpiryDate"": ""2009-07-31T00:00:00Z"",
1954
public void DeserializeGenericList()
1958
""Name"": ""Product 1"",
1959
""ExpiryDate"": ""\/Date(978048000000)\/"",
1964
""Name"": ""Product 2"",
1965
""ExpiryDate"": ""\/Date(1248998400000)\/"",
1971
List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);
1973
Console.WriteLine(products.Count);
1976
Product p1 = products[0];
1978
Console.WriteLine(p1.Name);
1981
Assert.AreEqual(2, products.Count);
1982
Assert.AreEqual("Product 1", products[0].Name);
1985
#if !PocketPC && !NET20
1987
public void DeserializeEmptyStringToNullableDateTime()
1989
string json = @"{""DateTimeField"":""""}";
1991
NullableDateTimeTestClass c = JsonConvert.DeserializeObject<NullableDateTimeTestClass>(json);
1992
Assert.AreEqual(null, c.DateTimeField);
1997
public void FailWhenClassWithNoDefaultConstructorHasMultipleConstructorsWithArguments()
1999
string json = @"{""sublocation"":""AlertEmailSender.Program.Main"",""userId"":0,""type"":0,""summary"":""Loading settings variables"",""details"":null,""stackTrace"":"" at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)\r\n at System.Environment.get_StackTrace()\r\n at mr.Logging.Event..ctor(String summary) in C:\\Projects\\MRUtils\\Logging\\Event.vb:line 71\r\n at AlertEmailSender.Program.Main(String[] args) in C:\\Projects\\AlertEmailSender\\AlertEmailSender\\Program.cs:line 25"",""tag"":null,""time"":""\/Date(1249591032026-0400)\/""}";
2001
ExceptionAssert.Throws<JsonSerializationException>(
2002
@"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Event. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'sublocation', line 1, position 15.",
2005
JsonConvert.DeserializeObject<TestObjects.Event>(json);
2010
public void DeserializeObjectSetOnlyProperty()
2012
string json = @"{'SetOnlyProperty':[1,2,3,4,5]}";
2014
SetOnlyPropertyClass2 setOnly = JsonConvert.DeserializeObject<SetOnlyPropertyClass2>(json);
2015
JArray a = (JArray)setOnly.GetValue();
2016
Assert.AreEqual(5, a.Count);
2017
Assert.AreEqual(1, (int)a[0]);
2018
Assert.AreEqual(5, (int)a[a.Count - 1]);
2022
public void DeserializeOptInClasses()
2024
string json = @"{id: ""12"", name: ""test"", items: [{id: ""112"", name: ""testing""}]}";
2026
ListTestClass l = JsonConvert.DeserializeObject<ListTestClass>(json);
2030
public void DeserializeNullableListWithNulls()
2032
List<decimal?> l = JsonConvert.DeserializeObject<List<decimal?>>("[ 3.3, null, 1.1 ] ");
2033
Assert.AreEqual(3, l.Count);
2035
Assert.AreEqual(3.3m, l[0]);
2036
Assert.AreEqual(null, l[1]);
2037
Assert.AreEqual(1.1m, l[2]);
2041
public void CannotDeserializeArrayIntoObject()
2043
string json = @"[]";
2045
ExceptionAssert.Throws<JsonSerializationException>(
2046
@"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Newtonsoft.Json.Tests.TestObjects.Person' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
2047
To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
2048
Path '', line 1, position 1.",
2051
JsonConvert.DeserializeObject<Person>(json);
2056
public void CannotDeserializeArrayIntoDictionary()
2058
string json = @"[]";
2060
ExceptionAssert.Throws<JsonSerializationException>(
2061
@"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
2062
To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
2063
Path '', line 1, position 1.",
2066
JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
2070
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
2072
public void CannotDeserializeArrayIntoSerializable()
2074
string json = @"[]";
2076
ExceptionAssert.Throws<JsonSerializationException>(
2077
@"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Exception' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
2078
To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
2079
Path '', line 1, position 1.",
2082
JsonConvert.DeserializeObject<Exception>(json);
2088
public void CannotDeserializeArrayIntoDouble()
2090
string json = @"[]";
2092
ExceptionAssert.Throws<JsonSerializationException>(
2093
@"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Double' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly.
2094
To fix this error either change the JSON to a JSON primitive value (e.g. string, number, boolean, null) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
2095
Path '', line 1, position 1.",
2098
JsonConvert.DeserializeObject<double>(json);
2102
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
2104
public void CannotDeserializeArrayIntoDynamic()
2106
string json = @"[]";
2108
ExceptionAssert.Throws<JsonSerializationException>(
2109
@"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Newtonsoft.Json.Tests.Linq.DynamicDictionary' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
2110
To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
2111
Path '', line 1, position 1.",
2114
JsonConvert.DeserializeObject<DynamicDictionary>(json);
2120
public void CannotDeserializeArrayIntoLinqToJson()
2122
string json = @"[]";
2124
ExceptionAssert.Throws<InvalidCastException>(
2125
@"Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.",
2128
JsonConvert.DeserializeObject<JObject>(json);
2133
public void CannotDeserializeConstructorIntoObject()
2135
string json = @"new Constructor(123)";
2137
ExceptionAssert.Throws<JsonSerializationException>(
2138
@"Error converting value ""Constructor"" to type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '', line 1, position 16.",
2141
JsonConvert.DeserializeObject<Person>(json);
2146
public void CannotDeserializeConstructorIntoObjectNested()
2148
string json = @"[new Constructor(123)]";
2150
ExceptionAssert.Throws<JsonSerializationException>(
2151
@"Error converting value ""Constructor"" to type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '[0]', line 1, position 17.",
2154
JsonConvert.DeserializeObject<List<Person>>(json);
2159
public void CannotDeserializeObjectIntoArray()
2161
string json = @"{}";
2163
ExceptionAssert.Throws<JsonSerializationException>(
2164
@"Cannot deserialize the current JSON object (e.g. {""name"":""value""}) into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
2165
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
2166
Path '', line 1, position 2.",
2169
JsonConvert.DeserializeObject<List<Person>>(json);
2174
public void CannotPopulateArrayIntoObject()
2176
string json = @"[]";
2178
ExceptionAssert.Throws<JsonSerializationException>(
2179
@"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '', line 1, position 1.",
2182
JsonConvert.PopulateObject(json, new Person());
2187
public void CannotPopulateObjectIntoArray()
2189
string json = @"{}";
2191
ExceptionAssert.Throws<JsonSerializationException>(
2192
@"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Path '', line 1, position 2.",
2195
JsonConvert.PopulateObject(json, new List<Person>());
2200
public void DeserializeEmptyString()
2202
string json = @"{""Name"":""""}";
2204
Person p = JsonConvert.DeserializeObject<Person>(json);
2205
Assert.AreEqual("", p.Name);
2209
public void SerializePropertyGetError()
2211
ExceptionAssert.Throws<JsonSerializationException>(
2212
@"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.",
2215
JsonConvert.SerializeObject(new MemoryStream(), new JsonSerializerSettings
2217
ContractResolver = new DefaultContractResolver
2219
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
2220
IgnoreSerializableAttribute = true
2228
public void DeserializePropertySetError()
2230
ExceptionAssert.Throws<JsonSerializationException>(
2231
@"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'.",
2234
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:0}", new JsonSerializerSettings
2236
ContractResolver = new DefaultContractResolver
2238
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
2239
IgnoreSerializableAttribute = true
2247
public void DeserializeEnsureTypeEmptyStringToIntError()
2249
ExceptionAssert.Throws<JsonSerializationException>(
2250
@"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 15.",
2253
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}", new JsonSerializerSettings
2255
ContractResolver = new DefaultContractResolver
2257
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
2258
IgnoreSerializableAttribute = true
2266
public void DeserializeEnsureTypeNullToIntError()
2268
ExceptionAssert.Throws<JsonSerializationException>(
2269
@"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 17.",
2272
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}", new JsonSerializerSettings
2274
ContractResolver = new DefaultContractResolver
2276
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
2277
IgnoreSerializableAttribute = true
2285
public void SerializeGenericListOfStrings()
2287
List<String> strings = new List<String>();
2289
strings.Add("str_1");
2290
strings.Add("str_2");
2291
strings.Add("str_3");
2293
string json = JsonConvert.SerializeObject(strings);
2294
Assert.AreEqual(@"[""str_1"",""str_2"",""str_3""]", json);
2298
public void ConstructorReadonlyFieldsTest()
2300
ConstructorReadonlyFields c1 = new ConstructorReadonlyFields("String!", int.MaxValue);
2301
string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
2307
ConstructorReadonlyFields c2 = JsonConvert.DeserializeObject<ConstructorReadonlyFields>(json);
2308
Assert.AreEqual("String!", c2.A);
2309
Assert.AreEqual(int.MaxValue, c2.B);
2313
public void SerializeStruct()
2315
StructTest structTest = new StructTest
2317
StringProperty = "StringProperty!",
2318
StringField = "StringField",
2323
string json = JsonConvert.SerializeObject(structTest, Formatting.Indented);
2324
Console.WriteLine(json);
2326
""StringField"": ""StringField"",
2328
""StringProperty"": ""StringProperty!"",
2332
StructTest deserialized = JsonConvert.DeserializeObject<StructTest>(json);
2333
Assert.AreEqual(structTest.StringProperty, deserialized.StringProperty);
2334
Assert.AreEqual(structTest.StringField, deserialized.StringField);
2335
Assert.AreEqual(structTest.IntProperty, deserialized.IntProperty);
2336
Assert.AreEqual(structTest.IntField, deserialized.IntField);
2340
public void SerializeListWithJsonConverter()
2343
f.Bars.Add(new Bar { Id = 0 });
2344
f.Bars.Add(new Bar { Id = 1 });
2345
f.Bars.Add(new Bar { Id = 2 });
2347
string json = JsonConvert.SerializeObject(f, Formatting.Indented);
2356
Foo newFoo = JsonConvert.DeserializeObject<Foo>(json);
2357
Assert.AreEqual(3, newFoo.Bars.Count);
2358
Assert.AreEqual(0, newFoo.Bars[0].Id);
2359
Assert.AreEqual(1, newFoo.Bars[1].Id);
2360
Assert.AreEqual(2, newFoo.Bars[2].Id);
2364
public void SerializeGuidKeyedDictionary()
2366
Dictionary<Guid, int> dictionary = new Dictionary<Guid, int>();
2367
dictionary.Add(new Guid("F60EAEE0-AE47-488E-B330-59527B742D77"), 1);
2368
dictionary.Add(new Guid("C2594C02-EBA1-426A-AA87-8DD8871350B0"), 2);
2370
string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
2372
""f60eaee0-ae47-488e-b330-59527b742d77"": 1,
2373
""c2594c02-eba1-426a-aa87-8dd8871350b0"": 2
2378
public void SerializePersonKeyedDictionary()
2380
Dictionary<Person, int> dictionary = new Dictionary<Person, int>();
2381
dictionary.Add(new Person { Name = "p1" }, 1);
2382
dictionary.Add(new Person { Name = "p2" }, 2);
2384
string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
2387
""Newtonsoft.Json.Tests.TestObjects.Person"": 1,
2388
""Newtonsoft.Json.Tests.TestObjects.Person"": 2
2393
public void DeserializePersonKeyedDictionary()
2395
ExceptionAssert.Throws<JsonSerializationException>("Could not convert string 'Newtonsoft.Json.Tests.TestObjects.Person' to dictionary key type 'Newtonsoft.Json.Tests.TestObjects.Person'. Create a TypeConverter to convert from the string to the key type object. Path 'Newtonsoft.Json.Tests.TestObjects.Person', line 2, position 46.",
2400
""Newtonsoft.Json.Tests.TestObjects.Person"": 1,
2401
""Newtonsoft.Json.Tests.TestObjects.Person"": 2
2404
JsonConvert.DeserializeObject<Dictionary<Person, int>>(json);
2409
public void SerializeFragment()
2411
string googleSearchText = @"{
2415
""GsearchResultClass"": ""GwebSearch"",
2416
""unescapedUrl"": ""http://en.wikipedia.org/wiki/Paris_Hilton"",
2417
""url"": ""http://en.wikipedia.org/wiki/Paris_Hilton"",
2418
""visibleUrl"": ""en.wikipedia.org"",
2419
""cacheUrl"": ""http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org"",
2420
""title"": ""<b>Paris Hilton</b> - Wikipedia, the free encyclopedia"",
2421
""titleNoFormatting"": ""Paris Hilton - Wikipedia, the free encyclopedia"",
2422
""content"": ""[1] In 2006, she released her debut album...""
2425
""GsearchResultClass"": ""GwebSearch"",
2426
""unescapedUrl"": ""http://www.imdb.com/name/nm0385296/"",
2427
""url"": ""http://www.imdb.com/name/nm0385296/"",
2428
""visibleUrl"": ""www.imdb.com"",
2429
""cacheUrl"": ""http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com"",
2430
""title"": ""<b>Paris Hilton</b>"",
2431
""titleNoFormatting"": ""Paris Hilton"",
2432
""content"": ""Self: Zoolander. Socialite <b>Paris Hilton</b>...""
2454
""estimatedResultCount"": ""59600000"",
2455
""currentPageIndex"": 0,
2456
""moreResultsUrl"": ""http://www.google.com/search?oe=utf8&ie=utf8...""
2459
""responseDetails"": null,
2460
""responseStatus"": 200
2463
JObject googleSearch = JObject.Parse(googleSearchText);
2465
// get JSON result objects into a list
2466
IList<JToken> results = googleSearch["responseData"]["results"].Children().ToList();
2468
// serialize JSON results into .NET objects
2469
IList<SearchResult> searchResults = new List<SearchResult>();
2470
foreach (JToken result in results)
2472
SearchResult searchResult = JsonConvert.DeserializeObject<SearchResult>(result.ToString());
2473
searchResults.Add(searchResult);
2476
// Title = <b>Paris Hilton</b> - Wikipedia, the free encyclopedia
2477
// Content = [1] In 2006, she released her debut album...
2478
// Url = http://en.wikipedia.org/wiki/Paris_Hilton
2480
// Title = <b>Paris Hilton</b>
2481
// Content = Self: Zoolander. Socialite <b>Paris Hilton</b>...
2482
// Url = http://www.imdb.com/name/nm0385296/
2484
Assert.AreEqual(2, searchResults.Count);
2485
Assert.AreEqual("<b>Paris Hilton</b> - Wikipedia, the free encyclopedia", searchResults[0].Title);
2486
Assert.AreEqual("<b>Paris Hilton</b>", searchResults[1].Title);
2490
public void DeserializeBaseReferenceWithDerivedValue()
2492
PersonPropertyClass personPropertyClass = new PersonPropertyClass();
2493
WagePerson wagePerson = (WagePerson)personPropertyClass.Person;
2495
wagePerson.BirthDate = new DateTime(2000, 11, 29, 23, 59, 59, DateTimeKind.Utc);
2496
wagePerson.Department = "McDees";
2497
wagePerson.HourlyWage = 12.50m;
2498
wagePerson.LastModified = new DateTime(2000, 11, 29, 23, 59, 59, DateTimeKind.Utc);
2499
wagePerson.Name = "Jim Bob";
2501
string json = JsonConvert.SerializeObject(personPropertyClass, Formatting.Indented);
2505
""HourlyWage"": 12.50,
2506
""Name"": ""Jim Bob"",
2507
""BirthDate"": ""2000-11-29T23:59:59Z"",
2508
""LastModified"": ""2000-11-29T23:59:59Z""
2513
PersonPropertyClass newPersonPropertyClass = JsonConvert.DeserializeObject<PersonPropertyClass>(json);
2514
Assert.AreEqual(wagePerson.HourlyWage, ((WagePerson)newPersonPropertyClass.Person).HourlyWage);
2517
public class ExistingValueClass
2519
public Dictionary<string, string> Dictionary { get; set; }
2520
public List<string> List { get; set; }
2522
public ExistingValueClass()
2524
Dictionary = new Dictionary<string, string>
2528
List = new List<string>
2536
public void DeserializePopulateDictionaryAndList()
2538
ExistingValueClass d = JsonConvert.DeserializeObject<ExistingValueClass>(@"{'Dictionary':{appended:'appended',existing:'new'}}");
2540
Assert.IsNotNull(d);
2541
Assert.IsNotNull(d.Dictionary);
2542
Assert.AreEqual(typeof(Dictionary<string, string>), d.Dictionary.GetType());
2543
Assert.AreEqual(typeof(List<string>), d.List.GetType());
2544
Assert.AreEqual(2, d.Dictionary.Count);
2545
Assert.AreEqual("new", d.Dictionary["existing"]);
2546
Assert.AreEqual("appended", d.Dictionary["appended"]);
2547
Assert.AreEqual(1, d.List.Count);
2548
Assert.AreEqual("existing", d.List[0]);
2551
public interface IKeyValueId
2553
int Id { get; set; }
2554
string Key { get; set; }
2555
string Value { get; set; }
2559
public class KeyValueId : IKeyValueId
2561
public int Id { get; set; }
2562
public string Key { get; set; }
2563
public string Value { get; set; }
2566
public class ThisGenericTest<T> where T : IKeyValueId
2568
private Dictionary<string, T> _dict1 = new Dictionary<string, T>();
2570
public string MyProperty { get; set; }
2572
public void Add(T item)
2574
this._dict1.Add(item.Key, item);
2577
public T this[string key]
2579
get { return this._dict1[key]; }
2580
set { this._dict1[key] = value; }
2583
public T this[int id]
2585
get { return this._dict1.Values.FirstOrDefault(x => x.Id == id); }
2588
var item = this[id];
2593
this._dict1[item.Key] = value;
2597
public string ToJson()
2599
return JsonConvert.SerializeObject(this, Formatting.Indented);
2604
get { return this._dict1.Values.ToArray<T>(); }
2607
foreach (var item in value)
2614
public void IgnoreIndexedProperties()
2616
ThisGenericTest<KeyValueId> g = new ThisGenericTest<KeyValueId>();
2618
g.Add(new KeyValueId { Id = 1, Key = "key1", Value = "value1" });
2619
g.Add(new KeyValueId { Id = 2, Key = "key2", Value = "value2" });
2621
g.MyProperty = "some value";
2623
string json = g.ToJson();
2626
""MyProperty"": ""some value"",
2631
""Value"": ""value1""
2636
""Value"": ""value2""
2641
ThisGenericTest<KeyValueId> gen = JsonConvert.DeserializeObject<ThisGenericTest<KeyValueId>>(json);
2642
Assert.AreEqual("some value", gen.MyProperty);
2645
public class JRawValueTestObject
2647
public JRaw Value { get; set; }
2651
public void JRawValue()
2653
JRawValueTestObject deserialized = JsonConvert.DeserializeObject<JRawValueTestObject>("{value:3}");
2654
Assert.AreEqual("3", deserialized.Value.ToString());
2656
deserialized = JsonConvert.DeserializeObject<JRawValueTestObject>("{value:'3'}");
2657
Assert.AreEqual(@"""3""", deserialized.Value.ToString());
2661
public void DeserializeDictionaryWithNoDefaultConstructor()
2663
string json = "{key1:'value',key2:'value',key3:'value'}";
2665
ExceptionAssert.Throws<JsonSerializationException>(
2666
"Unable to find a default constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Path 'key1', line 1, position 6.",
2669
JsonConvert.DeserializeObject<DictionaryWithNoDefaultConstructor>(json);
2673
public class DictionaryWithNoDefaultConstructor : Dictionary<string, string>
2675
public DictionaryWithNoDefaultConstructor(IEnumerable<KeyValuePair<string, string>> initial)
2677
foreach (KeyValuePair<string, string> pair in initial)
2679
Add(pair.Key, pair.Value);
2684
[JsonObject(MemberSerialization.OptIn)]
2687
[JsonProperty("A1")]
2693
set { _A1 = value; }
2696
[JsonProperty("A2")]
2697
private string A2 { get; set; }
2700
[JsonObject(MemberSerialization.OptIn)]
2703
public string B1 { get; set; }
2705
[JsonProperty("B2")]
2711
set { _B2 = value; }
2714
[JsonProperty("B3")]
2715
private string B3 { get; set; }
2719
public void SerializeNonPublicBaseJsonProperties()
2722
string json = JsonConvert.SerializeObject(value, Formatting.Indented);
2732
public class TestClass
2734
public string Key { get; set; }
2735
public object Value { get; set; }
2739
public void DeserializeToObjectProperty()
2741
var json = "{ Key: 'abc', Value: 123 }";
2742
var item = JsonConvert.DeserializeObject<TestClass>(json);
2744
Assert.AreEqual(123L, item.Value);
2747
public abstract class Animal
2749
public abstract string Name { get; }
2752
public class Human : Animal
2754
public override string Name
2756
get { return typeof(Human).Name; }
2759
public string Ethnicity { get; set; }
2762
#if !NET20 && !PocketPC && !WINDOWS_PHONE
2763
public class DataContractJsonSerializerTestClass
2765
public TimeSpan TimeSpanProperty { get; set; }
2766
public Guid GuidProperty { get; set; }
2767
public Animal AnimalProperty { get; set; }
2768
public Exception ExceptionProperty { get; set; }
2772
public void DataContractJsonSerializerTest()
2774
Exception ex = new Exception("Blah blah blah");
2776
DataContractJsonSerializerTestClass c = new DataContractJsonSerializerTestClass();
2777
c.TimeSpanProperty = new TimeSpan(200, 20, 59, 30, 900);
2778
c.GuidProperty = new Guid("66143115-BE2A-4a59-AF0A-348E1EA15B1E");
2779
c.AnimalProperty = new Human() { Ethnicity = "European" };
2780
c.ExceptionProperty = ex;
2782
MemoryStream ms = new MemoryStream();
2783
DataContractJsonSerializer serializer = new DataContractJsonSerializer(
2784
typeof(DataContractJsonSerializerTestClass),
2785
new Type[] { typeof(Human) });
2786
serializer.WriteObject(ms, c);
2788
byte[] jsonBytes = ms.ToArray();
2789
string json = Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length);
2791
//Console.WriteLine(JObject.Parse(json).ToString());
2792
//Console.WriteLine();
2794
//Console.WriteLine(JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings
2796
// // TypeNameHandling = TypeNameHandling.Objects
2801
public class ModelStateDictionary<T> : IDictionary<string, T>
2804
private readonly Dictionary<string, T> _innerDictionary = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
2806
public ModelStateDictionary()
2810
public ModelStateDictionary(ModelStateDictionary<T> dictionary)
2812
if (dictionary == null)
2814
throw new ArgumentNullException("dictionary");
2817
foreach (var entry in dictionary)
2819
_innerDictionary.Add(entry.Key, entry.Value);
2825
get { return _innerDictionary.Count; }
2828
public bool IsReadOnly
2830
get { return ((IDictionary<string, T>)_innerDictionary).IsReadOnly; }
2833
public ICollection<string> Keys
2835
get { return _innerDictionary.Keys; }
2838
public T this[string key]
2843
_innerDictionary.TryGetValue(key, out value);
2846
set { _innerDictionary[key] = value; }
2849
public ICollection<T> Values
2851
get { return _innerDictionary.Values; }
2854
public void Add(KeyValuePair<string, T> item)
2856
((IDictionary<string, T>)_innerDictionary).Add(item);
2859
public void Add(string key, T value)
2861
_innerDictionary.Add(key, value);
2866
_innerDictionary.Clear();
2869
public bool Contains(KeyValuePair<string, T> item)
2871
return ((IDictionary<string, T>)_innerDictionary).Contains(item);
2874
public bool ContainsKey(string key)
2876
return _innerDictionary.ContainsKey(key);
2879
public void CopyTo(KeyValuePair<string, T>[] array, int arrayIndex)
2881
((IDictionary<string, T>)_innerDictionary).CopyTo(array, arrayIndex);
2884
public IEnumerator<KeyValuePair<string, T>> GetEnumerator()
2886
return _innerDictionary.GetEnumerator();
2889
public void Merge(ModelStateDictionary<T> dictionary)
2891
if (dictionary == null)
2896
foreach (var entry in dictionary)
2898
this[entry.Key] = entry.Value;
2902
public bool Remove(KeyValuePair<string, T> item)
2904
return ((IDictionary<string, T>)_innerDictionary).Remove(item);
2907
public bool Remove(string key)
2909
return _innerDictionary.Remove(key);
2912
public bool TryGetValue(string key, out T value)
2914
return _innerDictionary.TryGetValue(key, out value);
2917
IEnumerator IEnumerable.GetEnumerator()
2919
return ((IEnumerable)_innerDictionary).GetEnumerator();
2924
public void SerializeNonIDictionary()
2926
ModelStateDictionary<string> modelStateDictionary = new ModelStateDictionary<string>();
2927
modelStateDictionary.Add("key", "value");
2929
string json = JsonConvert.SerializeObject(modelStateDictionary);
2931
Assert.AreEqual(@"{""key"":""value""}", json);
2933
ModelStateDictionary<string> newModelStateDictionary = JsonConvert.DeserializeObject<ModelStateDictionary<string>>(json);
2934
Assert.AreEqual(1, newModelStateDictionary.Count);
2935
Assert.AreEqual("value", newModelStateDictionary["key"]);
2938
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
2939
public class ISerializableTestObject : ISerializable
2941
internal string _stringValue;
2942
internal int _intValue;
2943
internal DateTimeOffset _dateTimeOffsetValue;
2944
internal Person _personValue;
2945
internal Person _nullPersonValue;
2946
internal int? _nullableInt;
2947
internal bool _booleanValue;
2948
internal byte _byteValue;
2949
internal char _charValue;
2950
internal DateTime _dateTimeValue;
2951
internal decimal _decimalValue;
2952
internal short _shortValue;
2953
internal long _longValue;
2954
internal sbyte _sbyteValue;
2955
internal float _floatValue;
2956
internal ushort _ushortValue;
2957
internal uint _uintValue;
2958
internal ulong _ulongValue;
2960
public ISerializableTestObject(string stringValue, int intValue, DateTimeOffset dateTimeOffset, Person personValue)
2962
_stringValue = stringValue;
2963
_intValue = intValue;
2964
_dateTimeOffsetValue = dateTimeOffset;
2965
_personValue = personValue;
2966
_dateTimeValue = new DateTime(0, DateTimeKind.Utc);
2969
protected ISerializableTestObject(SerializationInfo info, StreamingContext context)
2971
_stringValue = info.GetString("stringValue");
2972
_intValue = info.GetInt32("intValue");
2973
_dateTimeOffsetValue = (DateTimeOffset)info.GetValue("dateTimeOffsetValue", typeof(DateTimeOffset));
2974
_personValue = (Person)info.GetValue("personValue", typeof(Person));
2975
_nullPersonValue = (Person)info.GetValue("nullPersonValue", typeof(Person));
2976
_nullableInt = (int?)info.GetValue("nullableInt", typeof(int?));
2978
_booleanValue = info.GetBoolean("booleanValue");
2979
_byteValue = info.GetByte("byteValue");
2980
_charValue = info.GetChar("charValue");
2981
_dateTimeValue = info.GetDateTime("dateTimeValue");
2982
_decimalValue = info.GetDecimal("decimalValue");
2983
_shortValue = info.GetInt16("shortValue");
2984
_longValue = info.GetInt64("longValue");
2985
_sbyteValue = info.GetSByte("sbyteValue");
2986
_floatValue = info.GetSingle("floatValue");
2987
_ushortValue = info.GetUInt16("ushortValue");
2988
_uintValue = info.GetUInt32("uintValue");
2989
_ulongValue = info.GetUInt64("ulongValue");
2992
public void GetObjectData(SerializationInfo info, StreamingContext context)
2994
info.AddValue("stringValue", _stringValue);
2995
info.AddValue("intValue", _intValue);
2996
info.AddValue("dateTimeOffsetValue", _dateTimeOffsetValue);
2997
info.AddValue("personValue", _personValue);
2998
info.AddValue("nullPersonValue", _nullPersonValue);
2999
info.AddValue("nullableInt", null);
3001
info.AddValue("booleanValue", _booleanValue);
3002
info.AddValue("byteValue", _byteValue);
3003
info.AddValue("charValue", _charValue);
3004
info.AddValue("dateTimeValue", _dateTimeValue);
3005
info.AddValue("decimalValue", _decimalValue);
3006
info.AddValue("shortValue", _shortValue);
3007
info.AddValue("longValue", _longValue);
3008
info.AddValue("sbyteValue", _sbyteValue);
3009
info.AddValue("floatValue", _floatValue);
3010
info.AddValue("ushortValue", _ushortValue);
3011
info.AddValue("uintValue", _uintValue);
3012
info.AddValue("ulongValue", _ulongValue);
3018
public void SerializeISerializableInPartialTrustWithIgnoreInterface()
3022
JsonTypeReflector.SetFullyTrusted(false);
3023
ISerializableTestObject value = new ISerializableTestObject("string!", 0, default(DateTimeOffset), null);
3025
string json = JsonConvert.SerializeObject(value, new JsonSerializerSettings
3027
ContractResolver = new DefaultContractResolver(false)
3029
IgnoreSerializableInterface = true
3033
Assert.AreEqual("{}", json);
3035
value = JsonConvert.DeserializeObject<ISerializableTestObject>("{booleanValue:true}", new JsonSerializerSettings
3037
ContractResolver = new DefaultContractResolver(false)
3039
IgnoreSerializableInterface = true
3043
Assert.IsNotNull(value);
3044
Assert.AreEqual(false, value._booleanValue);
3048
JsonTypeReflector.SetFullyTrusted(true);
3053
public void SerializeISerializableInPartialTrust()
3057
ExceptionAssert.Throws<JsonSerializationException>(
3058
@"Type 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ISerializableTestObject' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
3059
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.
3060
Path 'booleanValue', line 1, position 14.",
3063
JsonTypeReflector.SetFullyTrusted(false);
3065
JsonConvert.DeserializeObject<ISerializableTestObject>("{booleanValue:true}");
3070
JsonTypeReflector.SetFullyTrusted(true);
3075
public void DeserializeISerializableInPartialTrust()
3079
ExceptionAssert.Throws<JsonSerializationException>(
3080
@"Type 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ISerializableTestObject' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
3081
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true. Path ''.",
3084
JsonTypeReflector.SetFullyTrusted(false);
3085
ISerializableTestObject value = new ISerializableTestObject("string!", 0, default(DateTimeOffset), null);
3087
JsonConvert.SerializeObject(value);
3092
JsonTypeReflector.SetFullyTrusted(true);
3098
public void SerializeISerializableTestObject_IsoDate()
3100
Person person = new Person();
3101
person.BirthDate = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
3102
person.LastModified = person.BirthDate;
3103
person.Department = "Department!";
3104
person.Name = "Name!";
3106
DateTimeOffset dateTimeOffset = new DateTimeOffset(2000, 12, 20, 22, 59, 59, TimeSpan.FromHours(2));
3107
string dateTimeOffsetText;
3109
dateTimeOffsetText = @"2000-12-20T22:59:59+02:00";
3111
dateTimeOffsetText = @"12/20/2000 22:59:59 +02:00";
3114
ISerializableTestObject o = new ISerializableTestObject("String!", int.MinValue, dateTimeOffset, person);
3116
string json = JsonConvert.SerializeObject(o, Formatting.Indented);
3118
""stringValue"": ""String!"",
3119
""intValue"": -2147483648,
3120
""dateTimeOffsetValue"": """ + dateTimeOffsetText + @""",
3122
""Name"": ""Name!"",
3123
""BirthDate"": ""2000-01-01T01:01:01Z"",
3124
""LastModified"": ""2000-01-01T01:01:01Z""
3126
""nullPersonValue"": null,
3127
""nullableInt"": null,
3128
""booleanValue"": false,
3130
""charValue"": ""\u0000"",
3131
""dateTimeValue"": ""0001-01-01T00:00:00Z"",
3132
""decimalValue"": 0.0,
3136
""floatValue"": 0.0,
3142
ISerializableTestObject o2 = JsonConvert.DeserializeObject<ISerializableTestObject>(json);
3143
Assert.AreEqual("String!", o2._stringValue);
3144
Assert.AreEqual(int.MinValue, o2._intValue);
3145
Assert.AreEqual(dateTimeOffset, o2._dateTimeOffsetValue);
3146
Assert.AreEqual("Name!", o2._personValue.Name);
3147
Assert.AreEqual(null, o2._nullPersonValue);
3148
Assert.AreEqual(null, o2._nullableInt);
3152
public void SerializeISerializableTestObject_MsAjax()
3154
Person person = new Person();
3155
person.BirthDate = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
3156
person.LastModified = person.BirthDate;
3157
person.Department = "Department!";
3158
person.Name = "Name!";
3160
DateTimeOffset dateTimeOffset = new DateTimeOffset(2000, 12, 20, 22, 59, 59, TimeSpan.FromHours(2));
3161
string dateTimeOffsetText;
3163
dateTimeOffsetText = @"\/Date(977345999000+0200)\/";
3165
dateTimeOffsetText = @"12/20/2000 22:59:59 +02:00";
3168
ISerializableTestObject o = new ISerializableTestObject("String!", int.MinValue, dateTimeOffset, person);
3170
string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
3172
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
3175
""stringValue"": ""String!"",
3176
""intValue"": -2147483648,
3177
""dateTimeOffsetValue"": """ + dateTimeOffsetText + @""",
3179
""Name"": ""Name!"",
3180
""BirthDate"": ""\/Date(946688461000)\/"",
3181
""LastModified"": ""\/Date(946688461000)\/""
3183
""nullPersonValue"": null,
3184
""nullableInt"": null,
3185
""booleanValue"": false,
3187
""charValue"": ""\u0000"",
3188
""dateTimeValue"": ""\/Date(-62135596800000)\/"",
3189
""decimalValue"": 0.0,
3193
""floatValue"": 0.0,
3199
ISerializableTestObject o2 = JsonConvert.DeserializeObject<ISerializableTestObject>(json);
3200
Assert.AreEqual("String!", o2._stringValue);
3201
Assert.AreEqual(int.MinValue, o2._intValue);
3202
Assert.AreEqual(dateTimeOffset, o2._dateTimeOffsetValue);
3203
Assert.AreEqual("Name!", o2._personValue.Name);
3204
Assert.AreEqual(null, o2._nullPersonValue);
3205
Assert.AreEqual(null, o2._nullableInt);
3209
public class KVPair<TKey, TValue>
3211
public TKey Key { get; set; }
3212
public TValue Value { get; set; }
3214
public KVPair(TKey k, TValue v)
3222
public void DeserializeUsingNonDefaultConstructorWithLeftOverValues()
3224
List<KVPair<string, string>> kvPairs =
3225
JsonConvert.DeserializeObject<List<KVPair<string, string>>>(
3226
"[{\"Key\":\"Two\",\"Value\":\"2\"},{\"Key\":\"One\",\"Value\":\"1\"}]");
3228
Assert.AreEqual(2, kvPairs.Count);
3229
Assert.AreEqual("Two", kvPairs[0].Key);
3230
Assert.AreEqual("2", kvPairs[0].Value);
3231
Assert.AreEqual("One", kvPairs[1].Key);
3232
Assert.AreEqual("1", kvPairs[1].Value);
3236
public void SerializeClassWithInheritedProtectedMember()
3239
string json = JsonConvert.SerializeObject(myA, Formatting.Indented);
3242
""AA_property1"": 2,
3243
""AA_property2"": 2,
3244
""AA_property3"": 2,
3248
BB myB = new BB(3, 4);
3249
json = JsonConvert.SerializeObject(myB, Formatting.Indented);
3254
""BB_property1"": 4,
3255
""BB_property2"": 4,
3256
""BB_property3"": 4,
3257
""BB_property4"": 4,
3258
""BB_property5"": 4,
3259
""BB_property7"": 4,
3260
""AA_property1"": 3,
3261
""AA_property2"": 3,
3262
""AA_property3"": 3,
3268
public void DeserializeClassWithInheritedProtectedMember()
3270
AA myA = JsonConvert.DeserializeObject<AA>(
3274
""AA_property1"": 2,
3275
""AA_property2"": 2,
3276
""AA_property3"": 2,
3277
""AA_property4"": 2,
3278
""AA_property5"": 2,
3282
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field1", BindingFlags.Instance | BindingFlags.NonPublic), myA));
3283
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field2", BindingFlags.Instance | BindingFlags.NonPublic), myA));
3284
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property1", BindingFlags.Instance | BindingFlags.NonPublic), myA));
3285
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property2", BindingFlags.Instance | BindingFlags.NonPublic), myA));
3286
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property3", BindingFlags.Instance | BindingFlags.NonPublic), myA));
3287
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property4", BindingFlags.Instance | BindingFlags.NonPublic), myA));
3288
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property5", BindingFlags.Instance | BindingFlags.NonPublic), myA));
3289
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property6", BindingFlags.Instance | BindingFlags.NonPublic), myA));
3291
BB myB = JsonConvert.DeserializeObject<BB>(
3297
""AA_property1"": 2,
3298
""AA_property2"": 2,
3299
""AA_property3"": 2,
3300
""AA_property4"": 2,
3301
""AA_property5"": 2,
3302
""AA_property6"": 2,
3303
""BB_property1"": 3,
3304
""BB_property2"": 3,
3305
""BB_property3"": 3,
3306
""BB_property4"": 3,
3307
""BB_property5"": 3,
3308
""BB_property6"": 3,
3309
""BB_property7"": 3,
3313
Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field1", BindingFlags.Instance | BindingFlags.NonPublic), myB));
3314
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field2", BindingFlags.Instance | BindingFlags.NonPublic), myB));
3315
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property1", BindingFlags.Instance | BindingFlags.NonPublic), myB));
3316
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property2", BindingFlags.Instance | BindingFlags.NonPublic), myB));
3317
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property3", BindingFlags.Instance | BindingFlags.NonPublic), myB));
3318
Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property4", BindingFlags.Instance | BindingFlags.NonPublic), myB));
3319
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property5", BindingFlags.Instance | BindingFlags.NonPublic), myB));
3320
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property6", BindingFlags.Instance | BindingFlags.NonPublic), myB));
3322
Assert.AreEqual(4, myB.BB_field1);
3323
Assert.AreEqual(4, myB.BB_field2);
3324
Assert.AreEqual(3, myB.BB_property1);
3325
Assert.AreEqual(3, myB.BB_property2);
3326
Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property3", BindingFlags.Instance | BindingFlags.Public), myB));
3327
Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property4", BindingFlags.Instance | BindingFlags.NonPublic), myB));
3328
Assert.AreEqual(0, myB.BB_property5);
3329
Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property6", BindingFlags.Instance | BindingFlags.Public), myB));
3330
Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property7", BindingFlags.Instance | BindingFlags.Public), myB));
3331
Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property8", BindingFlags.Instance | BindingFlags.Public), myB));
3337
protected int AA_field1;
3338
protected int AA_field2;
3341
protected int AA_property1 { get; set; }
3344
protected int AA_property2 { get; private set; }
3347
protected int AA_property3 { private get; set; }
3350
private int AA_property4 { get; set; }
3352
protected int AA_property5 { get; private set; }
3353
protected int AA_property6 { private get; set; }
3372
public class BB : AA
3375
public int BB_field1;
3376
public int BB_field2;
3379
public int BB_property1 { get; set; }
3382
public int BB_property2 { get; private set; }
3385
public int BB_property3 { private get; set; }
3388
private int BB_property4 { get; set; }
3390
public int BB_property5 { get; private set; }
3391
public int BB_property6 { private get; set; }
3394
public int BB_property7 { protected get; set; }
3396
public int BB_property8 { protected get; set; }
3402
public BB(int f, int g)
3418
#if !NET20 && !SILVERLIGHT
3419
public class XNodeTestObject
3421
public XDocument Document { get; set; }
3422
public XElement Element { get; set; }
3426
#if !SILVERLIGHT && !NETFX_CORE
3427
public class XmlNodeTestObject
3429
public XmlDocument Document { get; set; }
3433
#if !(NET20 || SILVERLIGHT || PORTABLE)
3435
public void SerializeDeserializeXNodeProperties()
3437
XNodeTestObject testObject = new XNodeTestObject();
3438
testObject.Document = XDocument.Parse("<root>hehe, root</root>");
3439
testObject.Element = XElement.Parse(@"<fifth xmlns:json=""http://json.org"" json:Awesome=""true"">element</fifth>");
3441
string json = JsonConvert.SerializeObject(testObject, Formatting.Indented);
3442
string expected = @"{
3444
""root"": ""hehe, root""
3448
""@xmlns:json"": ""http://json.org"",
3449
""@json:Awesome"": ""true"",
3450
""#text"": ""element""
3454
Assert.AreEqual(expected, json);
3456
XNodeTestObject newTestObject = JsonConvert.DeserializeObject<XNodeTestObject>(json);
3457
Assert.AreEqual(testObject.Document.ToString(), newTestObject.Document.ToString());
3458
Assert.AreEqual(testObject.Element.ToString(), newTestObject.Element.ToString());
3460
Assert.IsNull(newTestObject.Element.Parent);
3464
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
3466
public void SerializeDeserializeXmlNodeProperties()
3468
XmlNodeTestObject testObject = new XmlNodeTestObject();
3469
XmlDocument document = new XmlDocument();
3470
document.LoadXml("<root>hehe, root</root>");
3471
testObject.Document = document;
3473
string json = JsonConvert.SerializeObject(testObject, Formatting.Indented);
3474
string expected = @"{
3476
""root"": ""hehe, root""
3479
Assert.AreEqual(expected, json);
3481
XmlNodeTestObject newTestObject = JsonConvert.DeserializeObject<XmlNodeTestObject>(json);
3482
Assert.AreEqual(testObject.Document.InnerXml, newTestObject.Document.InnerXml);
3487
public void FullClientMapSerialization()
3489
ClientMap source = new ClientMap()
3491
position = new Pos() { X = 100, Y = 200 },
3492
center = new PosDouble() { X = 251.6, Y = 361.3 }
3495
string json = JsonConvert.SerializeObject(source, new PosConverter(), new PosDoubleConverter());
3496
Assert.AreEqual("{\"position\":new Pos(100,200),\"center\":new PosD(251.6,361.3)}", json);
3499
public class ClientMap
3501
public Pos position { get; set; }
3502
public PosDouble center { get; set; }
3507
public int X { get; set; }
3508
public int Y { get; set; }
3511
public class PosDouble
3513
public double X { get; set; }
3514
public double Y { get; set; }
3517
public class PosConverter : JsonConverter
3519
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
3524
writer.WriteRawValue(String.Format("new Pos({0},{1})", p.X, p.Y));
3529
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
3531
throw new NotImplementedException();
3534
public override bool CanConvert(Type objectType)
3536
return objectType.IsAssignableFrom(typeof(Pos));
3540
public class PosDoubleConverter : JsonConverter
3542
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
3544
PosDouble p = (PosDouble)value;
3547
writer.WriteRawValue(String.Format(CultureInfo.InvariantCulture, "new PosD({0},{1})", p.X, p.Y));
3552
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
3554
throw new NotImplementedException();
3557
public override bool CanConvert(Type objectType)
3559
return objectType.IsAssignableFrom(typeof(PosDouble));
3564
public void TestEscapeDictionaryStrings()
3566
const string s = @"host\user";
3567
string serialized = JsonConvert.SerializeObject(s);
3568
Assert.AreEqual(@"""host\\user""", serialized);
3570
Dictionary<int, object> d1 = new Dictionary<int, object>();
3572
Assert.AreEqual(@"{""5"":""host\\user""}", JsonConvert.SerializeObject(d1));
3574
Dictionary<string, object> d2 = new Dictionary<string, object>();
3576
Assert.AreEqual(@"{""host\\user"":5}", JsonConvert.SerializeObject(d2));
3579
public class GenericListTestClass
3581
public List<string> GenericList { get; set; }
3583
public GenericListTestClass()
3585
GenericList = new List<string>();
3590
public void DeserializeExistingGenericList()
3592
GenericListTestClass c = new GenericListTestClass();
3593
c.GenericList.Add("1");
3594
c.GenericList.Add("2");
3596
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
3598
GenericListTestClass newValue = JsonConvert.DeserializeObject<GenericListTestClass>(json);
3599
Assert.AreEqual(2, newValue.GenericList.Count);
3600
Assert.AreEqual(typeof(List<string>), newValue.GenericList.GetType());
3604
public void DeserializeSimpleKeyValuePair()
3606
List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
3607
list.Add(new KeyValuePair<string, string>("key1", "value1"));
3608
list.Add(new KeyValuePair<string, string>("key2", "value2"));
3610
string json = JsonConvert.SerializeObject(list);
3612
Assert.AreEqual(@"[{""Key"":""key1"",""Value"":""value1""},{""Key"":""key2"",""Value"":""value2""}]", json);
3614
List<KeyValuePair<string, string>> result = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(json);
3615
Assert.AreEqual(2, result.Count);
3616
Assert.AreEqual("key1", result[0].Key);
3617
Assert.AreEqual("value1", result[0].Value);
3618
Assert.AreEqual("key2", result[1].Key);
3619
Assert.AreEqual("value2", result[1].Value);
3623
public void DeserializeComplexKeyValuePair()
3625
DateTime dateTime = new DateTime(2000, 12, 1, 23, 1, 1, DateTimeKind.Utc);
3627
List<KeyValuePair<string, WagePerson>> list = new List<KeyValuePair<string, WagePerson>>();
3628
list.Add(new KeyValuePair<string, WagePerson>("key1", new WagePerson
3630
BirthDate = dateTime,
3631
Department = "Department1",
3632
LastModified = dateTime,
3635
list.Add(new KeyValuePair<string, WagePerson>("key2", new WagePerson
3637
BirthDate = dateTime,
3638
Department = "Department2",
3639
LastModified = dateTime,
3643
string json = JsonConvert.SerializeObject(list, Formatting.Indented);
3649
""HourlyWage"": 1.0,
3651
""BirthDate"": ""2000-12-01T23:01:01Z"",
3652
""LastModified"": ""2000-12-01T23:01:01Z""
3658
""HourlyWage"": 2.0,
3660
""BirthDate"": ""2000-12-01T23:01:01Z"",
3661
""LastModified"": ""2000-12-01T23:01:01Z""
3666
List<KeyValuePair<string, WagePerson>> result = JsonConvert.DeserializeObject<List<KeyValuePair<string, WagePerson>>>(json);
3667
Assert.AreEqual(2, result.Count);
3668
Assert.AreEqual("key1", result[0].Key);
3669
Assert.AreEqual(1, result[0].Value.HourlyWage);
3670
Assert.AreEqual("key2", result[1].Key);
3671
Assert.AreEqual(2, result[1].Value.HourlyWage);
3674
public class StringListAppenderConverter : JsonConverter
3676
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
3678
writer.WriteValue(value);
3681
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
3683
List<string> existingStrings = (List<string>)existingValue;
3684
List<string> newStrings = new List<string>(existingStrings);
3688
while (reader.TokenType != JsonToken.EndArray)
3690
string s = (string)reader.Value;
3699
public override bool CanConvert(Type objectType)
3701
return (objectType == typeof(List<string>));
3706
public void StringListAppenderConverterTest()
3708
Movie p = new Movie();
3709
p.ReleaseCountries = new List<string> { "Existing" };
3711
JsonConvert.PopulateObject("{'ReleaseCountries':['Appended']}", p, new JsonSerializerSettings
3713
Converters = new List<JsonConverter> { new StringListAppenderConverter() }
3716
Assert.AreEqual(2, p.ReleaseCountries.Count);
3717
Assert.AreEqual("Existing", p.ReleaseCountries[0]);
3718
Assert.AreEqual("Appended", p.ReleaseCountries[1]);
3721
public class StringAppenderConverter : JsonConverter
3723
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
3725
writer.WriteValue(value);
3728
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
3730
string existingString = (string)existingValue;
3731
string newString = existingString + (string)reader.Value;
3736
public override bool CanConvert(Type objectType)
3738
return (objectType == typeof(string));
3743
public void StringAppenderConverterTest()
3745
Movie p = new Movie();
3746
p.Name = "Existing,";
3748
JsonConvert.PopulateObject("{'Name':'Appended'}", p, new JsonSerializerSettings
3750
Converters = new List<JsonConverter> { new StringAppenderConverter() }
3753
Assert.AreEqual("Existing,Appended", p.Name);
3757
public void SerializeRefAdditionalContent()
3759
//Additional text found in JSON string after finishing deserializing object.
3761
var reference = new Dictionary<string, object>();
3762
reference.Add("$ref", "Persons");
3763
reference.Add("$id", 1);
3765
var child = new Dictionary<string, object>();
3766
child.Add("_id", 2);
3767
child.Add("Name", "Isabell");
3768
child.Add("Father", reference);
3770
var json = JsonConvert.SerializeObject(child, Formatting.Indented);
3772
ExceptionAssert.Throws<JsonSerializationException>(
3773
"Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Path 'Father.$id', line 6, position 11.",
3776
JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
3781
public void SerializeRefBadType()
3783
ExceptionAssert.Throws<JsonSerializationException>(
3784
"JSON reference $ref property must have a string or null value. Path 'Father.$ref', line 5, position 14.",
3787
//Additional text found in JSON string after finishing deserializing object.
3789
var reference = new Dictionary<string, object>();
3790
reference.Add("$ref", 1);
3791
reference.Add("$id", 1);
3793
var child = new Dictionary<string, object>();
3794
child.Add("_id", 2);
3795
child.Add("Name", "Isabell");
3796
child.Add("Father", reference);
3798
var json = JsonConvert.SerializeObject(child, Formatting.Indented);
3799
JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
3804
public void SerializeRefNull()
3806
var reference = new Dictionary<string, object>();
3807
reference.Add("$ref", null);
3808
reference.Add("$id", null);
3809
reference.Add("blah", "blah!");
3811
var child = new Dictionary<string, object>();
3812
child.Add("_id", 2);
3813
child.Add("Name", "Isabell");
3814
child.Add("Father", reference);
3816
var json = JsonConvert.SerializeObject(child);
3817
Dictionary<string, object> result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
3819
Assert.AreEqual(3, result.Count);
3820
Assert.AreEqual(1, ((JObject)result["Father"]).Count);
3821
Assert.AreEqual("blah!", (string)((JObject)result["Father"])["blah"]);
3824
public class ConstructorCompexIgnoredProperty
3827
public Product Ignored { get; set; }
3829
public string First { get; set; }
3830
public int Second { get; set; }
3832
public ConstructorCompexIgnoredProperty(string first, int second)
3840
public void DeserializeIgnoredPropertyInConstructor()
3842
string json = @"{""First"":""First"",""Second"":2,""Ignored"":{""Name"":""James""},""AdditionalContent"":{""LOL"":true}}";
3844
ConstructorCompexIgnoredProperty cc = JsonConvert.DeserializeObject<ConstructorCompexIgnoredProperty>(json);
3845
Assert.AreEqual("First", cc.First);
3846
Assert.AreEqual(2, cc.Second);
3847
Assert.AreEqual(null, cc.Ignored);
3851
public void ShouldSerializeTest()
3853
ShouldSerializeTestClass c = new ShouldSerializeTestClass();
3857
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
3863
c._shouldSerializeName = true;
3864
json = JsonConvert.SerializeObject(c, Formatting.Indented);
3867
""Name"": ""James"",
3871
ShouldSerializeTestClass deserialized = JsonConvert.DeserializeObject<ShouldSerializeTestClass>(json);
3872
Assert.AreEqual("James", deserialized.Name);
3873
Assert.AreEqual(27, deserialized.Age);
3876
public class Employee
3878
public string Name { get; set; }
3879
public Employee Manager { get; set; }
3881
public bool ShouldSerializeManager()
3883
return (Manager != this);
3888
public void ShouldSerializeExample()
3890
Employee joe = new Employee();
3891
joe.Name = "Joe Employee";
3892
Employee mike = new Employee();
3893
mike.Name = "Mike Manager";
3896
mike.Manager = mike;
3898
string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented);
3901
// "Name": "Joe Employee",
3903
// "Name": "Mike Manager"
3907
// "Name": "Mike Manager"
3911
Console.WriteLine(json);
3915
public void SpecifiedTest()
3917
SpecifiedTestClass c = new SpecifiedTestClass();
3920
c.NameSpecified = false;
3922
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
3928
SpecifiedTestClass deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json);
3929
Assert.IsNull(deserialized.Name);
3930
Assert.IsFalse(deserialized.NameSpecified);
3931
Assert.IsFalse(deserialized.WeightSpecified);
3932
Assert.IsFalse(deserialized.HeightSpecified);
3933
Assert.IsFalse(deserialized.FavoriteNumberSpecified);
3934
Assert.AreEqual(27, deserialized.Age);
3936
c.NameSpecified = true;
3937
c.WeightSpecified = true;
3938
c.HeightSpecified = true;
3939
c.FavoriteNumber = 23;
3940
json = JsonConvert.SerializeObject(c, Formatting.Indented);
3943
""Name"": ""James"",
3947
""FavoriteNumber"": 23
3950
deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json);
3951
Assert.AreEqual("James", deserialized.Name);
3952
Assert.IsTrue(deserialized.NameSpecified);
3953
Assert.IsTrue(deserialized.WeightSpecified);
3954
Assert.IsTrue(deserialized.HeightSpecified);
3955
Assert.IsTrue(deserialized.FavoriteNumberSpecified);
3956
Assert.AreEqual(27, deserialized.Age);
3957
Assert.AreEqual(23, deserialized.FavoriteNumber);
3961
// public void XmlSerializerSpecifiedTrueTest()
3963
// XmlSerializer s = new XmlSerializer(typeof(OptionalOrder));
3965
// StringWriter sw = new StringWriter();
3966
// s.Serialize(sw, new OptionalOrder() { FirstOrder = "First", FirstOrderSpecified = true });
3968
// Console.WriteLine(sw.ToString());
3970
// string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
3971
//<OptionalOrder xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
3972
// <FirstOrder>First</FirstOrder>
3973
//</OptionalOrder>";
3975
// OptionalOrder o = (OptionalOrder)s.Deserialize(new StringReader(xml));
3976
// Console.WriteLine(o.FirstOrder);
3977
// Console.WriteLine(o.FirstOrderSpecified);
3981
// public void XmlSerializerSpecifiedFalseTest()
3983
// XmlSerializer s = new XmlSerializer(typeof(OptionalOrder));
3985
// StringWriter sw = new StringWriter();
3986
// s.Serialize(sw, new OptionalOrder() { FirstOrder = "First", FirstOrderSpecified = false });
3988
// Console.WriteLine(sw.ToString());
3990
// // string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
3991
// //<OptionalOrder xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
3992
// // <FirstOrder>First</FirstOrder>
3993
// //</OptionalOrder>";
3995
// // OptionalOrder o = (OptionalOrder)s.Deserialize(new StringReader(xml));
3996
// // Console.WriteLine(o.FirstOrder);
3997
// // Console.WriteLine(o.FirstOrderSpecified);
4000
public class OptionalOrder
4002
// This field shouldn't be serialized
4003
// if it is uninitialized.
4004
public string FirstOrder;
4005
// Use the XmlIgnoreAttribute to ignore the
4006
// special field named "FirstOrderSpecified".
4007
[System.Xml.Serialization.XmlIgnoreAttribute]
4008
public bool FirstOrderSpecified;
4011
public class FamilyDetails
4013
public string Name { get; set; }
4014
public int NumberOfChildren { get; set; }
4017
public bool NumberOfChildrenSpecified { get; set; }
4021
public void SpecifiedExample()
4023
FamilyDetails joe = new FamilyDetails();
4024
joe.Name = "Joe Family Details";
4025
joe.NumberOfChildren = 4;
4026
joe.NumberOfChildrenSpecified = true;
4028
FamilyDetails martha = new FamilyDetails();
4029
martha.Name = "Martha Family Details";
4030
martha.NumberOfChildren = 3;
4031
martha.NumberOfChildrenSpecified = false;
4033
string json = JsonConvert.SerializeObject(new[] { joe, martha }, Formatting.Indented);
4036
// "Name": "Joe Family Details",
4037
// "NumberOfChildren": 4
4040
// "Name": "Martha Family Details"
4043
Console.WriteLine(json);
4045
string mikeString = "{\"Name\": \"Mike Person\"}";
4046
FamilyDetails mike = JsonConvert.DeserializeObject<FamilyDetails>(mikeString);
4048
Console.WriteLine("mikeString specifies number of children: {0}", mike.NumberOfChildrenSpecified);
4050
string mikeFullDisclosureString = "{\"Name\": \"Mike Person\", \"NumberOfChildren\": \"0\"}";
4051
mike = JsonConvert.DeserializeObject<FamilyDetails>(mikeFullDisclosureString);
4053
Console.WriteLine("mikeString specifies number of children: {0}", mike.NumberOfChildrenSpecified);
4056
public class DictionaryKey
4058
public string Value { get; set; }
4060
public override string ToString()
4065
public static implicit operator DictionaryKey(string value)
4067
return new DictionaryKey() { Value = value };
4072
public void SerializeDeserializeDictionaryKey()
4074
Dictionary<DictionaryKey, string> dictionary = new Dictionary<DictionaryKey, string>();
4076
dictionary.Add(new DictionaryKey() { Value = "First!" }, "First");
4077
dictionary.Add(new DictionaryKey() { Value = "Second!" }, "Second");
4079
string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
4082
""First!"": ""First"",
4083
""Second!"": ""Second""
4086
Dictionary<DictionaryKey, string> newDictionary =
4087
JsonConvert.DeserializeObject<Dictionary<DictionaryKey, string>>(json);
4089
Assert.AreEqual(2, newDictionary.Count);
4093
public void SerializeNullableArray()
4095
string jsonText = JsonConvert.SerializeObject(new double?[] { 2.4, 4.3, null }, Formatting.Indented);
4103
double?[] d = (double?[])JsonConvert.DeserializeObject(jsonText, typeof(double?[]));
4105
Assert.AreEqual(3, d.Length);
4106
Assert.AreEqual(2.4, d[0]);
4107
Assert.AreEqual(4.3, d[1]);
4108
Assert.AreEqual(null, d[2]);
4111
#if !SILVERLIGHT && !NET20 && !PocketPC
4113
public void SerializeHashSet()
4115
string jsonText = JsonConvert.SerializeObject(new HashSet<string>()
4120
}, Formatting.Indented);
4128
HashSet<string> d = JsonConvert.DeserializeObject<HashSet<string>>(jsonText);
4130
Assert.AreEqual(3, d.Count);
4131
Assert.IsTrue(d.Contains("One"));
4132
Assert.IsTrue(d.Contains("2"));
4133
Assert.IsTrue(d.Contains("III"));
4137
private class MyClass
4139
public byte[] Prop1 { get; set; }
4143
Prop1 = new byte[0];
4148
public void DeserializeByteArray()
4150
JsonSerializer serializer1 = new JsonSerializer();
4151
serializer1.Converters.Add(new IsoDateTimeConverter());
4152
serializer1.NullValueHandling = NullValueHandling.Ignore;
4154
string json = @"[{""Prop1"":""""},{""Prop1"":""""}]";
4156
JsonTextReader reader = new JsonTextReader(new StringReader(json));
4158
MyClass[] z = (MyClass[])serializer1.Deserialize(reader, typeof(MyClass[]));
4159
Assert.AreEqual(2, z.Length);
4160
Assert.AreEqual(0, z[0].Prop1.Length);
4161
Assert.AreEqual(0, z[1].Prop1.Length);
4164
#if !NET20 && !PocketPC && !SILVERLIGHT && !NETFX_CORE
4165
public class StringDictionaryTestClass
4167
public StringDictionary StringDictionaryProperty { get; set; }
4171
public void StringDictionaryTest()
4173
string classRef = typeof(StringDictionary).FullName;
4175
StringDictionaryTestClass s1 = new StringDictionaryTestClass()
4177
StringDictionaryProperty = new StringDictionary()
4185
string json = JsonConvert.SerializeObject(s1, Formatting.Indented);
4187
ExceptionAssert.Throws<InvalidOperationException>(
4188
"Cannot create and populate list type " + classRef + ".",
4191
JsonConvert.DeserializeObject<StringDictionaryTestClass>(json);
4196
[JsonObject(MemberSerialization.OptIn)]
4197
public struct StructWithAttribute
4199
public string MyString { get; set; }
4202
public int MyInt { get; set; }
4206
public void SerializeStructWithJsonObjectAttribute()
4208
StructWithAttribute testStruct = new StructWithAttribute
4210
MyInt = int.MaxValue
4213
string json = JsonConvert.SerializeObject(testStruct, Formatting.Indented);
4216
""MyInt"": 2147483647
4219
StructWithAttribute newStruct = JsonConvert.DeserializeObject<StructWithAttribute>(json);
4221
Assert.AreEqual(int.MaxValue, newStruct.MyInt);
4224
public class TimeZoneOffsetObject
4226
public DateTimeOffset Offset { get; set; }
4231
public void ReadWriteTimeZoneOffsetIso()
4233
var serializeObject = JsonConvert.SerializeObject(new TimeZoneOffsetObject
4235
Offset = new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6))
4238
Assert.AreEqual("{\"Offset\":\"2000-01-01T00:00:00+06:00\"}", serializeObject);
4239
var deserializeObject = JsonConvert.DeserializeObject<TimeZoneOffsetObject>(serializeObject);
4240
Assert.AreEqual(TimeSpan.FromHours(6), deserializeObject.Offset.Offset);
4241
Assert.AreEqual(new DateTime(2000, 1, 1), deserializeObject.Offset.Date);
4245
public void DeserializePropertyNullableDateTimeOffsetExactIso()
4247
NullableDateTimeTestClass d = JsonConvert.DeserializeObject<NullableDateTimeTestClass>("{\"DateTimeOffsetField\":\"2000-01-01T00:00:00+06:00\"}");
4248
Assert.AreEqual(new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6)), d.DateTimeOffsetField);
4252
public void ReadWriteTimeZoneOffsetMsAjax()
4254
var serializeObject = JsonConvert.SerializeObject(new TimeZoneOffsetObject
4256
Offset = new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6))
4257
}, Formatting.None, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
4259
Assert.AreEqual("{\"Offset\":\"\\/Date(946663200000+0600)\\/\"}", serializeObject);
4260
var deserializeObject = JsonConvert.DeserializeObject<TimeZoneOffsetObject>(serializeObject);
4261
Assert.AreEqual(TimeSpan.FromHours(6), deserializeObject.Offset.Offset);
4262
Assert.AreEqual(new DateTime(2000, 1, 1), deserializeObject.Offset.Date);
4266
public void DeserializePropertyNullableDateTimeOffsetExactMsAjax()
4268
NullableDateTimeTestClass d = JsonConvert.DeserializeObject<NullableDateTimeTestClass>("{\"DateTimeOffsetField\":\"\\/Date(946663200000+0600)\\/\"}");
4269
Assert.AreEqual(new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6)), d.DateTimeOffsetField);
4273
public abstract class LogEvent
4275
[JsonProperty("event")]
4276
public abstract string EventName { get; }
4279
public class DerivedEvent : LogEvent
4281
public override string EventName
4283
get { return "derived"; }
4288
public void OverridenPropertyMembers()
4290
string json = JsonConvert.SerializeObject(new DerivedEvent(), Formatting.Indented);
4293
""event"": ""derived""
4297
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
4299
public void SerializeExpandoObject()
4301
dynamic expando = new ExpandoObject();
4303
expando.Decimal = 99.9d;
4304
expando.Complex = new ExpandoObject();
4305
expando.Complex.String = "I am a string";
4306
expando.Complex.DateTime = new DateTime(2000, 12, 20, 18, 55, 0, DateTimeKind.Utc);
4308
string json = JsonConvert.SerializeObject(expando, Formatting.Indented);
4313
""String"": ""I am a string"",
4314
""DateTime"": ""2000-12-20T18:55:00Z""
4318
IDictionary<string, object> newExpando = JsonConvert.DeserializeObject<ExpandoObject>(json);
4320
CustomAssert.IsInstanceOfType(typeof(long), newExpando["Int"]);
4321
Assert.AreEqual((long)expando.Int, newExpando["Int"]);
4323
CustomAssert.IsInstanceOfType(typeof(double), newExpando["Decimal"]);
4324
Assert.AreEqual(expando.Decimal, newExpando["Decimal"]);
4326
CustomAssert.IsInstanceOfType(typeof(ExpandoObject), newExpando["Complex"]);
4327
IDictionary<string, object> o = (ExpandoObject)newExpando["Complex"];
4329
CustomAssert.IsInstanceOfType(typeof(string), o["String"]);
4330
Assert.AreEqual(expando.Complex.String, o["String"]);
4332
CustomAssert.IsInstanceOfType(typeof(DateTime), o["DateTime"]);
4333
Assert.AreEqual(expando.Complex.DateTime, o["DateTime"]);
4338
public void DeserializeDecimalExact()
4340
decimal d = JsonConvert.DeserializeObject<decimal>("123456789876543.21");
4341
Assert.AreEqual(123456789876543.21m, d);
4345
public void DeserializeNullableDecimalExact()
4347
decimal? d = JsonConvert.DeserializeObject<decimal?>("123456789876543.21");
4348
Assert.AreEqual(123456789876543.21m, d);
4352
public void DeserializeDecimalPropertyExact()
4354
string json = "{Amount:123456789876543.21}";
4355
Invoice i = JsonConvert.DeserializeObject<Invoice>(json);
4356
Assert.AreEqual(123456789876543.21m, i.Amount);
4360
public void DeserializeDecimalArrayExact()
4362
string json = "[123456789876543.21]";
4363
IList<decimal> a = JsonConvert.DeserializeObject<IList<decimal>>(json);
4364
Assert.AreEqual(123456789876543.21m, a[0]);
4368
public void DeserializeDecimalDictionaryExact()
4370
string json = "{'Value':123456789876543.21}";
4371
IDictionary<string, decimal> d = JsonConvert.DeserializeObject<IDictionary<string, decimal>>(json);
4372
Assert.AreEqual(123456789876543.21m, d["Value"]);
4375
public struct Vector
4381
public override string ToString()
4383
return string.Format("({0},{1},{2})", X, Y, Z);
4387
public class VectorParent
4389
public Vector Position;
4393
public void DeserializeStructProperty()
4395
VectorParent obj = new VectorParent();
4396
obj.Position = new Vector { X = 1, Y = 2, Z = 3 };
4398
string str = JsonConvert.SerializeObject(obj);
4400
obj = JsonConvert.DeserializeObject<VectorParent>(str);
4402
Assert.AreEqual(1, obj.Position.X);
4403
Assert.AreEqual(2, obj.Position.Y);
4404
Assert.AreEqual(3, obj.Position.Z);
4407
[JsonObject(MemberSerialization.OptIn)]
4408
public class Derived : Base
4411
public string IDoWork { get; private set; }
4417
internal Derived(string dontWork, string doWork)
4424
[JsonObject(MemberSerialization.OptIn)]
4428
public string IDontWork { get; private set; }
4434
internal Base(string dontWork)
4436
IDontWork = dontWork;
4441
public void PrivateSetterOnBaseClassProperty()
4443
var derived = new Derived("meh", "woo");
4445
var settings = new JsonSerializerSettings
4447
TypeNameHandling = TypeNameHandling.Objects,
4448
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
4451
string json = JsonConvert.SerializeObject(derived, Formatting.Indented, settings);
4453
var meh = JsonConvert.DeserializeObject<Base>(json, settings);
4455
Assert.AreEqual(((Derived)meh).IDoWork, "woo");
4456
Assert.AreEqual(meh.IDontWork, "meh");
4459
#if !(SILVERLIGHT || PocketPC || NET20 || NETFX_CORE)
4461
public struct StructISerializable : ISerializable
4463
private string _name;
4465
public StructISerializable(SerializationInfo info, StreamingContext context)
4467
_name = info.GetString("Name");
4473
get { return _name; }
4474
set { _name = value; }
4477
public void GetObjectData(SerializationInfo info, StreamingContext context)
4479
info.AddValue("Name", _name);
4484
public class NullableStructPropertyClass
4486
private StructISerializable _foo1;
4487
private StructISerializable? _foo2;
4490
public StructISerializable Foo1
4492
get { return _foo1; }
4493
set { _foo1 = value; }
4497
public StructISerializable? Foo2
4499
get { return _foo2; }
4500
set { _foo2 = value; }
4505
public void DeserializeNullableStruct()
4507
NullableStructPropertyClass nullableStructPropertyClass = new NullableStructPropertyClass();
4508
nullableStructPropertyClass.Foo1 = new StructISerializable() { Name = "foo 1" };
4509
nullableStructPropertyClass.Foo2 = new StructISerializable() { Name = "foo 2" };
4511
NullableStructPropertyClass barWithNull = new NullableStructPropertyClass();
4512
barWithNull.Foo1 = new StructISerializable() { Name = "foo 1" };
4513
barWithNull.Foo2 = null;
4515
//throws error on deserialization because bar1.Foo2 is of type Foo?
4516
string s = JsonConvert.SerializeObject(nullableStructPropertyClass);
4517
NullableStructPropertyClass deserialized = deserialize(s);
4518
Assert.AreEqual(deserialized.Foo1.Name, "foo 1");
4519
Assert.AreEqual(deserialized.Foo2.Value.Name, "foo 2");
4521
//no error Foo2 is null
4522
s = JsonConvert.SerializeObject(barWithNull);
4523
deserialized = deserialize(s);
4524
Assert.AreEqual(deserialized.Foo1.Name, "foo 1");
4525
Assert.AreEqual(deserialized.Foo2, null);
4529
private static NullableStructPropertyClass deserialize(string serStr)
4531
return JsonConvert.DeserializeObject<NullableStructPropertyClass>(
4533
new JsonSerializerSettings
4535
NullValueHandling = NullValueHandling.Ignore,
4536
MissingMemberHandling = MissingMemberHandling.Ignore
4541
public class Response
4543
public string Name { get; set; }
4544
public JToken Data { get; set; }
4548
public void DeserializeJToken()
4550
Response response = new Response
4553
Data = new JObject(new JProperty("First", "Value1"), new JProperty("Second", "Value2"))
4556
string json = JsonConvert.SerializeObject(response, Formatting.Indented);
4558
Response deserializedResponse = JsonConvert.DeserializeObject<Response>(json);
4560
Assert.AreEqual("Success", deserializedResponse.Name);
4561
Assert.IsTrue(deserializedResponse.Data.DeepEquals(response.Data));
4564
public abstract class Test<T>
4566
public abstract T Value { get; set; }
4569
[JsonObject(MemberSerialization.OptIn)]
4570
public class DecimalTest : Test<decimal>
4572
protected DecimalTest()
4576
public DecimalTest(decimal val)
4582
public override decimal Value { get; set; }
4586
public void OnError()
4588
var data = new DecimalTest(decimal.MinValue);
4589
var json = JsonConvert.SerializeObject(data);
4590
var obj = JsonConvert.DeserializeObject<DecimalTest>(json);
4592
Assert.AreEqual(decimal.MinValue, obj.Value);
4595
public class NonPublicConstructorWithJsonConstructor
4597
public string Value { get; private set; }
4598
public string Constructor { get; private set; }
4601
private NonPublicConstructorWithJsonConstructor()
4603
Constructor = "NonPublic";
4606
public NonPublicConstructorWithJsonConstructor(string value)
4609
Constructor = "Public Paramatized";
4614
public void NonPublicConstructorWithJsonConstructorTest()
4616
NonPublicConstructorWithJsonConstructor c = JsonConvert.DeserializeObject<NonPublicConstructorWithJsonConstructor>("{}");
4617
Assert.AreEqual("NonPublic", c.Constructor);
4620
public class PublicConstructorOverridenByJsonConstructor
4622
public string Value { get; private set; }
4623
public string Constructor { get; private set; }
4625
public PublicConstructorOverridenByJsonConstructor()
4627
Constructor = "NonPublic";
4631
public PublicConstructorOverridenByJsonConstructor(string value)
4634
Constructor = "Public Paramatized";
4639
public void PublicConstructorOverridenByJsonConstructorTest()
4641
PublicConstructorOverridenByJsonConstructor c = JsonConvert.DeserializeObject<PublicConstructorOverridenByJsonConstructor>("{Value:'value!'}");
4642
Assert.AreEqual("Public Paramatized", c.Constructor);
4643
Assert.AreEqual("value!", c.Value);
4646
public class MultipleParamatrizedConstructorsJsonConstructor
4648
public string Value { get; private set; }
4649
public int Age { get; private set; }
4650
public string Constructor { get; private set; }
4652
public MultipleParamatrizedConstructorsJsonConstructor(string value)
4655
Constructor = "Public Paramatized 1";
4659
public MultipleParamatrizedConstructorsJsonConstructor(string value, int age)
4663
Constructor = "Public Paramatized 2";
4668
public void MultipleParamatrizedConstructorsJsonConstructorTest()
4670
MultipleParamatrizedConstructorsJsonConstructor c = JsonConvert.DeserializeObject<MultipleParamatrizedConstructorsJsonConstructor>("{Value:'value!', Age:1}");
4671
Assert.AreEqual("Public Paramatized 2", c.Constructor);
4672
Assert.AreEqual("value!", c.Value);
4673
Assert.AreEqual(1, c.Age);
4676
public class EnumerableClass
4678
public IEnumerable<string> Enumerable { get; set; }
4682
public void DeserializeEnumerable()
4684
EnumerableClass c = new EnumerableClass
4686
Enumerable = new List<string> { "One", "Two", "Three" }
4689
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
4699
EnumerableClass c2 = JsonConvert.DeserializeObject<EnumerableClass>(json);
4701
Assert.AreEqual("One", c2.Enumerable.ElementAt(0));
4702
Assert.AreEqual("Two", c2.Enumerable.ElementAt(1));
4703
Assert.AreEqual("Three", c2.Enumerable.ElementAt(2));
4706
[JsonObject(MemberSerialization.OptIn)]
4707
public class ItemBase
4710
public string Name { get; set; }
4713
public class ComplexItem : ItemBase
4715
public Stream Source { get; set; }
4719
public void SerializeAttributesOnBase()
4721
ComplexItem i = new ComplexItem();
4723
string json = JsonConvert.SerializeObject(i, Formatting.Indented);
4730
public class DeserializeStringConvert
4732
public string Name { get; set; }
4733
public int Age { get; set; }
4734
public double Height { get; set; }
4735
public decimal Price { get; set; }
4739
public void DeserializeStringEnglish()
4742
'Name': 'James Hughes',
4748
DeserializeStringConvert p = JsonConvert.DeserializeObject<DeserializeStringConvert>(json);
4749
Assert.AreEqual(40, p.Age);
4750
Assert.AreEqual(44.4, p.Height);
4751
Assert.AreEqual(4m, p.Price);
4755
public void DeserializeNullDateTimeValueTest()
4757
ExceptionAssert.Throws<JsonSerializationException>(
4758
"Error converting value {null} to type 'System.DateTime'. Path '', line 1, position 4.",
4761
JsonConvert.DeserializeObject("null", typeof(DateTime));
4766
public void DeserializeNullNullableDateTimeValueTest()
4768
object dateTime = JsonConvert.DeserializeObject("null", typeof(DateTime?));
4770
Assert.IsNull(dateTime);
4774
public void MultiIndexSuperTest()
4776
MultiIndexSuper e = new MultiIndexSuper();
4778
string json = JsonConvert.SerializeObject(e, Formatting.Indented);
4780
Assert.AreEqual(@"{}", json);
4783
public class MultiIndexSuper : MultiIndexBase
4788
public abstract class MultiIndexBase
4790
protected internal object this[string propertyName]
4792
get { return null; }
4796
protected internal object this[object property]
4798
get { return null; }
4803
public class CommentTestClass
4805
public bool Indexed { get; set; }
4806
public int StartYear { get; set; }
4807
public IList<decimal> Values { get; set; }
4811
public void CommentTestClassTest()
4813
string json = @"{""indexed"":true, ""startYear"":1939, ""values"":
4814
[ 3000, /* 1940-1949 */
4815
3000, 3600, 3600, 3600, 3600, 4200, 4200, 4200, 4200, 4800, /* 1950-1959 */
4816
4800, 4800, 4800, 4800, 4800, 4800, 6600, 6600, 7800, 7800, /* 1960-1969 */
4817
7800, 7800, 9000, 10800, 13200, 14100, 15300, 16500, 17700, 22900, /* 1970-1979 */
4818
25900, 29700, 32400, 35700, 37800, 39600, 42000, 43800, 45000, 48000, /* 1980-1989 */
4819
51300, 53400, 55500, 57600, 60600, 61200, 62700, 65400, 68400, 72600, /* 1990-1999 */
4820
76200, 80400, 84900, 87000, 87900, 90000, 94200, 97500, 102000, 106800, /* 2000-2009 */
4821
106800, 106800] /* 2010-2011 */
4824
CommentTestClass commentTestClass = JsonConvert.DeserializeObject<CommentTestClass>(json);
4826
Assert.AreEqual(true, commentTestClass.Indexed);
4827
Assert.AreEqual(1939, commentTestClass.StartYear);
4828
Assert.AreEqual(63, commentTestClass.Values.Count);
4831
private class DTOWithParameterisedConstructor
4833
public DTOWithParameterisedConstructor(string A)
4839
public string A { get; set; }
4840
public int? B { get; set; }
4843
private class DTOWithoutParameterisedConstructor
4845
public DTOWithoutParameterisedConstructor()
4850
public string A { get; set; }
4851
public int? B { get; set; }
4855
public void PopulationBehaviourForOmittedPropertiesIsTheSameForParameterisedConstructorAsForDefaultConstructor()
4857
string json = @"{A:""Test""}";
4859
var withoutParameterisedConstructor = JsonConvert.DeserializeObject<DTOWithoutParameterisedConstructor>(json);
4860
var withParameterisedConstructor = JsonConvert.DeserializeObject<DTOWithParameterisedConstructor>(json);
4861
Assert.AreEqual(withoutParameterisedConstructor.B, withParameterisedConstructor.B);
4864
public class EnumerableArrayPropertyClass
4866
public IEnumerable<int> Numbers
4870
return new[] { 1, 2, 3 }; //fails
4871
//return new List<int>(new[] { 1, 2, 3 }); //works
4877
public void SkipPopulatingArrayPropertyClass()
4879
string json = JsonConvert.SerializeObject(new EnumerableArrayPropertyClass());
4880
JsonConvert.DeserializeObject<EnumerableArrayPropertyClass>(json);
4885
public class BaseDataContract
4887
[DataMember(Name = "virtualMember")]
4888
public virtual string VirtualMember { get; set; }
4890
[DataMember(Name = "nonVirtualMember")]
4891
public string NonVirtualMember { get; set; }
4894
public class ChildDataContract : BaseDataContract
4896
public override string VirtualMember { get; set; }
4897
public string NewMember { get; set; }
4901
public void ChildDataContractTest()
4903
ChildDataContract cc = new ChildDataContract
4905
VirtualMember = "VirtualMember!",
4906
NonVirtualMember = "NonVirtualMember!"
4909
string result = JsonConvert.SerializeObject(cc);
4910
Assert.AreEqual(@"{""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
4914
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
4915
public class BaseObject
4917
[JsonProperty(PropertyName = "virtualMember")]
4918
public virtual string VirtualMember { get; set; }
4920
[JsonProperty(PropertyName = "nonVirtualMember")]
4921
public string NonVirtualMember { get; set; }
4924
public class ChildObject : BaseObject
4926
public override string VirtualMember { get; set; }
4927
public string NewMember { get; set; }
4930
public class ChildWithDifferentOverrideObject : BaseObject
4932
[JsonProperty(PropertyName = "differentVirtualMember")]
4933
public override string VirtualMember { get; set; }
4937
public void ChildObjectTest()
4939
ChildObject cc = new ChildObject
4941
VirtualMember = "VirtualMember!",
4942
NonVirtualMember = "NonVirtualMember!"
4945
string result = JsonConvert.SerializeObject(cc);
4946
Assert.AreEqual(@"{""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
4950
public void ChildWithDifferentOverrideObjectTest()
4952
ChildWithDifferentOverrideObject cc = new ChildWithDifferentOverrideObject
4954
VirtualMember = "VirtualMember!",
4955
NonVirtualMember = "NonVirtualMember!"
4958
string result = JsonConvert.SerializeObject(cc);
4959
Assert.AreEqual(@"{""differentVirtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
4962
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
4963
public interface IInterfaceObject
4965
[JsonProperty(PropertyName = "virtualMember")]
4966
[JsonConverter(typeof(IsoDateTimeConverter))]
4967
DateTime InterfaceMember { get; set; }
4970
public class ImplementInterfaceObject : IInterfaceObject
4972
public DateTime InterfaceMember { get; set; }
4973
public string NewMember { get; set; }
4975
[JsonProperty(PropertyName = "newMemberWithProperty")]
4976
public string NewMemberWithProperty { get; set; }
4980
public void ImplementInterfaceObjectTest()
4982
ImplementInterfaceObject cc = new ImplementInterfaceObject
4984
InterfaceMember = new DateTime(2010, 12, 31, 0, 0, 0, DateTimeKind.Utc),
4985
NewMember = "NewMember!"
4988
string result = JsonConvert.SerializeObject(cc, Formatting.Indented);
4991
""virtualMember"": ""2010-12-31T00:00:00Z"",
4992
""newMemberWithProperty"": null
4996
public class NonDefaultConstructorWithReadOnlyCollectionProperty
4998
public string Title { get; set; }
4999
public IList<string> Categories { get; private set; }
5001
public NonDefaultConstructorWithReadOnlyCollectionProperty(string title)
5004
Categories = new List<string>();
5009
public void NonDefaultConstructorWithReadOnlyCollectionPropertyTest()
5011
NonDefaultConstructorWithReadOnlyCollectionProperty c1 = new NonDefaultConstructorWithReadOnlyCollectionProperty("blah");
5012
c1.Categories.Add("one");
5013
c1.Categories.Add("two");
5015
string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
5017
""Title"": ""blah"",
5024
NonDefaultConstructorWithReadOnlyCollectionProperty c2 = JsonConvert.DeserializeObject<NonDefaultConstructorWithReadOnlyCollectionProperty>(json);
5025
Assert.AreEqual(c1.Title, c2.Title);
5026
Assert.AreEqual(c1.Categories.Count, c2.Categories.Count);
5027
Assert.AreEqual("one", c2.Categories[0]);
5028
Assert.AreEqual("two", c2.Categories[1]);
5031
public class NonDefaultConstructorWithReadOnlyDictionaryProperty
5033
public string Title { get; set; }
5034
public IDictionary<string, int> Categories { get; private set; }
5036
public NonDefaultConstructorWithReadOnlyDictionaryProperty(string title)
5039
Categories = new Dictionary<string, int>();
5044
public void NonDefaultConstructorWithReadOnlyDictionaryPropertyTest()
5046
NonDefaultConstructorWithReadOnlyDictionaryProperty c1 = new NonDefaultConstructorWithReadOnlyDictionaryProperty("blah");
5047
c1.Categories.Add("one", 1);
5048
c1.Categories.Add("two", 2);
5050
string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
5052
""Title"": ""blah"",
5059
NonDefaultConstructorWithReadOnlyDictionaryProperty c2 = JsonConvert.DeserializeObject<NonDefaultConstructorWithReadOnlyDictionaryProperty>(json);
5060
Assert.AreEqual(c1.Title, c2.Title);
5061
Assert.AreEqual(c1.Categories.Count, c2.Categories.Count);
5062
Assert.AreEqual(1, c2.Categories["one"]);
5063
Assert.AreEqual(2, c2.Categories["two"]);
5066
[JsonObject(MemberSerialization.OptIn)]
5067
public class ClassAttributeBase
5070
public string BaseClassValue { get; set; }
5073
public class ClassAttributeDerived : ClassAttributeBase
5076
public string DerivedClassValue { get; set; }
5078
public string NonSerialized { get; set; }
5081
public class CollectionClassAttributeDerived : ClassAttributeBase, ICollection<object>
5084
public string CollectionDerivedClassValue { get; set; }
5086
public void Add(object item)
5088
throw new NotImplementedException();
5093
throw new NotImplementedException();
5096
public bool Contains(object item)
5098
throw new NotImplementedException();
5101
public void CopyTo(object[] array, int arrayIndex)
5103
throw new NotImplementedException();
5108
get { throw new NotImplementedException(); }
5111
public bool IsReadOnly
5113
get { throw new NotImplementedException(); }
5116
public bool Remove(object item)
5118
throw new NotImplementedException();
5121
public IEnumerator<object> GetEnumerator()
5123
throw new NotImplementedException();
5126
IEnumerator IEnumerable.GetEnumerator()
5128
throw new NotImplementedException();
5133
public void ClassAttributesInheritance()
5135
string json = JsonConvert.SerializeObject(new ClassAttributeDerived
5137
BaseClassValue = "BaseClassValue!",
5138
DerivedClassValue = "DerivedClassValue!",
5139
NonSerialized = "NonSerialized!"
5140
}, Formatting.Indented);
5143
""DerivedClassValue"": ""DerivedClassValue!"",
5144
""BaseClassValue"": ""BaseClassValue!""
5147
json = JsonConvert.SerializeObject(new CollectionClassAttributeDerived
5149
BaseClassValue = "BaseClassValue!",
5150
CollectionDerivedClassValue = "CollectionDerivedClassValue!"
5151
}, Formatting.Indented);
5154
""CollectionDerivedClassValue"": ""CollectionDerivedClassValue!"",
5155
""BaseClassValue"": ""BaseClassValue!""
5159
public class PrivateMembersClassWithAttributes
5161
public PrivateMembersClassWithAttributes(string privateString, string internalString, string readonlyString)
5163
_privateString = privateString;
5164
_readonlyString = readonlyString;
5165
_internalString = internalString;
5168
public PrivateMembersClassWithAttributes()
5170
_readonlyString = "default!";
5174
private string _privateString;
5176
private readonly string _readonlyString;
5178
internal string _internalString;
5180
public string UseValue()
5182
return _readonlyString;
5187
public void PrivateMembersClassWithAttributesTest()
5189
PrivateMembersClassWithAttributes c1 = new PrivateMembersClassWithAttributes("privateString!", "internalString!", "readonlyString!");
5191
string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
5193
""_privateString"": ""privateString!"",
5194
""_readonlyString"": ""readonlyString!"",
5195
""_internalString"": ""internalString!""
5198
PrivateMembersClassWithAttributes c2 = JsonConvert.DeserializeObject<PrivateMembersClassWithAttributes>(json);
5199
Assert.AreEqual("readonlyString!", c2.UseValue());
5202
public partial class BusRun
5204
public IEnumerable<Nullable<DateTime>> Departures { get; set; }
5205
public Boolean WheelchairAccessible { get; set; }
5209
public void DeserializeGenericEnumerableProperty()
5211
BusRun r = JsonConvert.DeserializeObject<BusRun>("{\"Departures\":[\"\\/Date(1309874148734-0400)\\/\",\"\\/Date(1309874148739-0400)\\/\",null],\"WheelchairAccessible\":true}");
5213
Assert.AreEqual(3, r.Departures.Count());
5214
Assert.IsNotNull(r.Departures.ElementAt(0));
5215
Assert.IsNotNull(r.Departures.ElementAt(1));
5216
Assert.IsNull(r.Departures.ElementAt(2));
5221
public class BaseType
5225
public string zebra;
5229
public class DerivedType : BaseType
5231
[DataMember(Order = 0)]
5233
[DataMember(Order = 1)]
5234
public string parrot;
5237
[DataMember(Order = 3)]
5238
public string antelope;
5241
[JsonProperty(Order = 1)]
5242
public string albatross;
5243
[JsonProperty(Order = -2)]
5244
public string dinosaur;
5248
public void JsonPropertyDataMemberOrder()
5250
DerivedType d = new DerivedType();
5251
string json = JsonConvert.SerializeObject(d, Formatting.Indented);
5260
""albatross"": null,
5266
public class ClassWithException
5268
public IList<Exception> Exceptions { get; set; }
5270
public ClassWithException()
5272
Exceptions = new List<Exception>();
5276
#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE)
5278
public void SerializeException1()
5280
ClassWithException classWithException = new ClassWithException();
5283
throw new Exception("Test Exception");
5285
catch (Exception ex)
5287
classWithException.Exceptions.Add(ex);
5289
string sex = JsonConvert.SerializeObject(classWithException);
5290
ClassWithException dex = JsonConvert.DeserializeObject<ClassWithException>(sex);
5291
Assert.AreEqual(dex.Exceptions[0].ToString(), dex.Exceptions[0].ToString());
5293
sex = JsonConvert.SerializeObject(classWithException, Formatting.Indented);
5295
dex = JsonConvert.DeserializeObject<ClassWithException>(sex); // this fails!
5296
Assert.AreEqual(dex.Exceptions[0].ToString(), dex.Exceptions[0].ToString());
5300
public void DeserializeIDictionary()
5302
IDictionary dictionary = JsonConvert.DeserializeObject<IDictionary>("{'name':'value!'}");
5303
Assert.AreEqual(1, dictionary.Count);
5304
Assert.AreEqual("value!", dictionary["name"]);
5307
public void DeserializeIList()
5309
IList list = JsonConvert.DeserializeObject<IList>("['1', 'two', 'III']");
5310
Assert.AreEqual(3, list.Count);
5313
public void UriGuidTimeSpanTestClassEmptyTest()
5315
UriGuidTimeSpanTestClass c1 = new UriGuidTimeSpanTestClass();
5316
string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
5319
""Guid"": ""00000000-0000-0000-0000-000000000000"",
5320
""NullableGuid"": null,
5321
""TimeSpan"": ""00:00:00"",
5322
""NullableTimeSpan"": null,
5326
UriGuidTimeSpanTestClass c2 = JsonConvert.DeserializeObject<UriGuidTimeSpanTestClass>(json);
5327
Assert.AreEqual(c1.Guid, c2.Guid);
5328
Assert.AreEqual(c1.NullableGuid, c2.NullableGuid);
5329
Assert.AreEqual(c1.TimeSpan, c2.TimeSpan);
5330
Assert.AreEqual(c1.NullableTimeSpan, c2.NullableTimeSpan);
5331
Assert.AreEqual(c1.Uri, c2.Uri);
5334
public void UriGuidTimeSpanTestClassValuesTest()
5336
UriGuidTimeSpanTestClass c1 = new UriGuidTimeSpanTestClass
5338
Guid = new Guid("1924129C-F7E0-40F3-9607-9939C531395A"),
5339
NullableGuid = new Guid("9E9F3ADF-E017-4F72-91E0-617EBE85967D"),
5340
TimeSpan = TimeSpan.FromDays(1),
5341
NullableTimeSpan = TimeSpan.FromHours(1),
5342
Uri = new Uri("http://testuri.com")
5344
string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
5347
""Guid"": ""1924129c-f7e0-40f3-9607-9939c531395a"",
5348
""NullableGuid"": ""9e9f3adf-e017-4f72-91e0-617ebe85967d"",
5349
""TimeSpan"": ""1.00:00:00"",
5350
""NullableTimeSpan"": ""01:00:00"",
5351
""Uri"": ""http://testuri.com/""
5354
UriGuidTimeSpanTestClass c2 = JsonConvert.DeserializeObject<UriGuidTimeSpanTestClass>(json);
5355
Assert.AreEqual(c1.Guid, c2.Guid);
5356
Assert.AreEqual(c1.NullableGuid, c2.NullableGuid);
5357
Assert.AreEqual(c1.TimeSpan, c2.TimeSpan);
5358
Assert.AreEqual(c1.NullableTimeSpan, c2.NullableTimeSpan);
5359
Assert.AreEqual(c1.Uri, c2.Uri);
5363
public void NullableValueGenericDictionary()
5365
IDictionary<string, int?> v1 = new Dictionary<string, int?>
5372
string json = JsonConvert.SerializeObject(v1, Formatting.Indented);
5380
IDictionary<string, int?> v2 = JsonConvert.DeserializeObject<IDictionary<string, int?>>(json);
5381
Assert.AreEqual(3, v2.Count);
5382
Assert.AreEqual(1, v2["First"]);
5383
Assert.AreEqual(null, v2["Second"]);
5384
Assert.AreEqual(3, v2["Third"]);
5388
public void UsingJsonTextWriter()
5390
// The property of the object has to be a number for the cast exception to occure
5391
object o = new { p = 1 };
5393
var json = JObject.FromObject(o);
5395
using (var sw = new StringWriter())
5396
using (var jw = new JsonTextWriter(sw))
5398
jw.WriteToken(json.CreateReader());
5401
string result = sw.ToString();
5402
Assert.AreEqual(@"{""p"":1}", result);
5406
#if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE)
5408
public void DeserializeConcurrentDictionary()
5410
IDictionary<string, Component> components = new Dictionary<string, Component>
5412
{"Key!", new Component()}
5414
GameObject go = new GameObject
5416
Components = new ConcurrentDictionary<string, Component>(components),
5421
string originalJson = JsonConvert.SerializeObject(go, Formatting.Indented);
5431
GameObject newObject = JsonConvert.DeserializeObject<GameObject>(originalJson);
5433
Assert.AreEqual(1, newObject.Components.Count);
5434
Assert.AreEqual("Id!", newObject.Id);
5435
Assert.AreEqual("Name!", newObject.Name);
5440
public void DeserializeKeyValuePairArray()
5442
string json = @"[ { ""Value"": [ ""1"", ""2"" ], ""Key"": ""aaa"", ""BadContent"": [ 0 ] }, { ""Value"": [ ""3"", ""4"" ], ""Key"": ""bbb"" } ]";
5444
IList<KeyValuePair<string, IList<string>>> values = JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json);
5446
Assert.AreEqual(2, values.Count);
5447
Assert.AreEqual("aaa", values[0].Key);
5448
Assert.AreEqual(2, values[0].Value.Count);
5449
Assert.AreEqual("1", values[0].Value[0]);
5450
Assert.AreEqual("2", values[0].Value[1]);
5451
Assert.AreEqual("bbb", values[1].Key);
5452
Assert.AreEqual(2, values[1].Value.Count);
5453
Assert.AreEqual("3", values[1].Value[0]);
5454
Assert.AreEqual("4", values[1].Value[1]);
5458
public void DeserializeNullableKeyValuePairArray()
5460
string json = @"[ { ""Value"": [ ""1"", ""2"" ], ""Key"": ""aaa"", ""BadContent"": [ 0 ] }, null, { ""Value"": [ ""3"", ""4"" ], ""Key"": ""bbb"" } ]";
5462
IList<KeyValuePair<string, IList<string>>?> values = JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>?>>(json);
5464
Assert.AreEqual(3, values.Count);
5465
Assert.AreEqual("aaa", values[0].Value.Key);
5466
Assert.AreEqual(2, values[0].Value.Value.Count);
5467
Assert.AreEqual("1", values[0].Value.Value[0]);
5468
Assert.AreEqual("2", values[0].Value.Value[1]);
5469
Assert.AreEqual(null, values[1]);
5470
Assert.AreEqual("bbb", values[2].Value.Key);
5471
Assert.AreEqual(2, values[2].Value.Value.Count);
5472
Assert.AreEqual("3", values[2].Value.Value[0]);
5473
Assert.AreEqual("4", values[2].Value.Value[1]);
5477
public void DeserializeNullToNonNullableKeyValuePairArray()
5479
string json = @"[ null ]";
5481
ExceptionAssert.Throws<JsonSerializationException>(
5482
"Cannot convert null value to KeyValuePair. Path '[0]', line 1, position 6.",
5485
JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json);
5490
public void SerializeUriWithQuotes()
5492
string input = "http://test.com/%22foo+bar%22";
5493
Uri uri = new Uri(input);
5494
string json = JsonConvert.SerializeObject(uri);
5495
Uri output = JsonConvert.DeserializeObject<Uri>(json);
5497
Assert.AreEqual(uri, output);
5501
public void SerializeUriWithSlashes()
5503
string input = @"http://tes/?a=b\\c&d=e\";
5504
Uri uri = new Uri(input);
5505
string json = JsonConvert.SerializeObject(uri);
5506
Uri output = JsonConvert.DeserializeObject<Uri>(json);
5508
Assert.AreEqual(uri, output);
5512
public void DeserializeByteArrayWithTypeNameHandling()
5514
TestObject test = new TestObject("Test", new byte[] { 72, 63, 62, 71, 92, 55 });
5516
JsonSerializer serializer = new JsonSerializer();
5517
serializer.TypeNameHandling = TypeNameHandling.All;
5520
using (MemoryStream bsonStream = new MemoryStream())
5521
using (JsonWriter bsonWriter = new JsonTextWriter(new StreamWriter(bsonStream)))
5523
serializer.Serialize(bsonWriter, test);
5526
objectBytes = bsonStream.ToArray();
5529
using (MemoryStream bsonStream = new MemoryStream(objectBytes))
5530
using (JsonReader bsonReader = new JsonTextReader(new StreamReader(bsonStream)))
5532
// Get exception here
5533
TestObject newObject = (TestObject)serializer.Deserialize(bsonReader);
5535
Assert.AreEqual("Test", newObject.Name);
5536
CollectionAssert.AreEquivalent(new byte[] { 72, 63, 62, 71, 92, 55 }, newObject.Data);
5540
#if !(SILVERLIGHT || WINDOWS_PHONE || NET20 || NETFX_CORE)
5542
public void DeserializeDecimalsWithCulture()
5544
CultureInfo initialCulture = Thread.CurrentThread.CurrentCulture;
5548
CultureInfo testCulture = CultureInfo.CreateSpecificCulture("nb-NO");
5550
Thread.CurrentThread.CurrentCulture = testCulture;
5551
Thread.CurrentThread.CurrentUICulture = testCulture;
5553
string json = @"{ 'Quantity': '1.5', 'OptionalQuantity': '2.2' }";
5555
DecimalTestClass c = JsonConvert.DeserializeObject<DecimalTestClass>(json);
5557
Assert.AreEqual(1.5m, c.Quantity);
5558
Assert.AreEqual(2.2d, c.OptionalQuantity);
5562
Thread.CurrentThread.CurrentCulture = initialCulture;
5563
Thread.CurrentThread.CurrentUICulture = initialCulture;
5569
public void ReadForTypeHackFixDecimal()
5571
IList<decimal> d1 = new List<decimal> { 1.1m };
5573
string json = JsonConvert.SerializeObject(d1);
5575
IList<decimal> d2 = JsonConvert.DeserializeObject<IList<decimal>>(json);
5577
Assert.AreEqual(d1.Count, d2.Count);
5578
Assert.AreEqual(d1[0], d2[0]);
5582
public void ReadForTypeHackFixDateTimeOffset()
5584
IList<DateTimeOffset?> d1 = new List<DateTimeOffset?> { null };
5586
string json = JsonConvert.SerializeObject(d1);
5588
IList<DateTimeOffset?> d2 = JsonConvert.DeserializeObject<IList<DateTimeOffset?>>(json);
5590
Assert.AreEqual(d1.Count, d2.Count);
5591
Assert.AreEqual(d1[0], d2[0]);
5595
public void ReadForTypeHackFixByteArray()
5597
IList<byte[]> d1 = new List<byte[]> { null };
5599
string json = JsonConvert.SerializeObject(d1);
5601
IList<byte[]> d2 = JsonConvert.DeserializeObject<IList<byte[]>>(json);
5603
Assert.AreEqual(d1.Count, d2.Count);
5604
Assert.AreEqual(d1[0], d2[0]);
5608
public void SerializeInheritanceHierarchyWithDuplicateProperty()
5613
a.no = int.MaxValue;
5615
string json = JsonConvert.SerializeObject(b);
5617
Assert.AreEqual(@"{""no"":true}", json);
5619
Bb b2 = JsonConvert.DeserializeObject<Bb>(json);
5621
Assert.AreEqual(true, b2.no);
5625
public void DeserializeNullInt()
5634
ExceptionAssert.Throws<JsonSerializationException>(
5635
"Error converting value {null} to type 'System.Int32'. Path '[3]', line 5, position 7.",
5638
List<int> numbers = JsonConvert.DeserializeObject<List<int>>(json);
5643
public void SerializeNullableWidgetStruct()
5645
Widget widget = new Widget { Id = new WidgetId { Value = "id" } };
5647
string json = JsonConvert.SerializeObject(widget);
5649
Assert.AreEqual(@"{""Id"":{""Value"":""id""}}", json);
5653
public void DeserializeNullableWidgetStruct()
5655
string json = @"{""Id"":{""Value"":""id""}}";
5657
Widget w = JsonConvert.DeserializeObject<Widget>(json);
5659
Assert.AreEqual(new WidgetId { Value = "id" }, w.Id);
5660
Assert.AreEqual(new WidgetId { Value = "id" }, w.Id.Value);
5661
Assert.AreEqual("id", w.Id.Value.Value);
5665
public void DeserializeBoolInt()
5667
ExceptionAssert.Throws<JsonReaderException>(
5668
"Error reading integer. Unexpected token: Boolean. Path 'PreProperty', line 2, position 22.",
5672
""PreProperty"": true,
5673
""PostProperty"": ""-1""
5676
JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
5681
public void DeserializeUnexpectedEndInt()
5683
ExceptionAssert.Throws<JsonSerializationException>(
5684
"Unexpected end when setting PreProperty's value. Path 'PreProperty', line 2, position 18.",
5690
JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
5695
public void DeserializeNullableGuid()
5697
string json = @"{""Id"":null}";
5698
var c = JsonConvert.DeserializeObject<NullableGuid>(json);
5700
Assert.AreEqual(null, c.Id);
5702
json = @"{""Id"":""d8220a4b-75b1-4b7a-8112-b7bdae956a45""}";
5703
c = JsonConvert.DeserializeObject<NullableGuid>(json);
5705
Assert.AreEqual(new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"), c.Id);
5709
public void DeserializeGuid()
5711
Item expected = new Item()
5713
SourceTypeID = new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"),
5714
BrokerID = new Guid("951663c4-924e-4c86-a57a-7ed737501dbd"),
5715
Latitude = 33.657145,
5716
Longitude = -117.766684,
5717
TimeStamp = new DateTime(2000, 3, 1, 23, 59, 59, DateTimeKind.Utc),
5718
Payload = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
5721
string jsonString = JsonConvert.SerializeObject(expected, Formatting.Indented);
5724
""SourceTypeID"": ""d8220a4b-75b1-4b7a-8112-b7bdae956a45"",
5725
""BrokerID"": ""951663c4-924e-4c86-a57a-7ed737501dbd"",
5726
""Latitude"": 33.657145,
5727
""Longitude"": -117.766684,
5728
""TimeStamp"": ""2000-03-01T23:59:59Z"",
5730
""$type"": ""System.Byte[], mscorlib"",
5731
""$value"": ""AAECAwQFBgcICQ==""
5735
Item actual = JsonConvert.DeserializeObject<Item>(jsonString);
5737
Assert.AreEqual(new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"), actual.SourceTypeID);
5738
Assert.AreEqual(new Guid("951663c4-924e-4c86-a57a-7ed737501dbd"), actual.BrokerID);
5739
byte[] bytes = (byte[])actual.Payload;
5740
CollectionAssert.AreEquivalent((new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }).ToList(), bytes.ToList());
5744
public void DeserializeObjectDictionary()
5746
var serializer = JsonSerializer.Create(new JsonSerializerSettings());
5747
var dict = serializer.Deserialize<Dictionary<string, string>>(new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}")));
5749
Assert.AreEqual("", dict["k1"]);
5750
Assert.AreEqual("v2", dict["k2"]);
5754
public void DeserializeNullableEnum()
5756
string json = JsonConvert.SerializeObject(new WithEnums
5762
Assert.AreEqual(@"{""Id"":7,""NullableEnum"":null}", json);
5764
WithEnums e = JsonConvert.DeserializeObject<WithEnums>(json);
5766
Assert.AreEqual(null, e.NullableEnum);
5768
json = JsonConvert.SerializeObject(new WithEnums
5771
NullableEnum = MyEnum.Value2
5774
Assert.AreEqual(@"{""Id"":7,""NullableEnum"":1}", json);
5776
e = JsonConvert.DeserializeObject<WithEnums>(json);
5778
Assert.AreEqual(MyEnum.Value2, e.NullableEnum);
5782
public void NullableStructWithConverter()
5784
string json = JsonConvert.SerializeObject(new Widget1 { Id = new WidgetId1 { Value = 1234 } });
5786
Assert.AreEqual(@"{""Id"":""1234""}", json);
5788
Widget1 w = JsonConvert.DeserializeObject<Widget1>(@"{""Id"":""1234""}");
5790
Assert.AreEqual(new WidgetId1 { Value = 1234 }, w.Id);
5794
public void SerializeDictionaryStringStringAndStringObject()
5796
var serializer = JsonSerializer.Create(new JsonSerializerSettings());
5797
var dict = serializer.Deserialize<Dictionary<string, string>>(new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}")));
5799
var reader = new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}"));
5800
var dict2 = serializer.Deserialize<Dictionary<string, object>>(reader);
5802
Assert.AreEqual(dict["k1"], dict2["k1"]);
5806
public void DeserializeEmptyStrings()
5808
object v = JsonConvert.DeserializeObject<double?>("");
5811
v = JsonConvert.DeserializeObject<char?>("");
5814
v = JsonConvert.DeserializeObject<int?>("");
5817
v = JsonConvert.DeserializeObject<decimal?>("");
5820
v = JsonConvert.DeserializeObject<DateTime?>("");
5823
v = JsonConvert.DeserializeObject<DateTimeOffset?>("");
5826
v = JsonConvert.DeserializeObject<byte[]>("");
5832
public double Id { get; set; }
5836
public void DeserializeDoubleFromEmptyString()
5838
ExceptionAssert.Throws<JsonSerializationException>(
5839
"No JSON content found and type 'System.Double' is not nullable. Path '', line 0, position 0.",
5842
JsonConvert.DeserializeObject<double>("");
5847
public void DeserializeEnumFromEmptyString()
5849
ExceptionAssert.Throws<JsonSerializationException>(
5850
"No JSON content found and type 'System.StringComparison' is not nullable. Path '', line 0, position 0.",
5853
JsonConvert.DeserializeObject<StringComparison>("");
5858
public void DeserializeInt32FromEmptyString()
5860
ExceptionAssert.Throws<JsonSerializationException>(
5861
"No JSON content found and type 'System.Int32' is not nullable. Path '', line 0, position 0.",
5864
JsonConvert.DeserializeObject<int>("");
5869
public void DeserializeByteArrayFromEmptyString()
5871
byte[] b = JsonConvert.DeserializeObject<byte[]>("");
5876
public void DeserializeDoubleFromNullString()
5878
ExceptionAssert.Throws<ArgumentNullException>(
5879
@"Value cannot be null.
5880
Parameter name: value",
5883
JsonConvert.DeserializeObject<double>(null);
5888
public void DeserializeFromNullString()
5890
ExceptionAssert.Throws<ArgumentNullException>(
5891
@"Value cannot be null.
5892
Parameter name: value",
5895
JsonConvert.DeserializeObject(null);
5901
public void DeserializeIsoDatesWithIsoConverter()
5903
string jsonIsoText =
5904
@"{""Value"":""2012-02-25T19:55:50.6095676+13:00""}";
5906
DateTimeWrapper c = JsonConvert.DeserializeObject<DateTimeWrapper>(jsonIsoText, new IsoDateTimeConverter());
5907
Assert.AreEqual(DateTimeKind.Local, c.Value.Kind);
5912
public void DeserializeUTC()
5914
DateTimeTestClass c =
5915
JsonConvert.DeserializeObject<DateTimeTestClass>(
5916
@"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12Z"",""PostField"":""Post""}",
5917
new JsonSerializerSettings
5919
DateTimeZoneHandling = DateTimeZoneHandling.Local
5922
Assert.AreEqual(new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime(), c.DateTimeField);
5923
Assert.AreEqual(new DateTimeOffset(2008, 12, 12, 12, 12, 12, 0, TimeSpan.Zero), c.DateTimeOffsetField);
5924
Assert.AreEqual("Pre", c.PreField);
5925
Assert.AreEqual("Post", c.PostField);
5927
DateTimeTestClass c2 =
5928
JsonConvert.DeserializeObject<DateTimeTestClass>(
5929
@"{""PreField"":""Pre"",""DateTimeField"":""2008-01-01T01:01:01Z"",""DateTimeOffsetField"":""2008-01-01T01:01:01Z"",""PostField"":""Post""}",
5930
new JsonSerializerSettings
5932
DateTimeZoneHandling = DateTimeZoneHandling.Local
5935
Assert.AreEqual(new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc).ToLocalTime(), c2.DateTimeField);
5936
Assert.AreEqual(new DateTimeOffset(2008, 1, 1, 1, 1, 1, 0, TimeSpan.Zero), c2.DateTimeOffsetField);
5937
Assert.AreEqual("Pre", c2.PreField);
5938
Assert.AreEqual("Post", c2.PostField);
5942
public void NullableDeserializeUTC()
5944
NullableDateTimeTestClass c =
5945
JsonConvert.DeserializeObject<NullableDateTimeTestClass>(
5946
@"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12Z"",""PostField"":""Post""}",
5947
new JsonSerializerSettings
5949
DateTimeZoneHandling = DateTimeZoneHandling.Local
5952
Assert.AreEqual(new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime(), c.DateTimeField);
5953
Assert.AreEqual(new DateTimeOffset(2008, 12, 12, 12, 12, 12, 0, TimeSpan.Zero), c.DateTimeOffsetField);
5954
Assert.AreEqual("Pre", c.PreField);
5955
Assert.AreEqual("Post", c.PostField);
5957
NullableDateTimeTestClass c2 =
5958
JsonConvert.DeserializeObject<NullableDateTimeTestClass>(
5959
@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}");
5961
Assert.AreEqual(null, c2.DateTimeField);
5962
Assert.AreEqual(null, c2.DateTimeOffsetField);
5963
Assert.AreEqual("Pre", c2.PreField);
5964
Assert.AreEqual("Post", c2.PostField);
5968
public void PrivateConstructor()
5970
var person = PersonWithPrivateConstructor.CreatePerson();
5971
person.Name = "John Doe";
5974
var serializedPerson = JsonConvert.SerializeObject(person);
5975
var roundtrippedPerson = JsonConvert.DeserializeObject<PersonWithPrivateConstructor>(serializedPerson);
5977
Assert.AreEqual(person.Name, roundtrippedPerson.Name);
5981
#if !(SILVERLIGHT || NETFX_CORE)
5983
public void MetroBlogPost()
5985
Product product = new Product();
5986
product.Name = "Apple";
5987
product.ExpiryDate = new DateTime(2012, 4, 1);
5988
product.Price = 3.99M;
5989
product.Sizes = new[] { "Small", "Medium", "Large" };
5991
string json = JsonConvert.SerializeObject(product);
5994
// "ExpiryDate": "2012-04-01T00:00:00",
5996
// "Sizes": [ "Small", "Medium", "Large" ]
5999
string metroJson = JsonConvert.SerializeObject(product, new JsonSerializerSettings
6001
ContractResolver = new MetroPropertyNameResolver(),
6002
Converters = { new MetroStringConverter() },
6003
Formatting = Formatting.Indented
6006
"":::NAME:::"": "":::APPLE:::"",
6007
"":::EXPIRYDATE:::"": ""2012-04-01T00:00:00"",
6008
"":::PRICE:::"": 3.99,
6016
// ":::NAME:::": ":::APPLE:::",
6017
// ":::EXPIRYDATE:::": "2012-04-01T00:00:00",
6018
// ":::PRICE:::": 3.99,
6019
// ":::SIZES:::": [ ":::SMALL:::", ":::MEDIUM:::", ":::LARGE:::" ]
6022
Color[] colors = new[] { Color.Blue, Color.Red, Color.Yellow, Color.Green, Color.Black, Color.Brown };
6024
string json2 = JsonConvert.SerializeObject(colors, new JsonSerializerSettings
6026
ContractResolver = new MetroPropertyNameResolver(),
6027
Converters = { new MetroStringConverter(), new MetroColorConverter() },
6028
Formatting = Formatting.Indented
6041
public class MetroColorConverter : JsonConverter
6043
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
6045
Color color = (Color)value;
6046
Color fixedColor = (color == Color.White || color == Color.Black) ? color : Color.Gray;
6048
writer.WriteValue(":::" + fixedColor.ToKnownColor().ToString().ToUpper() + ":::");
6051
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
6053
return Enum.Parse(typeof(Color), reader.Value.ToString());
6056
public override bool CanConvert(Type objectType)
6058
return objectType == typeof(Color);
6063
private class FooBar
6065
public DateTimeOffset Foo { get; set; }
6069
public void TokenFromBson()
6071
MemoryStream ms = new MemoryStream();
6072
BsonWriter writer = new BsonWriter(ms);
6073
writer.WriteStartArray();
6074
writer.WriteValue("2000-01-02T03:04:05+06:00");
6075
writer.WriteEndArray();
6077
byte[] data = ms.ToArray();
6078
BsonReader reader = new BsonReader(new MemoryStream(data))
6080
ReadRootValueAsArray = true
6083
JArray a = (JArray)JArray.ReadFrom(reader);
6084
JValue v = (JValue)a[0];
6085
Console.WriteLine(v.Value.GetType());
6086
Console.WriteLine(a.ToString());
6090
public void ObjectRequiredDeserializeMissing()
6093
IList<string> errors = new List<string>();
6095
EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
6097
errors.Add(e.ErrorContext.Error.Message);
6098
e.ErrorContext.Handled = true;
6101
var o = JsonConvert.DeserializeObject<RequiredObject>(json, new JsonSerializerSettings
6106
Assert.IsNotNull(o);
6107
Assert.AreEqual(4, errors.Count);
6108
Assert.AreEqual("Required property 'NonAttributeProperty' not found in JSON. Path '', line 1, position 2.", errors[0]);
6109
Assert.AreEqual("Required property 'UnsetProperty' not found in JSON. Path '', line 1, position 2.", errors[1]);
6110
Assert.AreEqual("Required property 'AllowNullProperty' not found in JSON. Path '', line 1, position 2.", errors[2]);
6111
Assert.AreEqual("Required property 'AlwaysProperty' not found in JSON. Path '', line 1, position 2.", errors[3]);
6115
public void ObjectRequiredDeserializeNull()
6117
string json = "{'NonAttributeProperty':null,'UnsetProperty':null,'AllowNullProperty':null,'AlwaysProperty':null}";
6118
IList<string> errors = new List<string>();
6120
EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
6122
errors.Add(e.ErrorContext.Error.Message);
6123
e.ErrorContext.Handled = true;
6126
var o = JsonConvert.DeserializeObject<RequiredObject>(json, new JsonSerializerSettings
6131
Assert.IsNotNull(o);
6132
Assert.AreEqual(3, errors.Count);
6133
Assert.AreEqual("Required property 'NonAttributeProperty' expects a value but got null. Path '', line 1, position 97.", errors[0]);
6134
Assert.AreEqual("Required property 'UnsetProperty' expects a value but got null. Path '', line 1, position 97.", errors[1]);
6135
Assert.AreEqual("Required property 'AlwaysProperty' expects a value but got null. Path '', line 1, position 97.", errors[2]);
6139
public void ObjectRequiredSerialize()
6141
IList<string> errors = new List<string>();
6143
EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
6145
errors.Add(e.ErrorContext.Error.Message);
6146
e.ErrorContext.Handled = true;
6149
string json = JsonConvert.SerializeObject(new RequiredObject(), new JsonSerializerSettings
6152
Formatting = Formatting.Indented
6156
""DefaultProperty"": null,
6157
""AllowNullProperty"": null
6160
Assert.AreEqual(3, errors.Count);
6161
Assert.AreEqual("Cannot write a null value for property 'NonAttributeProperty'. Property requires a value. Path ''.", errors[0]);
6162
Assert.AreEqual("Cannot write a null value for property 'UnsetProperty'. Property requires a value. Path ''.", errors[1]);
6163
Assert.AreEqual("Cannot write a null value for property 'AlwaysProperty'. Property requires a value. Path ''.", errors[2]);
6167
public void DeserializeCollectionItemConverter()
6169
PropertyItemConverter c = new PropertyItemConverter
6179
var c2 = JsonConvert.DeserializeObject<PropertyItemConverter>("{'Data':['::ONE::','::TWO::']}");
6181
Assert.IsNotNull(c2);
6182
Assert.AreEqual(2, c2.Data.Count);
6183
Assert.AreEqual("one", c2.Data[0]);
6184
Assert.AreEqual("two", c2.Data[1]);
6188
public void SerializeCollectionItemConverter()
6190
PropertyItemConverter c = new PropertyItemConverter
6200
string json = JsonConvert.SerializeObject(c);
6202
Assert.AreEqual(@"{""Data"":["":::ONE:::"","":::TWO:::"","":::THREE:::""]}", json);
6206
public void DeserializeEmptyJsonString()
6208
string s = (string) new JsonSerializer().Deserialize(new JsonTextReader(new StringReader("''")));
6209
Assert.AreEqual("", s);
6212
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
6214
public void SerializeAndDeserializeWithAttributes()
6216
var testObj = new PersonSerializable() { Name = "John Doe", Age = 28 };
6217
var objDeserialized = this.SerializeAndDeserialize<PersonSerializable>(testObj);
6219
Assert.AreEqual(testObj.Name, objDeserialized.Name);
6220
Assert.AreEqual(0, objDeserialized.Age);
6223
private T SerializeAndDeserialize<T>(T obj)
6226
var json = Serialize(obj);
6227
return Deserialize<T>(json);
6230
private string Serialize<T>(T obj)
6233
var stringWriter = new StringWriter();
6234
var serializer = new Newtonsoft.Json.JsonSerializer();
6235
serializer.ContractResolver = new DefaultContractResolver(false)
6237
IgnoreSerializableAttribute = false
6239
serializer.Serialize(stringWriter, obj);
6241
return stringWriter.ToString();
6244
private T Deserialize<T>(string json)
6247
var jsonReader = new Newtonsoft.Json.JsonTextReader(new StringReader(json));
6248
var serializer = new Newtonsoft.Json.JsonSerializer();
6249
serializer.ContractResolver = new DefaultContractResolver(false)
6251
IgnoreSerializableAttribute = false
6254
return serializer.Deserialize(jsonReader, typeof(T)) as T;
6259
public void PropertyItemConverter()
6263
EventName = "Blackadder III",
6264
Venue = "Gryphon Theatre",
6265
Performances = new List<DateTime>
6267
JsonConvert.ConvertJavaScriptTicksToDateTime(1336458600000),
6268
JsonConvert.ConvertJavaScriptTicksToDateTime(1336545000000),
6269
JsonConvert.ConvertJavaScriptTicksToDateTime(1336636800000)
6273
string json = JsonConvert.SerializeObject(e, Formatting.Indented);
6275
// "EventName": "Blackadder III",
6276
// "Venue": "Gryphon Theatre",
6277
// "Performances": [
6278
// new Date(1336458600000),
6279
// new Date(1336545000000),
6280
// new Date(1336636800000)
6285
""EventName"": ""Blackadder III"",
6286
""Venue"": ""Gryphon Theatre"",
6301
#if !(NET20 || NET35)
6303
public void SerializeDataContractSerializationAttributes()
6305
DataContractSerializationAttributesClass dataContract = new DataContractSerializationAttributesClass
6307
NoAttribute = "Value!",
6308
IgnoreDataMemberAttribute = "Value!",
6309
DataMemberAttribute = "Value!",
6310
IgnoreDataMemberAndDataMemberAttribute = "Value!"
6313
string json = JsonConvert.SerializeObject(dataContract, Formatting.Indented);
6315
""DataMemberAttribute"": ""Value!"",
6316
""IgnoreDataMemberAndDataMemberAttribute"": ""Value!""
6319
PocoDataContractSerializationAttributesClass poco = new PocoDataContractSerializationAttributesClass
6321
NoAttribute = "Value!",
6322
IgnoreDataMemberAttribute = "Value!",
6323
DataMemberAttribute = "Value!",
6324
IgnoreDataMemberAndDataMemberAttribute = "Value!"
6327
json = JsonConvert.SerializeObject(poco, Formatting.Indented);
6329
""NoAttribute"": ""Value!"",
6330
""DataMemberAttribute"": ""Value!""
6336
public void CheckAdditionalContent()
6338
string json = "{one:1}{}";
6340
JsonSerializerSettings settings = new JsonSerializerSettings();
6341
JsonSerializer s = JsonSerializer.Create(settings);
6342
IDictionary<string, int> o = s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json)));
6344
Assert.IsNotNull(o);
6345
Assert.AreEqual(1, o["one"]);
6347
settings.CheckAdditionalContent = true;
6348
s = JsonSerializer.Create(settings);
6349
ExceptionAssert.Throws<JsonReaderException>(
6350
"Additional text encountered after finished reading JSON content: {. Path '', line 1, position 7.",
6353
s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json)));
6357
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
6359
public void DeserializeException()
6361
string json = @"{ ""ClassName"" : ""System.InvalidOperationException"",
6363
""ExceptionMethod"" : ""8\nLogin\nAppBiz, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null\nMyApp.LoginBiz\nMyApp.User Login()"",
6364
""HResult"" : -2146233079,
6366
""InnerException"" : { ""ClassName"" : ""System.Exception"",
6368
""ExceptionMethod"" : null,
6369
""HResult"" : -2146233088,
6371
""InnerException"" : null,
6372
""Message"" : ""Inner exception..."",
6373
""RemoteStackIndex"" : 0,
6374
""RemoteStackTraceString"" : null,
6376
""StackTraceString"" : null,
6377
""WatsonBuckets"" : null
6379
""Message"" : ""Outter exception..."",
6380
""RemoteStackIndex"" : 0,
6381
""RemoteStackTraceString"" : null,
6382
""Source"" : ""AppBiz"",
6383
""StackTraceString"" : "" at MyApp.LoginBiz.Login() in C:\\MyApp\\LoginBiz.cs:line 44\r\n at MyApp.LoginSvc.Login() in C:\\MyApp\\LoginSvc.cs:line 71\r\n at SyncInvokeLogin(Object , Object[] , Object[] )\r\n at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)\r\n at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)"",
6384
""WatsonBuckets"" : null
6387
InvalidOperationException exception = JsonConvert.DeserializeObject<InvalidOperationException>(json);
6388
Assert.IsNotNull(exception);
6389
CustomAssert.IsInstanceOfType(typeof(InvalidOperationException), exception);
6391
Assert.AreEqual("Outter exception...", exception.Message);
6396
public void AdditionalContentAfterFinish()
6398
ExceptionAssert.Throws<JsonException>(
6399
"Additional text found in JSON string after finishing deserializing object.",
6402
string json = "[{},1]";
6404
JsonSerializer serializer = new JsonSerializer();
6405
serializer.CheckAdditionalContent = true;
6407
var reader = new JsonTextReader(new StringReader(json));
6411
serializer.Deserialize(reader, typeof (MyType));
6416
public void DeserializeRelativeUri()
6418
IList<Uri> uris = JsonConvert.DeserializeObject<IList<Uri>>(@"[""http://localhost/path?query#hash""]");
6419
Assert.AreEqual(1, uris.Count);
6420
Assert.AreEqual(new Uri("http://localhost/path?query#hash"), uris[0]);
6422
Uri uri = JsonConvert.DeserializeObject<Uri>(@"""http://localhost/path?query#hash""");
6423
Assert.IsNotNull(uri);
6425
Uri i1 = new Uri("http://localhost/path?query#hash", UriKind.RelativeOrAbsolute);
6426
Uri i2 = new Uri("http://localhost/path?query#hash");
6427
Assert.AreEqual(i1, i2);
6429
uri = JsonConvert.DeserializeObject<Uri>(@"""/path?query#hash""");
6430
Assert.IsNotNull(uri);
6431
Assert.AreEqual(new Uri("/path?query#hash", UriKind.RelativeOrAbsolute), uri);
6434
public class MyConverter : JsonConverter
6436
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
6438
writer.WriteValue("X");
6441
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
6446
public override bool CanConvert(Type objectType)
6454
[JsonProperty(ItemConverterType = typeof(MyConverter))]
6455
public Dictionary<string, object> MyProperty { get; set; }
6459
public void DeserializeDictionaryItemConverter()
6461
var actual = JsonConvert.DeserializeObject<MyType>(@"{ ""MyProperty"":{""Key"":""Y""}}");
6462
Assert.AreEqual("X", actual.MyProperty["Key"]);
6466
public void DeserializeCaseInsensitiveKeyValuePairConverter()
6468
KeyValuePair<int, string> result =
6469
JsonConvert.DeserializeObject<KeyValuePair<int, string>>(
6470
"{key: 123, \"VALUE\": \"test value\"}"
6473
Assert.AreEqual(123, result.Key);
6474
Assert.AreEqual("test value", result.Value);
6478
public void SerializeKeyValuePairConverterWithCamelCase()
6481
JsonConvert.SerializeObject(new KeyValuePair<int, string>(123, "test value"), Formatting.Indented, new JsonSerializerSettings
6483
ContractResolver = new CamelCasePropertyNamesContractResolver()
6488
""value"": ""test value""
6492
[JsonObject(MemberSerialization.Fields)]
6493
public class MyTuple<T1>
6495
private readonly T1 m_Item1;
6497
public MyTuple(T1 item1)
6504
get { return m_Item1; }
6508
[JsonObject(MemberSerialization.Fields)]
6509
public class MyTuplePartial<T1>
6511
private readonly T1 m_Item1;
6513
public MyTuplePartial(T1 item1)
6520
get { return m_Item1; }
6525
public void SerializeCustomTupleWithSerializableAttribute()
6527
var tuple = new MyTuple<int>(500);
6528
var json = JsonConvert.SerializeObject(tuple);
6529
Assert.AreEqual(@"{""m_Item1"":500}", json);
6531
MyTuple<int> obj = null;
6533
Action doStuff = () =>
6535
obj = JsonConvert.DeserializeObject<MyTuple<int>>(json);
6538
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
6540
Assert.AreEqual(500, obj.Item1);
6542
ExceptionAssert.Throws<JsonSerializationException>(
6543
"Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+MyTuple`1[System.Int32]. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'm_Item1', line 1, position 11.",
6550
public void SerializeCustomTupleWithSerializableAttributeInPartialTrust()
6554
JsonTypeReflector.SetFullyTrusted(false);
6556
var tuple = new MyTuplePartial<int>(500);
6557
var json = JsonConvert.SerializeObject(tuple);
6558
Assert.AreEqual(@"{""m_Item1"":500}", json);
6560
ExceptionAssert.Throws<JsonSerializationException>(
6561
"Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+MyTuplePartial`1[System.Int32]. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'm_Item1', line 1, position 11.",
6562
() => JsonConvert.DeserializeObject<MyTuplePartial<int>>(json));
6566
JsonTypeReflector.SetFullyTrusted(true);
6571
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE || NET35 || NET20)
6573
public void SerializeTupleWithSerializableAttribute()
6575
var tuple = Tuple.Create(500);
6576
var json = JsonConvert.SerializeObject(tuple, new JsonSerializerSettings
6578
ContractResolver = new SerializableContractResolver()
6580
Assert.AreEqual(@"{""m_Item1"":500}", json);
6582
var obj = JsonConvert.DeserializeObject<Tuple<int>>(json, new JsonSerializerSettings
6584
ContractResolver = new SerializableContractResolver()
6586
Assert.AreEqual(500, obj.Item1);
6589
public class SerializableContractResolver : DefaultContractResolver
6591
public SerializableContractResolver()
6593
IgnoreSerializableAttribute = false;
6599
public void SerializeArray2D()
6601
Array2D aa = new Array2D();
6602
aa.Before = "Before!";
6603
aa.After = "After!";
6604
aa.Coordinates = new[,] { { 1, 1 }, { 1, 2 }, { 2, 1 }, { 2, 2 } };
6606
string json = JsonConvert.SerializeObject(aa);
6608
Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}", json);
6612
public void SerializeArray3D()
6614
Array3D aa = new Array3D();
6615
aa.Before = "Before!";
6616
aa.After = "After!";
6617
aa.Coordinates = new[, ,] { { { 1, 1, 1 }, { 1, 1, 2 } }, { { 1, 2, 1 }, { 1, 2, 2 } }, { { 2, 1, 1 }, { 2, 1, 2 } }, { { 2, 2, 1 }, { 2, 2, 2 } } };
6619
string json = JsonConvert.SerializeObject(aa);
6621
Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1,2]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],[2,2,2]]],""After"":""After!""}", json);
6625
public void SerializeArray3DWithConverter()
6627
Array3DWithConverter aa = new Array3DWithConverter();
6628
aa.Before = "Before!";
6629
aa.After = "After!";
6630
aa.Coordinates = new[, ,] { { { 1, 1, 1 }, { 1, 1, 2 } }, { { 1, 2, 1 }, { 1, 2, 2 } }, { { 2, 1, 1 }, { 2, 1, 2 } }, { { 2, 2, 1 }, { 2, 2, 2 } } };
6632
string json = JsonConvert.SerializeObject(aa, Formatting.Indented);
6635
""Before"": ""Before!"",
6686
""After"": ""After!""
6691
public void DeserializeArray3DWithConverter()
6694
""Before"": ""Before!"",
6745
""After"": ""After!""
6748
Array3DWithConverter aa = JsonConvert.DeserializeObject<Array3DWithConverter>(json);
6750
Assert.AreEqual("Before!", aa.Before);
6751
Assert.AreEqual("After!", aa.After);
6752
Assert.AreEqual(4, aa.Coordinates.GetLength(0));
6753
Assert.AreEqual(2, aa.Coordinates.GetLength(1));
6754
Assert.AreEqual(3, aa.Coordinates.GetLength(2));
6755
Assert.AreEqual(1, aa.Coordinates[0, 0, 0]);
6756
Assert.AreEqual(2, aa.Coordinates[1, 1, 1]);
6760
public void DeserializeArray2D()
6762
string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}";
6764
Array2D aa = JsonConvert.DeserializeObject<Array2D>(json);
6766
Assert.AreEqual("Before!", aa.Before);
6767
Assert.AreEqual("After!", aa.After);
6768
Assert.AreEqual(4, aa.Coordinates.GetLength(0));
6769
Assert.AreEqual(2, aa.Coordinates.GetLength(1));
6770
Assert.AreEqual(1, aa.Coordinates[0, 0]);
6771
Assert.AreEqual(2, aa.Coordinates[1, 1]);
6773
string after = JsonConvert.SerializeObject(aa);
6775
Assert.AreEqual(json, after);
6779
public void DeserializeArray2D_WithTooManyItems()
6781
string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2,3],[2,1],[2,2]],""After"":""After!""}";
6783
ExceptionAssert.Throws<Exception>(
6784
"Cannot deserialize non-cubical array as multidimensional array.",
6785
() => JsonConvert.DeserializeObject<Array2D>(json));
6789
public void DeserializeArray2D_WithTooFewItems()
6791
string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1],[2,1],[2,2]],""After"":""After!""}";
6793
ExceptionAssert.Throws<Exception>(
6794
"Cannot deserialize non-cubical array as multidimensional array.",
6795
() => JsonConvert.DeserializeObject<Array2D>(json));
6799
public void DeserializeArray3D()
6801
string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1,2]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],[2,2,2]]],""After"":""After!""}";
6803
Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
6805
Assert.AreEqual("Before!", aa.Before);
6806
Assert.AreEqual("After!", aa.After);
6807
Assert.AreEqual(4, aa.Coordinates.GetLength(0));
6808
Assert.AreEqual(2, aa.Coordinates.GetLength(1));
6809
Assert.AreEqual(3, aa.Coordinates.GetLength(2));
6810
Assert.AreEqual(1, aa.Coordinates[0, 0, 0]);
6811
Assert.AreEqual(2, aa.Coordinates[1, 1, 1]);
6813
string after = JsonConvert.SerializeObject(aa);
6815
Assert.AreEqual(json, after);
6819
public void DeserializeArray3D_WithTooManyItems()
6821
string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1,2,1]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],[2,2,2]]],""After"":""After!""}";
6823
ExceptionAssert.Throws<Exception>(
6824
"Cannot deserialize non-cubical array as multidimensional array.",
6825
() => JsonConvert.DeserializeObject<Array3D>(json));
6829
public void DeserializeArray3D_WithBadItems()
6831
string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1,2]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],{}]],""After"":""After!""}";
6833
ExceptionAssert.Throws<JsonSerializationException>(
6834
"Unexpected token when deserializing multidimensional array: StartObject. Path 'Coordinates[3][1]', line 1, position 99.",
6835
() => JsonConvert.DeserializeObject<Array3D>(json));
6839
public void DeserializeArray3D_WithTooFewItems()
6841
string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],[2,2,2]]],""After"":""After!""}";
6843
ExceptionAssert.Throws<Exception>(
6844
"Cannot deserialize non-cubical array as multidimensional array.",
6845
() => JsonConvert.DeserializeObject<Array3D>(json));
6849
public void SerializeEmpty3DArray()
6851
Array3D aa = new Array3D();
6852
aa.Before = "Before!";
6853
aa.After = "After!";
6854
aa.Coordinates = new int[0, 0, 0];
6856
string json = JsonConvert.SerializeObject(aa);
6858
Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[],""After"":""After!""}", json);
6862
public void DeserializeEmpty3DArray()
6864
string json = @"{""Before"":""Before!"",""Coordinates"":[],""After"":""After!""}";
6866
Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
6868
Assert.AreEqual("Before!", aa.Before);
6869
Assert.AreEqual("After!", aa.After);
6870
Assert.AreEqual(0, aa.Coordinates.GetLength(0));
6871
Assert.AreEqual(0, aa.Coordinates.GetLength(1));
6872
Assert.AreEqual(0, aa.Coordinates.GetLength(2));
6874
string after = JsonConvert.SerializeObject(aa);
6876
Assert.AreEqual(json, after);
6880
public void DeserializeIncomplete3DArray()
6882
string json = @"{""Before"":""Before!"",""Coordinates"":[/*hi*/[/*hi*/[1/*hi*/,/*hi*/1/*hi*/,1]/*hi*/,/*hi*/[1,1";
6884
ExceptionAssert.Throws<JsonSerializationException>(
6885
"Unexpected end when deserializing array. Path 'Coordinates[0][1][1]', line 1, position 90.",
6886
() => JsonConvert.DeserializeObject<Array3D>(json));
6890
public void DeserializeIncompleteNotTopLevel3DArray()
6892
string json = @"{""Before"":""Before!"",""Coordinates"":[/*hi*/[/*hi*/";
6894
ExceptionAssert.Throws<JsonSerializationException>(
6895
"Unexpected end when deserializing array. Path 'Coordinates[0]', line 1, position 48.",
6896
() => JsonConvert.DeserializeObject<Array3D>(json));
6900
public void DeserializeNull3DArray()
6902
string json = @"{""Before"":""Before!"",""Coordinates"":null,""After"":""After!""}";
6904
Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
6906
Assert.AreEqual("Before!", aa.Before);
6907
Assert.AreEqual("After!", aa.After);
6908
Assert.AreEqual(null, aa.Coordinates);
6910
string after = JsonConvert.SerializeObject(aa);
6912
Assert.AreEqual(json, after);
6916
public void DeserializeSemiEmpty3DArray()
6918
string json = @"{""Before"":""Before!"",""Coordinates"":[[]],""After"":""After!""}";
6920
Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
6922
Assert.AreEqual("Before!", aa.Before);
6923
Assert.AreEqual("After!", aa.After);
6924
Assert.AreEqual(1, aa.Coordinates.GetLength(0));
6925
Assert.AreEqual(0, aa.Coordinates.GetLength(1));
6926
Assert.AreEqual(0, aa.Coordinates.GetLength(2));
6928
string after = JsonConvert.SerializeObject(aa);
6930
Assert.AreEqual(json, after);
6934
public void SerializeReferenceTracked3DArray()
6936
Event e1 = new Event
6938
EventName = "EventName!"
6940
Event[,] array1 = new [,] { { e1, e1 }, { e1, e1 } };
6941
IList<Event[,]> values1 = new List<Event[,]>
6947
string json = JsonConvert.SerializeObject(values1, new JsonSerializerSettings
6949
PreserveReferencesHandling = PreserveReferencesHandling.All,
6950
Formatting = Formatting.Indented
6962
""EventName"": ""EventName!"",
6964
""Performances"": null
6988
public void SerializeTypeName3DArray()
6990
Event e1 = new Event
6992
EventName = "EventName!"
6994
Event[,] array1 = new[,] { { e1, e1 }, { e1, e1 } };
6995
IList<Event[,]> values1 = new List<Event[,]>
7001
string json = JsonConvert.SerializeObject(values1, new JsonSerializerSettings
7003
TypeNameHandling = TypeNameHandling.All,
7004
Formatting = Formatting.Indented
7008
""$type"": ""System.Collections.Generic.List`1[[Newtonsoft.Json.Tests.Serialization.Event[,], Newtonsoft.Json.Tests]], mscorlib"",
7011
""$type"": ""Newtonsoft.Json.Tests.Serialization.Event[,], Newtonsoft.Json.Tests"",
7015
""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
7016
""EventName"": ""EventName!"",
7018
""Performances"": null
7021
""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
7022
""EventName"": ""EventName!"",
7024
""Performances"": null
7029
""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
7030
""EventName"": ""EventName!"",
7032
""Performances"": null
7035
""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
7036
""EventName"": ""EventName!"",
7038
""Performances"": null
7044
""$type"": ""Newtonsoft.Json.Tests.Serialization.Event[,], Newtonsoft.Json.Tests"",
7048
""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
7049
""EventName"": ""EventName!"",
7051
""Performances"": null
7054
""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
7055
""EventName"": ""EventName!"",
7057
""Performances"": null
7062
""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
7063
""EventName"": ""EventName!"",
7065
""Performances"": null
7068
""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
7069
""EventName"": ""EventName!"",
7071
""Performances"": null
7079
IList<Event[,]> values2 = (IList<Event[,]>)JsonConvert.DeserializeObject(json, new JsonSerializerSettings
7081
TypeNameHandling = TypeNameHandling.All
7084
Assert.AreEqual(2, values2.Count);
7085
Assert.AreEqual("EventName!", values2[0][0, 0].EventName);
7090
public void SerializeWinRTJsonObject()
7092
var o = Windows.Data.Json.JsonObject.Parse(@"{
7095
""DVD read/writer"",
7096
""500 gigabyte hard drive""
7100
string json = JsonConvert.SerializeObject(o, Formatting.Indented);
7103
""DVD read/writer"",
7104
""500 gigabyte hard drive""
7113
public void RoundtripOfDateTimeOffset()
7115
var content = @"{""startDateTime"":""2012-07-19T14:30:00+09:30""}";
7117
var jsonSerializerSettings = new JsonSerializerSettings() {DateFormatHandling = DateFormatHandling.IsoDateFormat, DateParseHandling = DateParseHandling.DateTimeOffset, DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind};
7119
var obj = (JObject)JsonConvert.DeserializeObject(content, jsonSerializerSettings);
7121
var dateTimeOffset = (DateTimeOffset)((JValue) obj["startDateTime"]).Value;
7123
Assert.AreEqual(TimeSpan.FromHours(9.5), dateTimeOffset.Offset);
7124
Assert.AreEqual("07/19/2012 14:30:00 +09:30", dateTimeOffset.ToString(CultureInfo.InvariantCulture));
7129
public class NullableTestClass
7131
public bool? MyNullableBool { get; set; }
7132
public int? MyNullableInteger { get; set; }
7133
public DateTime? MyNullableDateTime { get; set; }
7134
public DateTimeOffset? MyNullableDateTimeOffset { get; set; }
7135
public Decimal? MyNullableDecimal { get; set; }
7139
public void TestStringToNullableDeserialization()
7142
""MyNullableBool"": """",
7143
""MyNullableInteger"": """",
7144
""MyNullableDateTime"": """",
7145
""MyNullableDateTimeOffset"": """",
7146
""MyNullableDecimal"": """"
7149
NullableTestClass c2 = JsonConvert.DeserializeObject<NullableTestClass>(json);
7150
Assert.IsNull(c2.MyNullableBool);
7151
Assert.IsNull(c2.MyNullableInteger);
7152
Assert.IsNull(c2.MyNullableDateTime);
7153
Assert.IsNull(c2.MyNullableDateTimeOffset);
7154
Assert.IsNull(c2.MyNullableDecimal);
7158
#if !(PORTABLE || NET20 || NET35 || WINDOWS_PHONE)
7160
public void HashSetInterface()
7162
ISet<string> s1 = new HashSet<string>(new[] {"1", "two", "III"});
7164
string json = JsonConvert.SerializeObject(s1);
7166
ISet<string> s2 = JsonConvert.DeserializeObject<ISet<string>>(json);
7168
Assert.AreEqual(s1.Count, s2.Count);
7169
foreach (string s in s1)
7171
Assert.IsTrue(s2.Contains(s));
7176
public class NewEmployee : Employee
7178
public int Age { get; set; }
7180
public bool ShouldSerializeName()
7187
public void ShouldSerializeInheritedClassTest()
7189
NewEmployee joe = new NewEmployee();
7190
joe.Name = "Joe Employee";
7193
Employee mike = new Employee();
7194
mike.Name = "Mike Manager";
7195
mike.Manager = mike;
7199
//StringWriter sw = new StringWriter();
7201
//XmlSerializer x = new XmlSerializer(typeof(NewEmployee));
7202
//x.Serialize(sw, joe);
7204
//Console.WriteLine(sw);
7206
//JavaScriptSerializer s = new JavaScriptSerializer();
7207
//Console.WriteLine(s.Serialize(new {html = @"<script>hi</script>; & ! ^ * ( ) ! @ # $ % ^ ' "" - , . / ; : [ { } ] ; ' - _ = + ? ` ~ \ |"}));
7209
string json = JsonConvert.SerializeObject(joe, Formatting.Indented);
7213
""Name"": ""Joe Employee"",
7215
""Name"": ""Mike Manager""
7221
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
7223
public class PersonSerializable
7225
public PersonSerializable()
7228
private string _name = "";
7231
get { return _name; }
7232
set { _name = value; }
7236
private int _age = 0;
7239
get { return _age; }
7240
set { _age = value; }
7247
public string EventName { get; set; }
7248
public string Venue { get; set; }
7250
[JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
7251
public IList<DateTime> Performances { get; set; }
7254
public class PropertyItemConverter
7256
[JsonProperty(ItemConverterType = typeof(MetroStringConverter))]
7257
public IList<string> Data { get; set; }
7260
public class PersonWithPrivateConstructor
7262
private PersonWithPrivateConstructor()
7265
public static PersonWithPrivateConstructor CreatePerson()
7267
return new PersonWithPrivateConstructor();
7270
public string Name { get; set; }
7272
public int Age { get; set; }
7275
public class DateTimeWrapper
7277
public DateTime Value { get; set; }
7280
public class Widget1
7282
public WidgetId1? Id { get; set; }
7285
[JsonConverter(typeof(WidgetIdJsonConverter))]
7286
public struct WidgetId1
7288
public long Value { get; set; }
7291
public class WidgetIdJsonConverter : JsonConverter
7293
public override bool CanConvert(Type objectType)
7295
return objectType == typeof(WidgetId1) || objectType == typeof(WidgetId1?);
7298
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
7300
WidgetId1 id = (WidgetId1)value;
7301
writer.WriteValue(id.Value.ToString());
7304
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
7306
if (reader.TokenType == JsonToken.Null)
7308
return new WidgetId1 { Value = int.Parse(reader.Value.ToString()) };
7320
public class WithEnums
7322
public int Id { get; set; }
7323
public MyEnum? NullableEnum { get; set; }
7328
public Guid SourceTypeID { get; set; }
7329
public Guid BrokerID { get; set; }
7330
public double Latitude { get; set; }
7331
public double Longitude { get; set; }
7332
public DateTime TimeStamp { get; set; }
7333
[JsonProperty(TypeNameHandling = TypeNameHandling.All)]
7334
public object Payload { get; set; }
7337
public class NullableGuid
7339
public Guid? Id { get; set; }
7344
public WidgetId? Id { get; set; }
7347
public struct WidgetId
7349
public string Value { get; set; }
7352
public class DecimalTestClass
7354
public decimal Quantity { get; set; }
7355
public double OptionalQuantity { get; set; }
7358
public class TestObject
7365
public TestObject(string name, byte[] data)
7371
public string Name { get; set; }
7372
public byte[] Data { get; set; }
7375
public class UriGuidTimeSpanTestClass
7377
public Guid Guid { get; set; }
7378
public Guid? NullableGuid { get; set; }
7379
public TimeSpan TimeSpan { get; set; }
7380
public TimeSpan? NullableTimeSpan { get; set; }
7381
public Uri Uri { get; set; }
7389
internal class Bb : Aa
7394
#if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE)
7395
[JsonObject(MemberSerialization.OptIn)]
7396
public class GameObject
7399
public string Id { get; set; }
7402
public string Name { get; set; }
7404
[JsonProperty] public ConcurrentDictionary<string, Component> Components;
7408
Components = new ConcurrentDictionary<string, Component>();
7413
[JsonObject(MemberSerialization.OptIn)]
7414
public class Component
7416
[JsonIgnore] // Ignore circular reference
7417
public GameObject GameObject { get; set; }
7424
[JsonObject(MemberSerialization.OptIn)]
7425
public class TestComponent : Component
7428
public int MyProperty { get; set; }
7430
public TestComponent()
7436
[JsonObject(MemberSerialization.OptIn)]
7437
public class TestComponentSimple
7440
public int MyProperty { get; set; }
7442
public TestComponentSimple()
7447
[JsonObject(ItemRequired = Required.Always)]
7448
public class RequiredObject
7450
public int? NonAttributeProperty { get; set; }
7452
public int? UnsetProperty { get; set; }
7453
[JsonProperty(Required = Required.Default)]
7454
public int? DefaultProperty { get; set; }
7455
[JsonProperty(Required = Required.AllowNull)]
7456
public int? AllowNullProperty { get; set; }
7457
[JsonProperty(Required = Required.Always)]
7458
public int? AlwaysProperty { get; set; }
7461
public class MetroStringConverter : JsonConverter
7463
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
7465
#if !(SILVERLIGHT || NETFX_CORE)
7466
writer.WriteValue(":::" + value.ToString().ToUpper(CultureInfo.InvariantCulture) + ":::");
7468
writer.WriteValue(":::" + value.ToString().ToUpper() + ":::");
7472
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
7474
string s = (string)reader.Value;
7478
#if !(SILVERLIGHT || NETFX_CORE)
7479
return s.ToLower(CultureInfo.InvariantCulture).Trim(new[] { ':' });
7481
return s.ToLower().Trim(new[] { ':' });
7485
public override bool CanConvert(Type objectType)
7487
return objectType == typeof(string);
7491
public class MetroPropertyNameResolver : DefaultContractResolver
7493
protected internal override string ResolvePropertyName(string propertyName)
7495
#if !(SILVERLIGHT || NETFX_CORE)
7496
return ":::" + propertyName.ToUpper(CultureInfo.InvariantCulture) + ":::";
7498
return ":::" + propertyName.ToUpper() + ":::";
7503
#if !(NET20 || NET35)
7505
public class DataContractSerializationAttributesClass
7507
public string NoAttribute { get; set; }
7509
public string IgnoreDataMemberAttribute { get; set; }
7511
public string DataMemberAttribute { get; set; }
7514
public string IgnoreDataMemberAndDataMemberAttribute { get; set; }
7517
public class PocoDataContractSerializationAttributesClass
7519
public string NoAttribute { get; set; }
7521
public string IgnoreDataMemberAttribute { get; set; }
7523
public string DataMemberAttribute { get; set; }
7526
public string IgnoreDataMemberAndDataMemberAttribute { get; set; }
7530
public class Array2D
7532
public string Before { get; set; }
7533
public int[,] Coordinates { get; set; }
7534
public string After { get; set; }
7537
public class Array3D
7539
public string Before { get; set; }
7540
public int[,,] Coordinates { get; set; }
7541
public string After { get; set; }
7544
public class Array3DWithConverter
7546
public string Before { get; set; }
7547
[JsonProperty(ItemConverterType = typeof(IntToFloatConverter))]
7548
public int[, ,] Coordinates { get; set; }
7549
public string After { get; set; }
7552
public class IntToFloatConverter : JsonConverter
7554
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
7556
writer.WriteValue(Convert.ToDouble(value));
7559
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
7561
return Convert.ToInt32(reader.Value);
7564
public override bool CanConvert(Type objectType)
7566
return objectType == typeof (int);
7570
public class ShouldSerializeTestClass
7572
internal bool _shouldSerializeName;
7574
public string Name { get; set; }
7575
public int Age { get; set; }
7577
public void ShouldSerializeAge()
7579
// dummy. should never be used because it doesn't return bool
7582
public bool ShouldSerializeName()
7584
return _shouldSerializeName;
7588
public class SpecifiedTestClass
7590
private bool _nameSpecified;
7592
public string Name { get; set; }
7593
public int Age { get; set; }
7594
public int Weight { get; set; }
7595
public int Height { get; set; }
7596
public int FavoriteNumber { get; set; }
7598
// dummy. should never be used because it isn't of type bool
7600
public long AgeSpecified { get; set; }
7603
public bool NameSpecified
7605
get { return _nameSpecified; }
7606
set { _nameSpecified = value; }
7610
public bool WeightSpecified;
7613
[System.Xml.Serialization.XmlIgnoreAttribute]
7614
public bool HeightSpecified;
7617
public bool FavoriteNumberSpecified
7620
get { return FavoriteNumber != 0; }
b'\\ No newline at end of file'