PageRenderTime 81ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://github.com/buddydvd/Newtonsoft.Json
C# | 6113 lines | 5379 code | 607 blank | 127 comment | 64 complexity | 6af5dbc4728ea9c755b24f51ba98c337 MD5 | raw file
Possible License(s): LGPL-2.1
  1. #region License
  2. // Copyright (c) 2007 James Newton-King
  3. //
  4. // Permission is hereby granted, free of charge, to any person
  5. // obtaining a copy of this software and associated documentation
  6. // files (the "Software"), to deal in the Software without
  7. // restriction, including without limitation the rights to use,
  8. // copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the
  10. // Software is furnished to do so, subject to the following
  11. // conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  18. // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  20. // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21. // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23. // OTHER DEALINGS IN THE SOFTWARE.
  24. #endregion
  25. using System;
  26. #if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE)
  27. using System.Collections.Concurrent;
  28. #endif
  29. using System.Collections.Generic;
  30. #if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE
  31. using System.ComponentModel.DataAnnotations;
  32. using System.Configuration;
  33. using System.Runtime.CompilerServices;
  34. using System.Runtime.Serialization.Formatters;
  35. using System.Threading;
  36. using System.Web.Script.Serialization;
  37. #endif
  38. using System.Text;
  39. #if !NETFX_CORE
  40. using NUnit.Framework;
  41. #else
  42. using Microsoft.VisualStudio.TestTools.UnitTesting;
  43. using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
  44. using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
  45. #endif
  46. using Newtonsoft.Json;
  47. using System.IO;
  48. using System.Collections;
  49. using System.Xml;
  50. using System.Xml.Serialization;
  51. using System.Collections.ObjectModel;
  52. using Newtonsoft.Json.Bson;
  53. using Newtonsoft.Json.Linq;
  54. using Newtonsoft.Json.Converters;
  55. #if !PocketPC && !NET20 && !WINDOWS_PHONE
  56. using System.Runtime.Serialization.Json;
  57. #endif
  58. using Newtonsoft.Json.Serialization;
  59. using Newtonsoft.Json.Tests.TestObjects;
  60. using System.Runtime.Serialization;
  61. using System.Globalization;
  62. using Newtonsoft.Json.Utilities;
  63. using System.Reflection;
  64. #if !NET20 && !SILVERLIGHT
  65. using System.Xml.Linq;
  66. using System.Text.RegularExpressions;
  67. using System.Collections.Specialized;
  68. using System.Linq.Expressions;
  69. #endif
  70. #if !(NET35 || NET20 || WINDOWS_PHONE)
  71. using System.Dynamic;
  72. using System.ComponentModel;
  73. #endif
  74. #if NET20
  75. using Newtonsoft.Json.Utilities.LinqBridge;
  76. #else
  77. using System.Linq;
  78. #endif
  79. #if !(SILVERLIGHT || NETFX_CORE)
  80. using System.Drawing;
  81. #endif
  82. namespace Newtonsoft.Json.Tests.Serialization
  83. {
  84. [TestFixture]
  85. public class JsonSerializerTest : TestFixtureBase
  86. {
  87. [Test]
  88. public void PersonTypedObjectDeserialization()
  89. {
  90. Store store = new Store();
  91. string jsonText = JsonConvert.SerializeObject(store);
  92. Store deserializedStore = (Store) JsonConvert.DeserializeObject(jsonText, typeof (Store));
  93. Assert.AreEqual(store.Establised, deserializedStore.Establised);
  94. Assert.AreEqual(store.product.Count, deserializedStore.product.Count);
  95. Console.WriteLine(jsonText);
  96. }
  97. [Test]
  98. public void TypedObjectDeserialization()
  99. {
  100. Product product = new Product();
  101. product.Name = "Apple";
  102. product.ExpiryDate = new DateTime(2008, 12, 28);
  103. product.Price = 3.99M;
  104. product.Sizes = new string[] {"Small", "Medium", "Large"};
  105. string output = JsonConvert.SerializeObject(product);
  106. //{
  107. // "Name": "Apple",
  108. // "ExpiryDate": "\/Date(1230375600000+1300)\/",
  109. // "Price": 3.99,
  110. // "Sizes": [
  111. // "Small",
  112. // "Medium",
  113. // "Large"
  114. // ]
  115. //}
  116. Product deserializedProduct = (Product) JsonConvert.DeserializeObject(output, typeof (Product));
  117. Assert.AreEqual("Apple", deserializedProduct.Name);
  118. Assert.AreEqual(new DateTime(2008, 12, 28), deserializedProduct.ExpiryDate);
  119. Assert.AreEqual(3.99m, deserializedProduct.Price);
  120. Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
  121. Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
  122. Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
  123. }
  124. //[Test]
  125. //public void Advanced()
  126. //{
  127. // Product product = new Product();
  128. // product.ExpiryDate = new DateTime(2008, 12, 28);
  129. // JsonSerializer serializer = new JsonSerializer();
  130. // serializer.Converters.Add(new JavaScriptDateTimeConverter());
  131. // serializer.NullValueHandling = NullValueHandling.Ignore;
  132. // using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
  133. // using (JsonWriter writer = new JsonTextWriter(sw))
  134. // {
  135. // serializer.Serialize(writer, product);
  136. // // {"ExpiryDate":new Date(1230375600000),"Price":0}
  137. // }
  138. //}
  139. [Test]
  140. public void JsonConvertSerializer()
  141. {
  142. string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
  143. Product p = JsonConvert.DeserializeObject(value, typeof (Product)) as Product;
  144. Assert.AreEqual("Orange", p.Name);
  145. Assert.AreEqual(new DateTime(2010, 1, 24, 12, 0, 0), p.ExpiryDate);
  146. Assert.AreEqual(3.99m, p.Price);
  147. }
  148. [Test]
  149. public void DeserializeJavaScriptDate()
  150. {
  151. DateTime dateValue = new DateTime(2010, 3, 30);
  152. Dictionary<string, object> testDictionary = new Dictionary<string, object>();
  153. testDictionary["date"] = dateValue;
  154. string jsonText = JsonConvert.SerializeObject(testDictionary);
  155. #if !PocketPC && !NET20 && !WINDOWS_PHONE
  156. MemoryStream ms = new MemoryStream();
  157. DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof (Dictionary<string, object>));
  158. serializer.WriteObject(ms, testDictionary);
  159. byte[] data = ms.ToArray();
  160. string output = Encoding.UTF8.GetString(data, 0, data.Length);
  161. #endif
  162. Dictionary<string, object> deserializedDictionary = (Dictionary<string, object>) JsonConvert.DeserializeObject(jsonText, typeof (Dictionary<string, object>));
  163. DateTime deserializedDate = (DateTime) deserializedDictionary["date"];
  164. Assert.AreEqual(dateValue, deserializedDate);
  165. }
  166. [Test]
  167. public void TestMethodExecutorObject()
  168. {
  169. MethodExecutorObject executorObject = new MethodExecutorObject();
  170. executorObject.serverClassName = "BanSubs";
  171. executorObject.serverMethodParams = new object[] {"21321546", "101", "1236", "D:\\1.txt"};
  172. executorObject.clientGetResultFunction = "ClientBanSubsCB";
  173. string output = JsonConvert.SerializeObject(executorObject);
  174. MethodExecutorObject executorObject2 = JsonConvert.DeserializeObject(output, typeof (MethodExecutorObject)) as MethodExecutorObject;
  175. Assert.AreNotSame(executorObject, executorObject2);
  176. Assert.AreEqual(executorObject2.serverClassName, "BanSubs");
  177. Assert.AreEqual(executorObject2.serverMethodParams.Length, 4);
  178. CustomAssert.Contains(executorObject2.serverMethodParams, "101");
  179. Assert.AreEqual(executorObject2.clientGetResultFunction, "ClientBanSubsCB");
  180. }
  181. #if !SILVERLIGHT && !NETFX_CORE
  182. [Test]
  183. public void HashtableDeserialization()
  184. {
  185. string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
  186. Hashtable p = JsonConvert.DeserializeObject(value, typeof (Hashtable)) as Hashtable;
  187. Assert.AreEqual("Orange", p["Name"].ToString());
  188. }
  189. [Test]
  190. public void TypedHashtableDeserialization()
  191. {
  192. string value = @"{""Name"":""Orange"", ""Hash"":{""ExpiryDate"":""01/24/2010 12:00:00"",""UntypedArray"":[""01/24/2010 12:00:00""]}}";
  193. TypedSubHashtable p = JsonConvert.DeserializeObject(value, typeof (TypedSubHashtable)) as TypedSubHashtable;
  194. Assert.AreEqual("01/24/2010 12:00:00", p.Hash["ExpiryDate"].ToString());
  195. Assert.AreEqual(@"[
  196. ""01/24/2010 12:00:00""
  197. ]", p.Hash["UntypedArray"].ToString());
  198. }
  199. #endif
  200. [Test]
  201. public void SerializeDeserializeGetOnlyProperty()
  202. {
  203. string value = JsonConvert.SerializeObject(new GetOnlyPropertyClass());
  204. GetOnlyPropertyClass c = JsonConvert.DeserializeObject<GetOnlyPropertyClass>(value);
  205. Assert.AreEqual(c.Field, "Field");
  206. Assert.AreEqual(c.GetOnlyProperty, "GetOnlyProperty");
  207. }
  208. [Test]
  209. public void SerializeDeserializeSetOnlyProperty()
  210. {
  211. string value = JsonConvert.SerializeObject(new SetOnlyPropertyClass());
  212. SetOnlyPropertyClass c = JsonConvert.DeserializeObject<SetOnlyPropertyClass>(value);
  213. Assert.AreEqual(c.Field, "Field");
  214. }
  215. [Test]
  216. public void JsonIgnoreAttributeTest()
  217. {
  218. string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeTestClass());
  219. Assert.AreEqual(@"{""Field"":0,""Property"":21}", json);
  220. JsonIgnoreAttributeTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeTestClass>(@"{""Field"":99,""Property"":-1,""IgnoredField"":-1,""IgnoredObject"":[1,2,3,4,5]}");
  221. Assert.AreEqual(0, c.IgnoredField);
  222. Assert.AreEqual(99, c.Field);
  223. }
  224. [Test]
  225. public void GoogleSearchAPI()
  226. {
  227. string json = @"{
  228. results:
  229. [
  230. {
  231. GsearchResultClass:""GwebSearch"",
  232. unescapedUrl : ""http://www.google.com/"",
  233. url : ""http://www.google.com/"",
  234. visibleUrl : ""www.google.com"",
  235. cacheUrl :
  236. ""http://www.google.com/search?q=cache:zhool8dxBV4J:www.google.com"",
  237. title : ""Google"",
  238. titleNoFormatting : ""Google"",
  239. content : ""Enables users to search the Web, Usenet, and
  240. images. Features include PageRank, caching and translation of
  241. results, and an option to find similar pages.""
  242. },
  243. {
  244. GsearchResultClass:""GwebSearch"",
  245. unescapedUrl : ""http://news.google.com/"",
  246. url : ""http://news.google.com/"",
  247. visibleUrl : ""news.google.com"",
  248. cacheUrl :
  249. ""http://www.google.com/search?q=cache:Va_XShOz_twJ:news.google.com"",
  250. title : ""Google News"",
  251. titleNoFormatting : ""Google News"",
  252. content : ""Aggregated headlines and a search engine of many of the world's news sources.""
  253. },
  254. {
  255. GsearchResultClass:""GwebSearch"",
  256. unescapedUrl : ""http://groups.google.com/"",
  257. url : ""http://groups.google.com/"",
  258. visibleUrl : ""groups.google.com"",
  259. cacheUrl :
  260. ""http://www.google.com/search?q=cache:x2uPD3hfkn0J:groups.google.com"",
  261. title : ""Google Groups"",
  262. titleNoFormatting : ""Google Groups"",
  263. content : ""Enables users to search and browse the Usenet
  264. archives which consist of over 700 million messages, and post new
  265. comments.""
  266. },
  267. {
  268. GsearchResultClass:""GwebSearch"",
  269. unescapedUrl : ""http://maps.google.com/"",
  270. url : ""http://maps.google.com/"",
  271. visibleUrl : ""maps.google.com"",
  272. cacheUrl :
  273. ""http://www.google.com/search?q=cache:dkf5u2twBXIJ:maps.google.com"",
  274. title : ""Google Maps"",
  275. titleNoFormatting : ""Google Maps"",
  276. content : ""Provides directions, interactive maps, and
  277. satellite/aerial imagery of the United States. Can also search by
  278. keyword such as type of business.""
  279. }
  280. ],
  281. adResults:
  282. [
  283. {
  284. GsearchResultClass:""GwebSearch.ad"",
  285. title : ""Gartner Symposium/ITxpo"",
  286. content1 : ""Meet brilliant Gartner IT analysts"",
  287. content2 : ""20-23 May 2007- Barcelona, Spain"",
  288. url :
  289. ""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="",
  290. impressionUrl :
  291. ""http://www.google.com/uds/css/ad-indicator-on.gif?ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB"",
  292. unescapedUrl :
  293. ""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="",
  294. visibleUrl : ""www.gartner.com""
  295. }
  296. ]
  297. }
  298. ";
  299. object o = JsonConvert.DeserializeObject(json);
  300. string s = string.Empty;
  301. s += s;
  302. }
  303. [Test]
  304. public void TorrentDeserializeTest()
  305. {
  306. string jsonText = @"{
  307. """":"""",
  308. ""label"": [
  309. [""SomeName"",6]
  310. ],
  311. ""torrents"": [
  312. [""192D99A5C943555CB7F00A852821CF6D6DB3008A"",201,""filename.avi"",178311826,1000,178311826,72815250,408,1603,7,121430,""NameOfLabelPrevioslyDefined"",3,6,0,8,128954,-1,0],
  313. ],
  314. ""torrentc"": ""1816000723""
  315. }";
  316. JObject o = (JObject) JsonConvert.DeserializeObject(jsonText);
  317. Assert.AreEqual(4, o.Children().Count());
  318. JToken torrentsArray = (JToken) o["torrents"];
  319. JToken nestedTorrentsArray = (JToken) torrentsArray[0];
  320. Assert.AreEqual(nestedTorrentsArray.Children().Count(), 19);
  321. }
  322. [Test]
  323. public void JsonPropertyClassSerialize()
  324. {
  325. JsonPropertyClass test = new JsonPropertyClass();
  326. test.Pie = "Delicious";
  327. test.SweetCakesCount = int.MaxValue;
  328. string jsonText = JsonConvert.SerializeObject(test);
  329. Assert.AreEqual(@"{""pie"":""Delicious"",""pie1"":""PieChart!"",""sweet_cakes_count"":2147483647}", jsonText);
  330. JsonPropertyClass test2 = JsonConvert.DeserializeObject<JsonPropertyClass>(jsonText);
  331. Assert.AreEqual(test.Pie, test2.Pie);
  332. Assert.AreEqual(test.SweetCakesCount, test2.SweetCakesCount);
  333. }
  334. [Test]
  335. [ExpectedException(typeof (JsonSerializationException)
  336. #if !NETFX_CORE
  337. , ExpectedMessage = @"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name."
  338. #endif
  339. )]
  340. public void BadJsonPropertyClassSerialize()
  341. {
  342. JsonConvert.SerializeObject(new BadJsonPropertyClass());
  343. }
  344. [Test]
  345. public void InheritedListSerialize()
  346. {
  347. Article a1 = new Article("a1");
  348. Article a2 = new Article("a2");
  349. ArticleCollection articles1 = new ArticleCollection();
  350. articles1.Add(a1);
  351. articles1.Add(a2);
  352. string jsonText = JsonConvert.SerializeObject(articles1);
  353. ArticleCollection articles2 = JsonConvert.DeserializeObject<ArticleCollection>(jsonText);
  354. Assert.AreEqual(articles1.Count, articles2.Count);
  355. Assert.AreEqual(articles1[0].Name, articles2[0].Name);
  356. }
  357. [Test]
  358. public void ReadOnlyCollectionSerialize()
  359. {
  360. ReadOnlyCollection<int> r1 = new ReadOnlyCollection<int>(new int[] {0, 1, 2, 3, 4});
  361. string jsonText = JsonConvert.SerializeObject(r1);
  362. ReadOnlyCollection<int> r2 = JsonConvert.DeserializeObject<ReadOnlyCollection<int>>(jsonText);
  363. CollectionAssert.AreEqual(r1, r2);
  364. }
  365. #if !PocketPC && !NET20 && !WINDOWS_PHONE
  366. [Test]
  367. public void Unicode()
  368. {
  369. string json = @"[""PRE\u003cPOST""]";
  370. DataContractJsonSerializer s = new DataContractJsonSerializer(typeof (List<string>));
  371. List<string> dataContractResult = (List<string>) s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
  372. List<string> jsonNetResult = JsonConvert.DeserializeObject<List<string>>(json);
  373. Assert.AreEqual(1, jsonNetResult.Count);
  374. Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
  375. }
  376. [Test]
  377. public void BackslashEqivilence()
  378. {
  379. string json = @"[""vvv\/vvv\tvvv\""vvv\bvvv\nvvv\rvvv\\vvv\fvvv""]";
  380. #if !SILVERLIGHT && !NETFX_CORE
  381. JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
  382. List<string> javaScriptSerializerResult = javaScriptSerializer.Deserialize<List<string>>(json);
  383. #endif
  384. DataContractJsonSerializer s = new DataContractJsonSerializer(typeof (List<string>));
  385. List<string> dataContractResult = (List<string>) s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
  386. List<string> jsonNetResult = JsonConvert.DeserializeObject<List<string>>(json);
  387. Assert.AreEqual(1, jsonNetResult.Count);
  388. Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
  389. #if !SILVERLIGHT && !NETFX_CORE
  390. Assert.AreEqual(javaScriptSerializerResult[0], jsonNetResult[0]);
  391. #endif
  392. }
  393. [Test]
  394. [ExpectedException(typeof (JsonReaderException)
  395. #if !NETFX_CORE
  396. , ExpectedMessage = @"Bad JSON escape sequence: \j. Line 1, position 7."
  397. #endif
  398. )]
  399. public void InvalidBackslash()
  400. {
  401. string json = @"[""vvv\jvvv""]";
  402. JsonConvert.DeserializeObject<List<string>>(json);
  403. }
  404. [Test]
  405. public void DateTimeTest()
  406. {
  407. List<DateTime> testDates = new List<DateTime>
  408. {
  409. new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Local),
  410. new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
  411. new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc),
  412. new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local),
  413. new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
  414. new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc),
  415. };
  416. MemoryStream ms = new MemoryStream();
  417. DataContractJsonSerializer s = new DataContractJsonSerializer(typeof (List<DateTime>));
  418. s.WriteObject(ms, testDates);
  419. ms.Seek(0, SeekOrigin.Begin);
  420. StreamReader sr = new StreamReader(ms);
  421. string expected = sr.ReadToEnd();
  422. string result = JsonConvert.SerializeObject(testDates, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
  423. Assert.AreEqual(expected, result);
  424. }
  425. [Test]
  426. public void DateTimeOffsetIso()
  427. {
  428. List<DateTimeOffset> testDates = new List<DateTimeOffset>
  429. {
  430. new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
  431. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
  432. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
  433. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
  434. };
  435. string result = JsonConvert.SerializeObject(testDates);
  436. 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);
  437. }
  438. [Test]
  439. public void DateTimeOffsetMsAjax()
  440. {
  441. List<DateTimeOffset> testDates = new List<DateTimeOffset>
  442. {
  443. new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
  444. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
  445. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
  446. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
  447. };
  448. string result = JsonConvert.SerializeObject(testDates, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
  449. Assert.AreEqual(@"[""\/Date(-59011455539000+0000)\/"",""\/Date(946688461000+0000)\/"",""\/Date(946641661000+1300)\/"",""\/Date(946701061000-0330)\/""]", result);
  450. }
  451. #endif
  452. [Test]
  453. public void NonStringKeyDictionary()
  454. {
  455. Dictionary<int, int> values = new Dictionary<int, int>();
  456. values.Add(-5, 6);
  457. values.Add(int.MinValue, int.MaxValue);
  458. string json = JsonConvert.SerializeObject(values);
  459. Assert.AreEqual(@"{""-5"":6,""-2147483648"":2147483647}", json);
  460. Dictionary<int, int> newValues = JsonConvert.DeserializeObject<Dictionary<int, int>>(json);
  461. CollectionAssert.AreEqual(values, newValues);
  462. }
  463. [Test]
  464. public void AnonymousObjectSerialization()
  465. {
  466. var anonymous =
  467. new
  468. {
  469. StringValue = "I am a string",
  470. IntValue = int.MaxValue,
  471. NestedAnonymous = new {NestedValue = byte.MaxValue},
  472. NestedArray = new[] {1, 2},
  473. Product = new Product() {Name = "TestProduct"}
  474. };
  475. string json = JsonConvert.SerializeObject(anonymous);
  476. 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);
  477. anonymous = JsonConvert.DeserializeAnonymousType(json, anonymous);
  478. Assert.AreEqual("I am a string", anonymous.StringValue);
  479. Assert.AreEqual(int.MaxValue, anonymous.IntValue);
  480. Assert.AreEqual(255, anonymous.NestedAnonymous.NestedValue);
  481. Assert.AreEqual(2, anonymous.NestedArray.Length);
  482. Assert.AreEqual(1, anonymous.NestedArray[0]);
  483. Assert.AreEqual(2, anonymous.NestedArray[1]);
  484. Assert.AreEqual("TestProduct", anonymous.Product.Name);
  485. }
  486. [Test]
  487. public void CustomCollectionSerialization()
  488. {
  489. ProductCollection collection = new ProductCollection()
  490. {
  491. new Product() {Name = "Test1"},
  492. new Product() {Name = "Test2"},
  493. new Product() {Name = "Test3"}
  494. };
  495. JsonSerializer jsonSerializer = new JsonSerializer();
  496. jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  497. StringWriter sw = new StringWriter();
  498. jsonSerializer.Serialize(sw, collection);
  499. 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}]",
  500. sw.GetStringBuilder().ToString());
  501. ProductCollection collectionNew = (ProductCollection) jsonSerializer.Deserialize(new JsonTextReader(new StringReader(sw.GetStringBuilder().ToString())), typeof (ProductCollection));
  502. CollectionAssert.AreEqual(collection, collectionNew);
  503. }
  504. [Test]
  505. public void SerializeObject()
  506. {
  507. string json = JsonConvert.SerializeObject(new object());
  508. Assert.AreEqual("{}", json);
  509. }
  510. [Test]
  511. public void SerializeNull()
  512. {
  513. string json = JsonConvert.SerializeObject(null);
  514. Assert.AreEqual("null", json);
  515. }
  516. [Test]
  517. public void CanDeserializeIntArrayWhenNotFirstPropertyInJson()
  518. {
  519. string json = "{foo:'hello',bar:[1,2,3]}";
  520. ClassWithArray wibble = JsonConvert.DeserializeObject<ClassWithArray>(json);
  521. Assert.AreEqual("hello", wibble.Foo);
  522. Assert.AreEqual(4, wibble.Bar.Count);
  523. Assert.AreEqual(int.MaxValue, wibble.Bar[0]);
  524. Assert.AreEqual(1, wibble.Bar[1]);
  525. Assert.AreEqual(2, wibble.Bar[2]);
  526. Assert.AreEqual(3, wibble.Bar[3]);
  527. }
  528. [Test]
  529. public void CanDeserializeIntArray_WhenArrayIsFirstPropertyInJson()
  530. {
  531. string json = "{bar:[1,2,3], foo:'hello'}";
  532. ClassWithArray wibble = JsonConvert.DeserializeObject<ClassWithArray>(json);
  533. Assert.AreEqual("hello", wibble.Foo);
  534. Assert.AreEqual(4, wibble.Bar.Count);
  535. Assert.AreEqual(int.MaxValue, wibble.Bar[0]);
  536. Assert.AreEqual(1, wibble.Bar[1]);
  537. Assert.AreEqual(2, wibble.Bar[2]);
  538. Assert.AreEqual(3, wibble.Bar[3]);
  539. }
  540. [Test]
  541. public void ObjectCreationHandlingReplace()
  542. {
  543. string json = "{bar:[1,2,3], foo:'hello'}";
  544. JsonSerializer s = new JsonSerializer();
  545. s.ObjectCreationHandling = ObjectCreationHandling.Replace;
  546. ClassWithArray wibble = (ClassWithArray) s.Deserialize(new StringReader(json), typeof (ClassWithArray));
  547. Assert.AreEqual("hello", wibble.Foo);
  548. Assert.AreEqual(1, wibble.Bar.Count);
  549. }
  550. [Test]
  551. public void CanDeserializeSerializedJson()
  552. {
  553. ClassWithArray wibble = new ClassWithArray();
  554. wibble.Foo = "hello";
  555. wibble.Bar.Add(1);
  556. wibble.Bar.Add(2);
  557. wibble.Bar.Add(3);
  558. string json = JsonConvert.SerializeObject(wibble);
  559. ClassWithArray wibbleOut = JsonConvert.DeserializeObject<ClassWithArray>(json);
  560. Assert.AreEqual("hello", wibbleOut.Foo);
  561. Assert.AreEqual(5, wibbleOut.Bar.Count);
  562. Assert.AreEqual(int.MaxValue, wibbleOut.Bar[0]);
  563. Assert.AreEqual(int.MaxValue, wibbleOut.Bar[1]);
  564. Assert.AreEqual(1, wibbleOut.Bar[2]);
  565. Assert.AreEqual(2, wibbleOut.Bar[3]);
  566. Assert.AreEqual(3, wibbleOut.Bar[4]);
  567. }
  568. [Test]
  569. public void SerializeConverableObjects()
  570. {
  571. string json = JsonConvert.SerializeObject(new ConverableMembers(), Formatting.Indented);
  572. string expected = null;
  573. #if !NETFX_CORE
  574. expected = @"{
  575. ""String"": ""string"",
  576. ""Int32"": 2147483647,
  577. ""UInt32"": 4294967295,
  578. ""Byte"": 255,
  579. ""SByte"": 127,
  580. ""Short"": 32767,
  581. ""UShort"": 65535,
  582. ""Long"": 9223372036854775807,
  583. ""ULong"": 9223372036854775807,
  584. ""Double"": 1.7976931348623157E+308,
  585. ""Float"": 3.40282347E+38,
  586. ""DBNull"": null,
  587. ""Bool"": true,
  588. ""Char"": ""\u0000""
  589. }";
  590. #else
  591. expected = @"{
  592. ""String"": ""string"",
  593. ""Int32"": 2147483647,
  594. ""UInt32"": 4294967295,
  595. ""Byte"": 255,
  596. ""SByte"": 127,
  597. ""Short"": 32767,
  598. ""UShort"": 65535,
  599. ""Long"": 9223372036854775807,
  600. ""ULong"": 9223372036854775807,
  601. ""Double"": 1.7976931348623157E+308,
  602. ""Float"": 3.40282347E+38,
  603. ""Bool"": true,
  604. ""Char"": ""\u0000""
  605. }";
  606. #endif
  607. Assert.AreEqual(expected, json);
  608. ConverableMembers c = JsonConvert.DeserializeObject<ConverableMembers>(json);
  609. Assert.AreEqual("string", c.String);
  610. Assert.AreEqual(double.MaxValue, c.Double);
  611. #if !NETFX_CORE
  612. Assert.AreEqual(DBNull.Value, c.DBNull);
  613. #endif
  614. }
  615. [Test]
  616. public void SerializeStack()
  617. {
  618. Stack<object> s = new Stack<object>();
  619. s.Push(1);
  620. s.Push(2);
  621. s.Push(3);
  622. string json = JsonConvert.SerializeObject(s);
  623. Assert.AreEqual("[3,2,1]", json);
  624. }
  625. [Test]
  626. public void GuidTest()
  627. {
  628. Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
  629. string json = JsonConvert.SerializeObject(new ClassWithGuid {GuidField = guid});
  630. Assert.AreEqual(@"{""GuidField"":""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""}", json);
  631. ClassWithGuid c = JsonConvert.DeserializeObject<ClassWithGuid>(json);
  632. Assert.AreEqual(guid, c.GuidField);
  633. }
  634. [Test]
  635. public void EnumTest()
  636. {
  637. string json = JsonConvert.SerializeObject(StringComparison.CurrentCultureIgnoreCase);
  638. Assert.AreEqual(@"1", json);
  639. StringComparison s = JsonConvert.DeserializeObject<StringComparison>(json);
  640. Assert.AreEqual(StringComparison.CurrentCultureIgnoreCase, s);
  641. }
  642. public class ClassWithTimeSpan
  643. {
  644. public TimeSpan TimeSpanField;
  645. }
  646. [Test]
  647. public void TimeSpanTest()
  648. {
  649. TimeSpan ts = new TimeSpan(00, 23, 59, 1);
  650. string json = JsonConvert.SerializeObject(new ClassWithTimeSpan {TimeSpanField = ts}, Formatting.Indented);
  651. Assert.AreEqual(@"{
  652. ""TimeSpanField"": ""23:59:01""
  653. }", json);
  654. ClassWithTimeSpan c = JsonConvert.DeserializeObject<ClassWithTimeSpan>(json);
  655. Assert.AreEqual(ts, c.TimeSpanField);
  656. }
  657. [Test]
  658. public void JsonIgnoreAttributeOnClassTest()
  659. {
  660. string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeOnClassTestClass());
  661. Assert.AreEqual(@"{""TheField"":0,""Property"":21}", json);
  662. JsonIgnoreAttributeOnClassTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeOnClassTestClass>(@"{""TheField"":99,""Property"":-1,""IgnoredField"":-1}");
  663. Assert.AreEqual(0, c.IgnoredField);
  664. Assert.AreEqual(99, c.Field);
  665. }
  666. #if !SILVERLIGHT && !NETFX_CORE
  667. [Test]
  668. public void SerializeArrayAsArrayList()
  669. {
  670. string jsonText = @"[3, ""somestring"",[1,2,3],{}]";
  671. ArrayList o = JsonConvert.DeserializeObject<ArrayList>(jsonText);
  672. Assert.AreEqual(4, o.Count);
  673. Assert.AreEqual(3, ((JArray) o[2]).Count);
  674. Assert.AreEqual(0, ((JObject) o[3]).Count);
  675. }
  676. #endif
  677. [Test]
  678. public void SerializeMemberGenericList()
  679. {
  680. Name name = new Name("The Idiot in Next To Me");
  681. PhoneNumber p1 = new PhoneNumber("555-1212");
  682. PhoneNumber p2 = new PhoneNumber("444-1212");
  683. name.pNumbers.Add(p1);
  684. name.pNumbers.Add(p2);
  685. string json = JsonConvert.SerializeObject(name, Formatting.Indented);
  686. Assert.AreEqual(@"{
  687. ""personsName"": ""The Idiot in Next To Me"",
  688. ""pNumbers"": [
  689. {
  690. ""phoneNumber"": ""555-1212""
  691. },
  692. {
  693. ""phoneNumber"": ""444-1212""
  694. }
  695. ]
  696. }", json);
  697. Name newName = JsonConvert.DeserializeObject<Name>(json);
  698. Assert.AreEqual("The Idiot in Next To Me", newName.personsName);
  699. // not passed in as part of the constructor but assigned to pNumbers property
  700. Assert.AreEqual(2, newName.pNumbers.Count);
  701. Assert.AreEqual("555-1212", newName.pNumbers[0].phoneNumber);
  702. Assert.AreEqual("444-1212", newName.pNumbers[1].phoneNumber);
  703. }
  704. [Test]
  705. public void ConstructorCaseSensitivity()
  706. {
  707. ConstructorCaseSensitivityClass c = new ConstructorCaseSensitivityClass("param1", "Param1", "Param2");
  708. string json = JsonConvert.SerializeObject(c);
  709. ConstructorCaseSensitivityClass deserialized = JsonConvert.DeserializeObject<ConstructorCaseSensitivityClass>(json);
  710. Assert.AreEqual("param1", deserialized.param1);
  711. Assert.AreEqual("Param1", deserialized.Param1);
  712. Assert.AreEqual("Param2", deserialized.Param2);
  713. }
  714. [Test]
  715. public void SerializerShouldUseClassConverter()
  716. {
  717. ConverterPrecedenceClass c1 = new ConverterPrecedenceClass("!Test!");
  718. string json = JsonConvert.SerializeObject(c1);
  719. Assert.AreEqual(@"[""Class"",""!Test!""]", json);
  720. ConverterPrecedenceClass c2 = JsonConvert.DeserializeObject<ConverterPrecedenceClass>(json);
  721. Assert.AreEqual("!Test!", c2.TestValue);
  722. }
  723. [Test]
  724. public void SerializerShouldUseClassConverterOverArgumentConverter()
  725. {
  726. ConverterPrecedenceClass c1 = new ConverterPrecedenceClass("!Test!");
  727. string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
  728. Assert.AreEqual(@"[""Class"",""!Test!""]", json);
  729. ConverterPrecedenceClass c2 = JsonConvert.DeserializeObject<ConverterPrecedenceClass>(json, new ArgumentConverterPrecedenceClassConverter());
  730. Assert.AreEqual("!Test!", c2.TestValue);
  731. }
  732. [Test]
  733. public void SerializerShouldUseMemberConverter_IsoDate()
  734. {
  735. DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  736. MemberConverterClass m1 = new MemberConverterClass {DefaultConverter = testDate, MemberConverter = testDate};
  737. string json = JsonConvert.SerializeObject(m1);
  738. Assert.AreEqual(@"{""DefaultConverter"":""1970-01-01T00:00:00Z"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  739. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
  740. Assert.AreEqual(testDate, m2.DefaultConverter);
  741. Assert.AreEqual(testDate, m2.MemberConverter);
  742. }
  743. [Test]
  744. public void SerializerShouldUseMemberConverter_MsDate()
  745. {
  746. DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  747. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  748. string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
  749. {
  750. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  751. });
  752. Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  753. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
  754. Assert.AreEqual(testDate, m2.DefaultConverter);
  755. Assert.AreEqual(testDate, m2.MemberConverter);
  756. }
  757. [Test]
  758. public void SerializerShouldUseMemberConverterOverArgumentConverter()
  759. {
  760. DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  761. MemberConverterClass m1 = new MemberConverterClass {DefaultConverter = testDate, MemberConverter = testDate};
  762. string json = JsonConvert.SerializeObject(m1, new JavaScriptDateTimeConverter());
  763. Assert.AreEqual(@"{""DefaultConverter"":new Date(0),""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  764. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json, new JavaScriptDateTimeConverter());
  765. Assert.AreEqual(testDate, m2.DefaultConverter);
  766. Assert.AreEqual(testDate, m2.MemberConverter);
  767. }
  768. [Test]
  769. public void ConverterAttributeExample()
  770. {
  771. DateTime date = Convert.ToDateTime("1970-01-01T00:00:00Z").ToUniversalTime();
  772. MemberConverterClass c = new MemberConverterClass
  773. {
  774. DefaultConverter = date,
  775. MemberConverter = date
  776. };
  777. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  778. Console.WriteLine(json);
  779. //{
  780. // "DefaultConverter": "\/Date(0)\/",
  781. // "MemberConverter": "1970-01-01T00:00:00Z"
  782. //}
  783. }
  784. [Test]
  785. public void SerializerShouldUseMemberConverterOverClassAndArgumentConverter()
  786. {
  787. ClassAndMemberConverterClass c1 = new ClassAndMemberConverterClass();
  788. c1.DefaultConverter = new ConverterPrecedenceClass("DefaultConverterValue");
  789. c1.MemberConverter = new ConverterPrecedenceClass("MemberConverterValue");
  790. string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
  791. Assert.AreEqual(@"{""DefaultConverter"":[""Class"",""DefaultConverterValue""],""MemberConverter"":[""Member"",""MemberConverterValue""]}", json);
  792. ClassAndMemberConverterClass c2 = JsonConvert.DeserializeObject<ClassAndMemberConverterClass>(json, new ArgumentConverterPrecedenceClassConverter());
  793. Assert.AreEqual("DefaultConverterValue", c2.DefaultConverter.TestValue);
  794. Assert.AreEqual("MemberConverterValue", c2.MemberConverter.TestValue);
  795. }
  796. [Test]
  797. public void IncompatibleJsonAttributeShouldThrow()
  798. {
  799. ExceptionAssert.Throws<JsonSerializationException>(
  800. "JsonConverter IsoDateTimeConverter on Newtonsoft.Json.Tests.TestObjects.IncompatibleJsonAttributeClass is not compatible with member type IncompatibleJsonAttributeClass.",
  801. () =>
  802. {
  803. IncompatibleJsonAttributeClass c = new IncompatibleJsonAttributeClass();
  804. JsonConvert.SerializeObject(c);
  805. });
  806. }
  807. [Test]
  808. public void GenericAbstractProperty()
  809. {
  810. string json = JsonConvert.SerializeObject(new GenericImpl());
  811. Assert.AreEqual(@"{""Id"":0}", json);
  812. }
  813. [Test]
  814. public void DeserializeNullable()
  815. {
  816. string json;
  817. json = JsonConvert.SerializeObject((int?) null);
  818. Assert.AreEqual("null", json);
  819. json = JsonConvert.SerializeObject((int?) 1);
  820. Assert.AreEqual("1", json);
  821. }
  822. [Test]
  823. public void SerializeJsonRaw()
  824. {
  825. PersonRaw personRaw = new PersonRaw
  826. {
  827. FirstName = "FirstNameValue",
  828. RawContent = new JRaw("[1,2,3,4,5]"),
  829. LastName = "LastNameValue"
  830. };
  831. string json;
  832. json = JsonConvert.SerializeObject(personRaw);
  833. Assert.AreEqual(@"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}", json);
  834. }
  835. [Test]
  836. public void DeserializeJsonRaw()
  837. {
  838. string json = @"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}";
  839. PersonRaw personRaw = JsonConvert.DeserializeObject<PersonRaw>(json);
  840. Assert.AreEqual("FirstNameValue", personRaw.FirstName);
  841. Assert.AreEqual("[1,2,3,4,5]", personRaw.RawContent.ToString());
  842. Assert.AreEqual("LastNameValue", personRaw.LastName);
  843. }
  844. [Test]
  845. public void DeserializeNullableMember()
  846. {
  847. UserNullable userNullablle = new UserNullable
  848. {
  849. Id = new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"),
  850. FName = "FirstValue",
  851. LName = "LastValue",
  852. RoleId = 5,
  853. NullableRoleId = 6,
  854. NullRoleId = null,
  855. Active = true
  856. };
  857. string json = JsonConvert.SerializeObject(userNullablle);
  858. Assert.AreEqual(@"{""Id"":""ad6205e8-0df4-465d-aea6-8ba18e93a7e7"",""FName"":""FirstValue"",""LName"":""LastValue"",""RoleId"":5,""NullableRoleId"":6,""NullRoleId"":null,""Active"":true}", json);
  859. UserNullable userNullablleDeserialized = JsonConvert.DeserializeObject<UserNullable>(json);
  860. Assert.AreEqual(new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"), userNullablleDeserialized.Id);
  861. Assert.AreEqual("FirstValue", userNullablleDeserialized.FName);
  862. Assert.AreEqual("LastValue", userNullablleDeserialized.LName);
  863. Assert.AreEqual(5, userNullablleDeserialized.RoleId);
  864. Assert.AreEqual(6, userNullablleDeserialized.NullableRoleId);
  865. Assert.AreEqual(null, userNullablleDeserialized.NullRoleId);
  866. Assert.AreEqual(true, userNullablleDeserialized.Active);
  867. }
  868. [Test]
  869. public void DeserializeInt64ToNullableDouble()
  870. {
  871. string json = @"{""Height"":1}";
  872. DoubleClass c = JsonConvert.DeserializeObject<DoubleClass>(json);
  873. Assert.AreEqual(1, c.Height);
  874. }
  875. [Test]
  876. public void SerializeTypeProperty()
  877. {
  878. string boolRef = typeof (bool).AssemblyQualifiedName;
  879. TypeClass typeClass = new TypeClass {TypeProperty = typeof (bool)};
  880. string json = JsonConvert.SerializeObject(typeClass);
  881. Assert.AreEqual(@"{""TypeProperty"":""" + boolRef + @"""}", json);
  882. TypeClass typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
  883. Assert.AreEqual(typeof (bool), typeClass2.TypeProperty);
  884. string jsonSerializerTestRef = typeof (JsonSerializerTest).AssemblyQualifiedName;
  885. typeClass = new TypeClass {TypeProperty = typeof (JsonSerializerTest)};
  886. json = JsonConvert.SerializeObject(typeClass);
  887. Assert.AreEqual(@"{""TypeProperty"":""" + jsonSerializerTestRef + @"""}", json);
  888. typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
  889. Assert.AreEqual(typeof (JsonSerializerTest), typeClass2.TypeProperty);
  890. }
  891. [Test]
  892. public void RequiredMembersClass()
  893. {
  894. RequiredMembersClass c = new RequiredMembersClass()
  895. {
  896. BirthDate = new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc),
  897. FirstName = "Bob",
  898. LastName = "Smith",
  899. MiddleName = "Cosmo"
  900. };
  901. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  902. Assert.AreEqual(@"{
  903. ""FirstName"": ""Bob"",
  904. ""MiddleName"": ""Cosmo"",
  905. ""LastName"": ""Smith"",
  906. ""BirthDate"": ""2000-12-20T10:55:55Z""
  907. }", json);
  908. RequiredMembersClass c2 = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  909. Assert.AreEqual("Bob", c2.FirstName);
  910. Assert.AreEqual(new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc), c2.BirthDate);
  911. }
  912. [Test]
  913. public void DeserializeRequiredMembersClassWithNullValues()
  914. {
  915. string json = @"{
  916. ""FirstName"": ""I can't be null bro!"",
  917. ""MiddleName"": null,
  918. ""LastName"": null,
  919. ""BirthDate"": ""\/Date(977309755000)\/""
  920. }";
  921. RequiredMembersClass c = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  922. Assert.AreEqual("I can't be null bro!", c.FirstName);
  923. Assert.AreEqual(null, c.MiddleName);
  924. Assert.AreEqual(null, c.LastName);
  925. }
  926. [Test]
  927. public void DeserializeRequiredMembersClassNullRequiredValueProperty()
  928. {
  929. ExceptionAssert.Throws<JsonSerializationException>("Required property 'FirstName' expects a value but got null. Line 6, position 2.",
  930. () =>
  931. {
  932. string json = @"{
  933. ""FirstName"": null,
  934. ""MiddleName"": null,
  935. ""LastName"": null,
  936. ""BirthDate"": ""\/Date(977309755000)\/""
  937. }";
  938. JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  939. });
  940. }
  941. [Test]
  942. public void SerializeRequiredMembersClassNullRequiredValueProperty()
  943. {
  944. ExceptionAssert.Throws<JsonSerializationException>("Cannot write a null value for property 'FirstName'. Property requires a value.",
  945. () =>
  946. {
  947. RequiredMembersClass requiredMembersClass = new RequiredMembersClass
  948. {
  949. FirstName = null,
  950. BirthDate = new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc),
  951. LastName = null,
  952. MiddleName = null
  953. };
  954. string json = JsonConvert.SerializeObject(requiredMembersClass);
  955. Console.WriteLine(json);
  956. });
  957. }
  958. [Test]
  959. public void RequiredMembersClassMissingRequiredProperty()
  960. {
  961. ExceptionAssert.Throws<JsonSerializationException>("Required property 'LastName' not found in JSON. Line 3, position 2.",
  962. () =>
  963. {
  964. string json = @"{
  965. ""FirstName"": ""Bob""
  966. }";
  967. JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  968. });
  969. }
  970. [Test]
  971. public void SerializeJaggedArray()
  972. {
  973. JaggedArray aa = new JaggedArray();
  974. aa.Before = "Before!";
  975. aa.After = "After!";
  976. aa.Coordinates = new[] {new[] {1, 1}, new[] {1, 2}, new[] {2, 1}, new[] {2, 2}};
  977. string json = JsonConvert.SerializeObject(aa);
  978. Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}", json);
  979. }
  980. [Test]
  981. public void DeserializeJaggedArray()
  982. {
  983. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}";
  984. JaggedArray aa = JsonConvert.DeserializeObject<JaggedArray>(json);
  985. Assert.AreEqual("Before!", aa.Before);
  986. Assert.AreEqual("After!", aa.After);
  987. Assert.AreEqual(4, aa.Coordinates.Length);
  988. Assert.AreEqual(2, aa.Coordinates[0].Length);
  989. Assert.AreEqual(1, aa.Coordinates[0][0]);
  990. Assert.AreEqual(2, aa.Coordinates[1][1]);
  991. string after = JsonConvert.SerializeObject(aa);
  992. Assert.AreEqual(json, after);
  993. }
  994. [Test]
  995. public void DeserializeGoogleGeoCode()
  996. {
  997. string json = @"{
  998. ""name"": ""1600 Amphitheatre Parkway, Mountain View, CA, USA"",
  999. ""Status"": {
  1000. ""code"": 200,
  1001. ""request"": ""geocode""
  1002. },
  1003. ""Placemark"": [
  1004. {
  1005. ""address"": ""1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"",
  1006. ""AddressDetails"": {
  1007. ""Country"": {
  1008. ""CountryNameCode"": ""US"",
  1009. ""AdministrativeArea"": {
  1010. ""AdministrativeAreaName"": ""CA"",
  1011. ""SubAdministrativeArea"": {
  1012. ""SubAdministrativeAreaName"": ""Santa Clara"",
  1013. ""Locality"": {
  1014. ""LocalityName"": ""Mountain View"",
  1015. ""Thoroughfare"": {
  1016. ""ThoroughfareName"": ""1600 Amphitheatre Pkwy""
  1017. },
  1018. ""PostalCode"": {
  1019. ""PostalCodeNumber"": ""94043""
  1020. }
  1021. }
  1022. }
  1023. }
  1024. },
  1025. ""Accuracy"": 8
  1026. },
  1027. ""Point"": {
  1028. ""coordinates"": [-122.083739, 37.423021, 0]
  1029. }
  1030. }
  1031. ]
  1032. }";
  1033. GoogleMapGeocoderStructure jsonGoogleMapGeocoder = JsonConvert.DeserializeObject<GoogleMapGeocoderStructure>(json);
  1034. }
  1035. [Test]
  1036. [ExpectedException(typeof (JsonSerializationException)
  1037. #if !NETFX_CORE
  1038. , ExpectedMessage = @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantated. Line 1, position 14."
  1039. #endif
  1040. )]
  1041. public void DeserializeInterfaceProperty()
  1042. {
  1043. InterfacePropertyTestClass testClass = new InterfacePropertyTestClass();
  1044. testClass.co = new Co();
  1045. String strFromTest = JsonConvert.SerializeObject(testClass);
  1046. InterfacePropertyTestClass testFromDe = (InterfacePropertyTestClass) JsonConvert.DeserializeObject(strFromTest, typeof (InterfacePropertyTestClass));
  1047. }
  1048. private Person GetPerson()
  1049. {
  1050. Person person = new Person
  1051. {
  1052. Name = "Mike Manager",
  1053. BirthDate = new DateTime(1983, 8, 3, 0, 0, 0, DateTimeKind.Utc),
  1054. Department = "IT",
  1055. LastModified = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc)
  1056. };
  1057. return person;
  1058. }
  1059. [Test]
  1060. public void WriteJsonDates()
  1061. {
  1062. LogEntry entry = new LogEntry
  1063. {
  1064. LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
  1065. Details = "Application started."
  1066. };
  1067. string defaultJson = JsonConvert.SerializeObject(entry);
  1068. // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}
  1069. string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
  1070. // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00.0000000Z"}
  1071. string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
  1072. // {"Details":"Application started.","LogDate":new Date(1234656000000)}
  1073. Console.WriteLine(defaultJson);
  1074. Console.WriteLine(isoJson);
  1075. Console.WriteLine(javascriptJson);
  1076. }
  1077. public void GenericListAndDictionaryInterfaceProperties()
  1078. {
  1079. GenericListAndDictionaryInterfaceProperties o = new GenericListAndDictionaryInterfaceProperties();
  1080. o.IDictionaryProperty = new Dictionary<string, int>
  1081. {
  1082. {"one", 1},
  1083. {"two", 2},
  1084. {"three", 3}
  1085. };
  1086. o.IListProperty = new List<int>
  1087. {
  1088. 1, 2, 3
  1089. };
  1090. o.IEnumerableProperty = new List<int>
  1091. {
  1092. 4, 5, 6
  1093. };
  1094. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  1095. Assert.AreEqual(@"{
  1096. ""IEnumerableProperty"": [
  1097. 4,
  1098. 5,
  1099. 6
  1100. ],
  1101. ""IListProperty"": [
  1102. 1,
  1103. 2,
  1104. 3
  1105. ],
  1106. ""IDictionaryProperty"": {
  1107. ""one"": 1,
  1108. ""two"": 2,
  1109. ""three"": 3
  1110. }
  1111. }", json);
  1112. GenericListAndDictionaryInterfaceProperties deserializedObject = JsonConvert.DeserializeObject<GenericListAndDictionaryInterfaceProperties>(json);
  1113. Assert.IsNotNull(deserializedObject);
  1114. CollectionAssert.AreEqual(o.IListProperty.ToArray(), deserializedObject.IListProperty.ToArray());
  1115. CollectionAssert.AreEqual(o.IEnumerableProperty.ToArray(), deserializedObject.IEnumerableProperty.ToArray());
  1116. CollectionAssert.AreEqual(o.IDictionaryProperty.ToArray(), deserializedObject.IDictionaryProperty.ToArray());
  1117. }
  1118. [Test]
  1119. public void DeserializeBestMatchPropertyCase()
  1120. {
  1121. string json = @"{
  1122. ""firstName"": ""firstName"",
  1123. ""FirstName"": ""FirstName"",
  1124. ""LastName"": ""LastName"",
  1125. ""lastName"": ""lastName"",
  1126. }";
  1127. PropertyCase o = JsonConvert.DeserializeObject<PropertyCase>(json);
  1128. Assert.IsNotNull(o);
  1129. Assert.AreEqual("firstName", o.firstName);
  1130. Assert.AreEqual("FirstName", o.FirstName);
  1131. Assert.AreEqual("LastName", o.LastName);
  1132. Assert.AreEqual("lastName", o.lastName);
  1133. }
  1134. [Test]
  1135. public void DeserializePropertiesOnToNonDefaultConstructor()
  1136. {
  1137. SubKlass i = new SubKlass("my subprop");
  1138. i.SuperProp = "overrided superprop";
  1139. string json = JsonConvert.SerializeObject(i);
  1140. Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", json);
  1141. SubKlass ii = JsonConvert.DeserializeObject<SubKlass>(json);
  1142. string newJson = JsonConvert.SerializeObject(ii);
  1143. Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", newJson);
  1144. }
  1145. [Test]
  1146. public void SerializeJsonPropertyWithHandlingValues()
  1147. {
  1148. JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
  1149. o.DefaultValueHandlingIgnoreProperty = "Default!";
  1150. o.DefaultValueHandlingIncludeProperty = "Default!";
  1151. o.DefaultValueHandlingPopulateProperty = "Default!";
  1152. o.DefaultValueHandlingIgnoreAndPopulateProperty = "Default!";
  1153. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  1154. Assert.AreEqual(@"{
  1155. ""DefaultValueHandlingIncludeProperty"": ""Default!"",
  1156. ""DefaultValueHandlingPopulateProperty"": ""Default!"",
  1157. ""NullValueHandlingIncludeProperty"": null,
  1158. ""ReferenceLoopHandlingErrorProperty"": null,
  1159. ""ReferenceLoopHandlingIgnoreProperty"": null,
  1160. ""ReferenceLoopHandlingSerializeProperty"": null
  1161. }", json);
  1162. json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});
  1163. Assert.AreEqual(@"{
  1164. ""DefaultValueHandlingIncludeProperty"": ""Default!"",
  1165. ""DefaultValueHandlingPopulateProperty"": ""Default!"",
  1166. ""NullValueHandlingIncludeProperty"": null
  1167. }", json);
  1168. }
  1169. [Test]
  1170. public void DeserializeJsonPropertyWithHandlingValues()
  1171. {
  1172. string json = "{}";
  1173. JsonPropertyWithHandlingValues o = JsonConvert.DeserializeObject<JsonPropertyWithHandlingValues>(json);
  1174. Assert.AreEqual("Default!", o.DefaultValueHandlingIgnoreAndPopulateProperty);
  1175. Assert.AreEqual("Default!", o.DefaultValueHandlingPopulateProperty);
  1176. Assert.AreEqual(null, o.DefaultValueHandlingIgnoreProperty);
  1177. Assert.AreEqual(null, o.DefaultValueHandlingIncludeProperty);
  1178. }
  1179. [Test]
  1180. [ExpectedException(typeof (JsonSerializationException))]
  1181. public void JsonPropertyWithHandlingValues_ReferenceLoopError()
  1182. {
  1183. JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
  1184. o.ReferenceLoopHandlingErrorProperty = o;
  1185. JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
  1186. }
  1187. [Test]
  1188. public void PartialClassDeserialize()
  1189. {
  1190. string json = @"{
  1191. ""request"": ""ux.settings.update"",
  1192. ""sid"": ""14c561bd-32a8-457e-b4e5-4bba0832897f"",
  1193. ""uid"": ""30c39065-0f31-de11-9442-001e3786a8ec"",
  1194. ""fidOrder"": [
  1195. ""id"",
  1196. ""andytest_name"",
  1197. ""andytest_age"",
  1198. ""andytest_address"",
  1199. ""andytest_phone"",
  1200. ""date"",
  1201. ""title"",
  1202. ""titleId""
  1203. ],
  1204. ""entityName"": ""Andy Test"",
  1205. ""setting"": ""entity.field.order""
  1206. }";
  1207. RequestOnly r = JsonConvert.DeserializeObject<RequestOnly>(json);
  1208. Assert.AreEqual("ux.settings.update", r.Request);
  1209. NonRequest n = JsonConvert.DeserializeObject<NonRequest>(json);
  1210. Assert.AreEqual(new Guid("14c561bd-32a8-457e-b4e5-4bba0832897f"), n.Sid);
  1211. Assert.AreEqual(new Guid("30c39065-0f31-de11-9442-001e3786a8ec"), n.Uid);
  1212. Assert.AreEqual(8, n.FidOrder.Count);
  1213. Assert.AreEqual("id", n.FidOrder[0]);
  1214. Assert.AreEqual("titleId", n.FidOrder[n.FidOrder.Count - 1]);
  1215. }
  1216. #if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE
  1217. [MetadataType(typeof (OptInClassMetadata))]
  1218. public class OptInClass
  1219. {
  1220. [DataContract]
  1221. public class OptInClassMetadata
  1222. {
  1223. [DataMember]
  1224. public string Name { get; set; }
  1225. [DataMember]
  1226. public int Age { get; set; }
  1227. public string NotIncluded { get; set; }
  1228. }
  1229. public string Name { get; set; }
  1230. public int Age { get; set; }
  1231. public string NotIncluded { get; set; }
  1232. }
  1233. [Test]
  1234. public void OptInClassMetadataSerialization()
  1235. {
  1236. OptInClass optInClass = new OptInClass();
  1237. optInClass.Age = 26;
  1238. optInClass.Name = "James NK";
  1239. optInClass.NotIncluded = "Poor me :(";
  1240. string json = JsonConvert.SerializeObject(optInClass, Formatting.Indented);
  1241. Assert.AreEqual(@"{
  1242. ""Name"": ""James NK"",
  1243. ""Age"": 26
  1244. }", json);
  1245. OptInClass newOptInClass = JsonConvert.DeserializeObject<OptInClass>(@"{
  1246. ""Name"": ""James NK"",
  1247. ""NotIncluded"": ""Ignore me!"",
  1248. ""Age"": 26
  1249. }");
  1250. Assert.AreEqual(26, newOptInClass.Age);
  1251. Assert.AreEqual("James NK", newOptInClass.Name);
  1252. Assert.AreEqual(null, newOptInClass.NotIncluded);
  1253. }
  1254. #endif
  1255. #if !PocketPC && !NET20
  1256. [DataContract]
  1257. public class DataContractPrivateMembers
  1258. {
  1259. public DataContractPrivateMembers()
  1260. {
  1261. }
  1262. public DataContractPrivateMembers(string name, int age, int rank, string title)
  1263. {
  1264. _name = name;
  1265. Age = age;
  1266. Rank = rank;
  1267. Title = title;
  1268. }
  1269. [DataMember] private string _name;
  1270. [DataMember(Name = "_age")]
  1271. private int Age { get; set; }
  1272. [JsonProperty]
  1273. private int Rank { get; set; }
  1274. [JsonProperty(PropertyName = "JsonTitle")]
  1275. [DataMember(Name = "DataTitle")]
  1276. private string Title { get; set; }
  1277. public string NotIncluded { get; set; }
  1278. public override string ToString()
  1279. {
  1280. return "_name: " + _name + ", _age: " + Age + ", Rank: " + Rank + ", JsonTitle: " + Title;
  1281. }
  1282. }
  1283. [Test]
  1284. public void SerializeDataContractPrivateMembers()
  1285. {
  1286. DataContractPrivateMembers c = new DataContractPrivateMembers("Jeff", 26, 10, "Dr");
  1287. c.NotIncluded = "Hi";
  1288. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  1289. Assert.AreEqual(@"{
  1290. ""_name"": ""Jeff"",
  1291. ""_age"": 26,
  1292. ""Rank"": 10,
  1293. ""JsonTitle"": ""Dr""
  1294. }", json);
  1295. DataContractPrivateMembers cc = JsonConvert.DeserializeObject<DataContractPrivateMembers>(json);
  1296. Assert.AreEqual("_name: Jeff, _age: 26, Rank: 10, JsonTitle: Dr", cc.ToString());
  1297. }
  1298. #endif
  1299. [Test]
  1300. public void DeserializeDictionaryInterface()
  1301. {
  1302. string json = @"{
  1303. ""Name"": ""Name!"",
  1304. ""Dictionary"": {
  1305. ""Item"": 11
  1306. }
  1307. }";
  1308. DictionaryInterfaceClass c = JsonConvert.DeserializeObject<DictionaryInterfaceClass>(
  1309. json,
  1310. new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace});
  1311. Assert.AreEqual("Name!", c.Name);
  1312. Assert.AreEqual(1, c.Dictionary.Count);
  1313. Assert.AreEqual(11, c.Dictionary["Item"]);
  1314. }
  1315. [Test]
  1316. public void DeserializeDictionaryInterfaceWithExistingValues()
  1317. {
  1318. string json = @"{
  1319. ""Random"": {
  1320. ""blah"": 1
  1321. },
  1322. ""Name"": ""Name!"",
  1323. ""Dictionary"": {
  1324. ""Item"": 11,
  1325. ""Item1"": 12
  1326. },
  1327. ""Collection"": [
  1328. 999
  1329. ],
  1330. ""Employee"": {
  1331. ""Manager"": {
  1332. ""Name"": ""ManagerName!""
  1333. }
  1334. }
  1335. }";
  1336. DictionaryInterfaceClass c = JsonConvert.DeserializeObject<DictionaryInterfaceClass>(json,
  1337. new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Reuse});
  1338. Assert.AreEqual("Name!", c.Name);
  1339. Assert.AreEqual(3, c.Dictionary.Count);
  1340. Assert.AreEqual(11, c.Dictionary["Item"]);
  1341. Assert.AreEqual(1, c.Dictionary["existing"]);
  1342. Assert.AreEqual(4, c.Collection.Count);
  1343. Assert.AreEqual(1, c.Collection.ElementAt(0));
  1344. Assert.AreEqual(999, c.Collection.ElementAt(3));
  1345. Assert.AreEqual("EmployeeName!", c.Employee.Name);
  1346. Assert.AreEqual("ManagerName!", c.Employee.Manager.Name);
  1347. Assert.IsNotNull(c.Random);
  1348. }
  1349. [Test]
  1350. public void TypedObjectDeserializationWithComments()
  1351. {
  1352. string json = @"/*comment*/ { /*comment*/
  1353. ""Name"": /*comment*/ ""Apple"" /*comment*/, /*comment*/
  1354. ""ExpiryDate"": ""\/Date(1230422400000)\/"",
  1355. ""Price"": 3.99,
  1356. ""Sizes"": /*comment*/ [ /*comment*/
  1357. ""Small"", /*comment*/
  1358. ""Medium"" /*comment*/,
  1359. /*comment*/ ""Large""
  1360. /*comment*/ ] /*comment*/
  1361. } /*comment*/";
  1362. Product deserializedProduct = (Product) JsonConvert.DeserializeObject(json, typeof (Product));
  1363. Assert.AreEqual("Apple", deserializedProduct.Name);
  1364. Assert.AreEqual(new DateTime(2008, 12, 28, 0, 0, 0, DateTimeKind.Utc), deserializedProduct.ExpiryDate);
  1365. Assert.AreEqual(3.99m, deserializedProduct.Price);
  1366. Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
  1367. Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
  1368. Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
  1369. }
  1370. [Test]
  1371. public void NestedInsideOuterObject()
  1372. {
  1373. string json = @"{
  1374. ""short"": {
  1375. ""original"": ""http://www.contrast.ie/blog/online&#45;marketing&#45;2009/"",
  1376. ""short"": ""m2sqc6"",
  1377. ""shortened"": ""http://short.ie/m2sqc6"",
  1378. ""error"": {
  1379. ""code"": 0,
  1380. ""msg"": ""No action taken""
  1381. }
  1382. }
  1383. }";
  1384. JObject o = JObject.Parse(json);
  1385. Shortie s = JsonConvert.DeserializeObject<Shortie>(o["short"].ToString());
  1386. Assert.IsNotNull(s);
  1387. Assert.AreEqual(s.Original, "http://www.contrast.ie/blog/online&#45;marketing&#45;2009/");
  1388. Assert.AreEqual(s.Short, "m2sqc6");
  1389. Assert.AreEqual(s.Shortened, "http://short.ie/m2sqc6");
  1390. }
  1391. [Test]
  1392. public void UriSerialization()
  1393. {
  1394. Uri uri = new Uri("http://codeplex.com");
  1395. string json = JsonConvert.SerializeObject(uri);
  1396. Assert.AreEqual("http://codeplex.com/", uri.ToString());
  1397. Uri newUri = JsonConvert.DeserializeObject<Uri>(json);
  1398. Assert.AreEqual(uri, newUri);
  1399. }
  1400. [Test]
  1401. public void AnonymousPlusLinqToSql()
  1402. {
  1403. var value = new
  1404. {
  1405. bar = new JObject(new JProperty("baz", 13))
  1406. };
  1407. string json = JsonConvert.SerializeObject(value);
  1408. Assert.AreEqual(@"{""bar"":{""baz"":13}}", json);
  1409. }
  1410. [Test]
  1411. public void SerializeEnumerableAsObject()
  1412. {
  1413. Content content = new Content
  1414. {
  1415. Text = "Blah, blah, blah",
  1416. Children = new List<Content>
  1417. {
  1418. new Content {Text = "First"},
  1419. new Content {Text = "Second"}
  1420. }
  1421. };
  1422. string json = JsonConvert.SerializeObject(content, Formatting.Indented);
  1423. Assert.AreEqual(@"{
  1424. ""Children"": [
  1425. {
  1426. ""Children"": null,
  1427. ""Text"": ""First""
  1428. },
  1429. {
  1430. ""Children"": null,
  1431. ""Text"": ""Second""
  1432. }
  1433. ],
  1434. ""Text"": ""Blah, blah, blah""
  1435. }", json);
  1436. }
  1437. [Test]
  1438. public void DeserializeEnumerableAsObject()
  1439. {
  1440. string json = @"{
  1441. ""Children"": [
  1442. {
  1443. ""Children"": null,
  1444. ""Text"": ""First""
  1445. },
  1446. {
  1447. ""Children"": null,
  1448. ""Text"": ""Second""
  1449. }
  1450. ],
  1451. ""Text"": ""Blah, blah, blah""
  1452. }";
  1453. Content content = JsonConvert.DeserializeObject<Content>(json);
  1454. Assert.AreEqual("Blah, blah, blah", content.Text);
  1455. Assert.AreEqual(2, content.Children.Count);
  1456. Assert.AreEqual("First", content.Children[0].Text);
  1457. Assert.AreEqual("Second", content.Children[1].Text);
  1458. }
  1459. [Test]
  1460. public void RoleTransferTest()
  1461. {
  1462. string json = @"{""Operation"":""1"",""RoleName"":""Admin"",""Direction"":""0""}";
  1463. RoleTransfer r = JsonConvert.DeserializeObject<RoleTransfer>(json);
  1464. Assert.AreEqual(RoleTransferOperation.Second, r.Operation);
  1465. Assert.AreEqual("Admin", r.RoleName);
  1466. Assert.AreEqual(RoleTransferDirection.First, r.Direction);
  1467. }
  1468. [Test]
  1469. public void PrimitiveValuesInObjectArray()
  1470. {
  1471. string json = @"{""action"":""Router"",""method"":""Navigate"",""data"":[""dashboard"",null],""type"":""rpc"",""tid"":2}";
  1472. ObjectArrayPropertyTest o = JsonConvert.DeserializeObject<ObjectArrayPropertyTest>(json);
  1473. Assert.AreEqual("Router", o.Action);
  1474. Assert.AreEqual("Navigate", o.Method);
  1475. Assert.AreEqual(2, o.Data.Length);
  1476. Assert.AreEqual("dashboard", o.Data[0]);
  1477. Assert.AreEqual(null, o.Data[1]);
  1478. }
  1479. [Test]
  1480. public void ComplexValuesInObjectArray()
  1481. {
  1482. string json = @"{""action"":""Router"",""method"":""Navigate"",""data"":[""dashboard"",[""id"", 1, ""teststring"", ""test""],{""one"":1}],""type"":""rpc"",""tid"":2}";
  1483. ObjectArrayPropertyTest o = JsonConvert.DeserializeObject<ObjectArrayPropertyTest>(json);
  1484. Assert.AreEqual("Router", o.Action);
  1485. Assert.AreEqual("Navigate", o.Method);
  1486. Assert.AreEqual(3, o.Data.Length);
  1487. Assert.AreEqual("dashboard", o.Data[0]);
  1488. CustomAssert.IsInstanceOfType(typeof (JArray), o.Data[1]);
  1489. Assert.AreEqual(4, ((JArray) o.Data[1]).Count);
  1490. CustomAssert.IsInstanceOfType(typeof (JObject), o.Data[2]);
  1491. Assert.AreEqual(1, ((JObject) o.Data[2]).Count);
  1492. Assert.AreEqual(1, (int) ((JObject) o.Data[2])["one"]);
  1493. }
  1494. [Test]
  1495. public void DeserializeGenericDictionary()
  1496. {
  1497. string json = @"{""key1"":""value1"",""key2"":""value2""}";
  1498. Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  1499. Console.WriteLine(values.Count);
  1500. // 2
  1501. Console.WriteLine(values["key1"]);
  1502. // value1
  1503. Assert.AreEqual(2, values.Count);
  1504. Assert.AreEqual("value1", values["key1"]);
  1505. Assert.AreEqual("value2", values["key2"]);
  1506. }
  1507. [Test]
  1508. public void SerializeGenericList()
  1509. {
  1510. Product p1 = new Product
  1511. {
  1512. Name = "Product 1",
  1513. Price = 99.95m,
  1514. ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
  1515. };
  1516. Product p2 = new Product
  1517. {
  1518. Name = "Product 2",
  1519. Price = 12.50m,
  1520. ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
  1521. };
  1522. List<Product> products = new List<Product>();
  1523. products.Add(p1);
  1524. products.Add(p2);
  1525. string json = JsonConvert.SerializeObject(products, Formatting.Indented);
  1526. //[
  1527. // {
  1528. // "Name": "Product 1",
  1529. // "ExpiryDate": "\/Date(978048000000)\/",
  1530. // "Price": 99.95,
  1531. // "Sizes": null
  1532. // },
  1533. // {
  1534. // "Name": "Product 2",
  1535. // "ExpiryDate": "\/Date(1248998400000)\/",
  1536. // "Price": 12.50,
  1537. // "Sizes": null
  1538. // }
  1539. //]
  1540. Assert.AreEqual(@"[
  1541. {
  1542. ""Name"": ""Product 1"",
  1543. ""ExpiryDate"": ""2000-12-29T00:00:00Z"",
  1544. ""Price"": 99.95,
  1545. ""Sizes"": null
  1546. },
  1547. {
  1548. ""Name"": ""Product 2"",
  1549. ""ExpiryDate"": ""2009-07-31T00:00:00Z"",
  1550. ""Price"": 12.50,
  1551. ""Sizes"": null
  1552. }
  1553. ]", json);
  1554. }
  1555. [Test]
  1556. public void DeserializeGenericList()
  1557. {
  1558. string json = @"[
  1559. {
  1560. ""Name"": ""Product 1"",
  1561. ""ExpiryDate"": ""\/Date(978048000000)\/"",
  1562. ""Price"": 99.95,
  1563. ""Sizes"": null
  1564. },
  1565. {
  1566. ""Name"": ""Product 2"",
  1567. ""ExpiryDate"": ""\/Date(1248998400000)\/"",
  1568. ""Price"": 12.50,
  1569. ""Sizes"": null
  1570. }
  1571. ]";
  1572. List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);
  1573. Console.WriteLine(products.Count);
  1574. // 2
  1575. Product p1 = products[0];
  1576. Console.WriteLine(p1.Name);
  1577. // Product 1
  1578. Assert.AreEqual(2, products.Count);
  1579. Assert.AreEqual("Product 1", products[0].Name);
  1580. }
  1581. #if !PocketPC && !NET20
  1582. [Test]
  1583. public void DeserializeEmptyStringToNullableDateTime()
  1584. {
  1585. string json = @"{""DateTimeField"":""""}";
  1586. NullableDateTimeTestClass c = JsonConvert.DeserializeObject<NullableDateTimeTestClass>(json);
  1587. Assert.AreEqual(null, c.DateTimeField);
  1588. }
  1589. #endif
  1590. [Test]
  1591. [ExpectedException(typeof (JsonSerializationException)
  1592. #if !NETFX_CORE
  1593. , ExpectedMessage = @"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. Line 1, position 15."
  1594. #endif
  1595. )]
  1596. public void FailWhenClassWithNoDefaultConstructorHasMultipleConstructorsWithArguments()
  1597. {
  1598. 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)\/""}";
  1599. Event e = JsonConvert.DeserializeObject<Event>(json);
  1600. }
  1601. [Test]
  1602. public void DeserializeObjectSetOnlyProperty()
  1603. {
  1604. string json = @"{'SetOnlyProperty':[1,2,3,4,5]}";
  1605. SetOnlyPropertyClass2 setOnly = JsonConvert.DeserializeObject<SetOnlyPropertyClass2>(json);
  1606. JArray a = (JArray) setOnly.GetValue();
  1607. Assert.AreEqual(5, a.Count);
  1608. Assert.AreEqual(1, (int) a[0]);
  1609. Assert.AreEqual(5, (int) a[a.Count - 1]);
  1610. }
  1611. [Test]
  1612. public void DeserializeOptInClasses()
  1613. {
  1614. string json = @"{id: ""12"", name: ""test"", items: [{id: ""112"", name: ""testing""}]}";
  1615. ListTestClass l = JsonConvert.DeserializeObject<ListTestClass>(json);
  1616. }
  1617. [Test]
  1618. public void DeserializeNullableListWithNulls()
  1619. {
  1620. List<decimal?> l = JsonConvert.DeserializeObject<List<decimal?>>("[ 3.3, null, 1.1 ] ");
  1621. Assert.AreEqual(3, l.Count);
  1622. Assert.AreEqual(3.3m, l[0]);
  1623. Assert.AreEqual(null, l[1]);
  1624. Assert.AreEqual(1.1m, l[2]);
  1625. }
  1626. [Test]
  1627. [ExpectedException(typeof(JsonSerializationException)
  1628. #if !NETFX_CORE
  1629. , ExpectedMessage = @"Cannot deserialize JSON array (i.e. [1,2,3]) into type 'Newtonsoft.Json.Tests.TestObjects.Person'.
  1630. The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList.
  1631. To force JSON arrays to deserialize add the JsonArrayAttribute to the type. Line 1, position 1."
  1632. #endif
  1633. )]
  1634. public void CannotDeserializeArrayIntoObject()
  1635. {
  1636. string json = @"[]";
  1637. JsonConvert.DeserializeObject<Person>(json);
  1638. }
  1639. [Test]
  1640. [ExpectedException(typeof (JsonSerializationException)
  1641. #if !NETFX_CORE
  1642. , ExpectedMessage = @"Cannot deserialize JSON object (i.e. {""name"":""value""}) into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'.
  1643. The deserialized type should be a normal .NET type (i.e. not a primitive type like integer, not a collection type like an array or List<T>) or a dictionary type (i.e. Dictionary<TKey, TValue>).
  1644. To force JSON objects to deserialize add the JsonObjectAttribute to the type. Line 1, position 2."
  1645. #endif
  1646. )]
  1647. public void CannotDeserializeObjectIntoArray()
  1648. {
  1649. string json = @"{}";
  1650. JsonConvert.DeserializeObject<List<Person>>(json);
  1651. }
  1652. [Test]
  1653. [ExpectedException(typeof (JsonSerializationException)
  1654. #if !NETFX_CORE
  1655. , ExpectedMessage = @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Line 1, position 1."
  1656. #endif
  1657. )]
  1658. public void CannotPopulateArrayIntoObject()
  1659. {
  1660. string json = @"[]";
  1661. JsonConvert.PopulateObject(json, new Person());
  1662. }
  1663. [Test]
  1664. [ExpectedException(typeof (JsonSerializationException)
  1665. #if !NETFX_CORE
  1666. , ExpectedMessage = @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Line 1, position 2."
  1667. #endif
  1668. )]
  1669. public void CannotPopulateObjectIntoArray()
  1670. {
  1671. string json = @"{}";
  1672. JsonConvert.PopulateObject(json, new List<Person>());
  1673. }
  1674. [Test]
  1675. public void DeserializeEmptyString()
  1676. {
  1677. string json = @"{""Name"":""""}";
  1678. Person p = JsonConvert.DeserializeObject<Person>(json);
  1679. Assert.AreEqual("", p.Name);
  1680. }
  1681. [Test]
  1682. [ExpectedException(typeof (JsonSerializationException)
  1683. #if !NETFX_CORE
  1684. , ExpectedMessage = @"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'."
  1685. #endif
  1686. )]
  1687. public void SerializePropertyGetError()
  1688. {
  1689. JsonConvert.SerializeObject(new MemoryStream(), new JsonSerializerSettings
  1690. {
  1691. ContractResolver = new DefaultContractResolver
  1692. {
  1693. #if !(SILVERLIGHT || NETFX_CORE)
  1694. IgnoreSerializableAttribute = true
  1695. #endif
  1696. }
  1697. });
  1698. }
  1699. [Test]
  1700. [ExpectedException(typeof (JsonSerializationException)
  1701. #if !NETFX_CORE
  1702. , ExpectedMessage = @"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'."
  1703. #endif
  1704. )]
  1705. public void DeserializePropertySetError()
  1706. {
  1707. JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:0}", new JsonSerializerSettings
  1708. {
  1709. ContractResolver = new DefaultContractResolver
  1710. {
  1711. #if !(SILVERLIGHT || NETFX_CORE)
  1712. IgnoreSerializableAttribute = true
  1713. #endif
  1714. }
  1715. });
  1716. }
  1717. [Test]
  1718. [ExpectedException(typeof (JsonReaderException)
  1719. #if !NETFX_CORE
  1720. , ExpectedMessage = @"Could not convert string to integer: . Line 1, position 15."
  1721. #endif
  1722. )]
  1723. public void DeserializeEnsureTypeEmptyStringToIntError()
  1724. {
  1725. JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}", new JsonSerializerSettings
  1726. {
  1727. ContractResolver = new DefaultContractResolver
  1728. {
  1729. #if !(SILVERLIGHT || NETFX_CORE)
  1730. IgnoreSerializableAttribute = true
  1731. #endif
  1732. }
  1733. });
  1734. }
  1735. [Test]
  1736. [ExpectedException(typeof (JsonSerializationException)
  1737. #if !NETFX_CORE
  1738. , ExpectedMessage = @"Error converting value {null} to type 'System.Int32'. Line 1, position 17."
  1739. #endif
  1740. )]
  1741. public void DeserializeEnsureTypeNullToIntError()
  1742. {
  1743. JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}", new JsonSerializerSettings
  1744. {
  1745. ContractResolver = new DefaultContractResolver
  1746. {
  1747. #if !(SILVERLIGHT || NETFX_CORE)
  1748. IgnoreSerializableAttribute = true
  1749. #endif
  1750. }
  1751. });
  1752. }
  1753. [Test]
  1754. public void SerializeGenericListOfStrings()
  1755. {
  1756. List<String> strings = new List<String>();
  1757. strings.Add("str_1");
  1758. strings.Add("str_2");
  1759. strings.Add("str_3");
  1760. string json = JsonConvert.SerializeObject(strings);
  1761. Assert.AreEqual(@"[""str_1"",""str_2"",""str_3""]", json);
  1762. }
  1763. [Test]
  1764. public void ConstructorReadonlyFieldsTest()
  1765. {
  1766. ConstructorReadonlyFields c1 = new ConstructorReadonlyFields("String!", int.MaxValue);
  1767. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  1768. Assert.AreEqual(@"{
  1769. ""A"": ""String!"",
  1770. ""B"": 2147483647
  1771. }", json);
  1772. ConstructorReadonlyFields c2 = JsonConvert.DeserializeObject<ConstructorReadonlyFields>(json);
  1773. Assert.AreEqual("String!", c2.A);
  1774. Assert.AreEqual(int.MaxValue, c2.B);
  1775. }
  1776. [Test]
  1777. public void SerializeStruct()
  1778. {
  1779. StructTest structTest = new StructTest
  1780. {
  1781. StringProperty = "StringProperty!",
  1782. StringField = "StringField",
  1783. IntProperty = 5,
  1784. IntField = 10
  1785. };
  1786. string json = JsonConvert.SerializeObject(structTest, Formatting.Indented);
  1787. Console.WriteLine(json);
  1788. Assert.AreEqual(@"{
  1789. ""StringField"": ""StringField"",
  1790. ""IntField"": 10,
  1791. ""StringProperty"": ""StringProperty!"",
  1792. ""IntProperty"": 5
  1793. }", json);
  1794. StructTest deserialized = JsonConvert.DeserializeObject<StructTest>(json);
  1795. Assert.AreEqual(structTest.StringProperty, deserialized.StringProperty);
  1796. Assert.AreEqual(structTest.StringField, deserialized.StringField);
  1797. Assert.AreEqual(structTest.IntProperty, deserialized.IntProperty);
  1798. Assert.AreEqual(structTest.IntField, deserialized.IntField);
  1799. }
  1800. [Test]
  1801. public void SerializeListWithJsonConverter()
  1802. {
  1803. Foo f = new Foo();
  1804. f.Bars.Add(new Bar {Id = 0});
  1805. f.Bars.Add(new Bar {Id = 1});
  1806. f.Bars.Add(new Bar {Id = 2});
  1807. string json = JsonConvert.SerializeObject(f, Formatting.Indented);
  1808. Assert.AreEqual(@"{
  1809. ""Bars"": [
  1810. 0,
  1811. 1,
  1812. 2
  1813. ]
  1814. }", json);
  1815. Foo newFoo = JsonConvert.DeserializeObject<Foo>(json);
  1816. Assert.AreEqual(3, newFoo.Bars.Count);
  1817. Assert.AreEqual(0, newFoo.Bars[0].Id);
  1818. Assert.AreEqual(1, newFoo.Bars[1].Id);
  1819. Assert.AreEqual(2, newFoo.Bars[2].Id);
  1820. }
  1821. [Test]
  1822. public void SerializeGuidKeyedDictionary()
  1823. {
  1824. Dictionary<Guid, int> dictionary = new Dictionary<Guid, int>();
  1825. dictionary.Add(new Guid("F60EAEE0-AE47-488E-B330-59527B742D77"), 1);
  1826. dictionary.Add(new Guid("C2594C02-EBA1-426A-AA87-8DD8871350B0"), 2);
  1827. string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
  1828. Assert.AreEqual(@"{
  1829. ""f60eaee0-ae47-488e-b330-59527b742d77"": 1,
  1830. ""c2594c02-eba1-426a-aa87-8dd8871350b0"": 2
  1831. }", json);
  1832. }
  1833. [Test]
  1834. public void SerializePersonKeyedDictionary()
  1835. {
  1836. Dictionary<Person, int> dictionary = new Dictionary<Person, int>();
  1837. dictionary.Add(new Person {Name = "p1"}, 1);
  1838. dictionary.Add(new Person {Name = "p2"}, 2);
  1839. string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
  1840. Assert.AreEqual(@"{
  1841. ""Newtonsoft.Json.Tests.TestObjects.Person"": 1,
  1842. ""Newtonsoft.Json.Tests.TestObjects.Person"": 2
  1843. }", json);
  1844. }
  1845. [Test]
  1846. public void DeserializePersonKeyedDictionary()
  1847. {
  1848. 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. Line 2, position 46.",
  1849. () =>
  1850. {
  1851. string json =
  1852. @"{
  1853. ""Newtonsoft.Json.Tests.TestObjects.Person"": 1,
  1854. ""Newtonsoft.Json.Tests.TestObjects.Person"": 2
  1855. }";
  1856. JsonConvert.DeserializeObject<Dictionary<Person, int>>(json);
  1857. });
  1858. }
  1859. [Test]
  1860. public void SerializeFragment()
  1861. {
  1862. string googleSearchText = @"{
  1863. ""responseData"": {
  1864. ""results"": [
  1865. {
  1866. ""GsearchResultClass"": ""GwebSearch"",
  1867. ""unescapedUrl"": ""http://en.wikipedia.org/wiki/Paris_Hilton"",
  1868. ""url"": ""http://en.wikipedia.org/wiki/Paris_Hilton"",
  1869. ""visibleUrl"": ""en.wikipedia.org"",
  1870. ""cacheUrl"": ""http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org"",
  1871. ""title"": ""<b>Paris Hilton</b> - Wikipedia, the free encyclopedia"",
  1872. ""titleNoFormatting"": ""Paris Hilton - Wikipedia, the free encyclopedia"",
  1873. ""content"": ""[1] In 2006, she released her debut album...""
  1874. },
  1875. {
  1876. ""GsearchResultClass"": ""GwebSearch"",
  1877. ""unescapedUrl"": ""http://www.imdb.com/name/nm0385296/"",
  1878. ""url"": ""http://www.imdb.com/name/nm0385296/"",
  1879. ""visibleUrl"": ""www.imdb.com"",
  1880. ""cacheUrl"": ""http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com"",
  1881. ""title"": ""<b>Paris Hilton</b>"",
  1882. ""titleNoFormatting"": ""Paris Hilton"",
  1883. ""content"": ""Self: Zoolander. Socialite <b>Paris Hilton</b>...""
  1884. }
  1885. ],
  1886. ""cursor"": {
  1887. ""pages"": [
  1888. {
  1889. ""start"": ""0"",
  1890. ""label"": 1
  1891. },
  1892. {
  1893. ""start"": ""4"",
  1894. ""label"": 2
  1895. },
  1896. {
  1897. ""start"": ""8"",
  1898. ""label"": 3
  1899. },
  1900. {
  1901. ""start"": ""12"",
  1902. ""label"": 4
  1903. }
  1904. ],
  1905. ""estimatedResultCount"": ""59600000"",
  1906. ""currentPageIndex"": 0,
  1907. ""moreResultsUrl"": ""http://www.google.com/search?oe=utf8&ie=utf8...""
  1908. }
  1909. },
  1910. ""responseDetails"": null,
  1911. ""responseStatus"": 200
  1912. }";
  1913. JObject googleSearch = JObject.Parse(googleSearchText);
  1914. // get JSON result objects into a list
  1915. IList<JToken> results = googleSearch["responseData"]["results"].Children().ToList();
  1916. // serialize JSON results into .NET objects
  1917. IList<SearchResult> searchResults = new List<SearchResult>();
  1918. foreach (JToken result in results)
  1919. {
  1920. SearchResult searchResult = JsonConvert.DeserializeObject<SearchResult>(result.ToString());
  1921. searchResults.Add(searchResult);
  1922. }
  1923. // Title = <b>Paris Hilton</b> - Wikipedia, the free encyclopedia
  1924. // Content = [1] In 2006, she released her debut album...
  1925. // Url = http://en.wikipedia.org/wiki/Paris_Hilton
  1926. // Title = <b>Paris Hilton</b>
  1927. // Content = Self: Zoolander. Socialite <b>Paris Hilton</b>...
  1928. // Url = http://www.imdb.com/name/nm0385296/
  1929. Assert.AreEqual(2, searchResults.Count);
  1930. Assert.AreEqual("<b>Paris Hilton</b> - Wikipedia, the free encyclopedia", searchResults[0].Title);
  1931. Assert.AreEqual("<b>Paris Hilton</b>", searchResults[1].Title);
  1932. }
  1933. [Test]
  1934. public void DeserializeBaseReferenceWithDerivedValue()
  1935. {
  1936. PersonPropertyClass personPropertyClass = new PersonPropertyClass();
  1937. WagePerson wagePerson = (WagePerson) personPropertyClass.Person;
  1938. wagePerson.BirthDate = new DateTime(2000, 11, 29, 23, 59, 59, DateTimeKind.Utc);
  1939. wagePerson.Department = "McDees";
  1940. wagePerson.HourlyWage = 12.50m;
  1941. wagePerson.LastModified = new DateTime(2000, 11, 29, 23, 59, 59, DateTimeKind.Utc);
  1942. wagePerson.Name = "Jim Bob";
  1943. string json = JsonConvert.SerializeObject(personPropertyClass, Formatting.Indented);
  1944. Assert.AreEqual(
  1945. @"{
  1946. ""Person"": {
  1947. ""HourlyWage"": 12.50,
  1948. ""Name"": ""Jim Bob"",
  1949. ""BirthDate"": ""2000-11-29T23:59:59Z"",
  1950. ""LastModified"": ""2000-11-29T23:59:59Z""
  1951. }
  1952. }",
  1953. json);
  1954. PersonPropertyClass newPersonPropertyClass = JsonConvert.DeserializeObject<PersonPropertyClass>(json);
  1955. Assert.AreEqual(wagePerson.HourlyWage, ((WagePerson) newPersonPropertyClass.Person).HourlyWage);
  1956. }
  1957. public class ExistingValueClass
  1958. {
  1959. public Dictionary<string, string> Dictionary { get; set; }
  1960. public List<string> List { get; set; }
  1961. public ExistingValueClass()
  1962. {
  1963. Dictionary = new Dictionary<string, string>
  1964. {
  1965. {"existing", "yup"}
  1966. };
  1967. List = new List<string>
  1968. {
  1969. "existing"
  1970. };
  1971. }
  1972. }
  1973. [Test]
  1974. public void DeserializePopulateDictionaryAndList()
  1975. {
  1976. ExistingValueClass d = JsonConvert.DeserializeObject<ExistingValueClass>(@"{'Dictionary':{appended:'appended',existing:'new'}}");
  1977. Assert.IsNotNull(d);
  1978. Assert.IsNotNull(d.Dictionary);
  1979. Assert.AreEqual(typeof (Dictionary<string, string>), d.Dictionary.GetType());
  1980. Assert.AreEqual(typeof (List<string>), d.List.GetType());
  1981. Assert.AreEqual(2, d.Dictionary.Count);
  1982. Assert.AreEqual("new", d.Dictionary["existing"]);
  1983. Assert.AreEqual("appended", d.Dictionary["appended"]);
  1984. Assert.AreEqual(1, d.List.Count);
  1985. Assert.AreEqual("existing", d.List[0]);
  1986. }
  1987. public interface IKeyValueId
  1988. {
  1989. int Id { get; set; }
  1990. string Key { get; set; }
  1991. string Value { get; set; }
  1992. }
  1993. public class KeyValueId : IKeyValueId
  1994. {
  1995. public int Id { get; set; }
  1996. public string Key { get; set; }
  1997. public string Value { get; set; }
  1998. }
  1999. public class ThisGenericTest<T> where T : IKeyValueId
  2000. {
  2001. private Dictionary<string, T> _dict1 = new Dictionary<string, T>();
  2002. public string MyProperty { get; set; }
  2003. public void Add(T item)
  2004. {
  2005. this._dict1.Add(item.Key, item);
  2006. }
  2007. public T this[string key]
  2008. {
  2009. get { return this._dict1[key]; }
  2010. set { this._dict1[key] = value; }
  2011. }
  2012. public T this[int id]
  2013. {
  2014. get { return this._dict1.Values.FirstOrDefault(x => x.Id == id); }
  2015. set
  2016. {
  2017. var item = this[id];
  2018. if (item == null)
  2019. this.Add(value);
  2020. else
  2021. this._dict1[item.Key] = value;
  2022. }
  2023. }
  2024. public string ToJson()
  2025. {
  2026. return JsonConvert.SerializeObject(this, Formatting.Indented);
  2027. }
  2028. public T[] TheItems
  2029. {
  2030. get { return this._dict1.Values.ToArray<T>(); }
  2031. set
  2032. {
  2033. foreach (var item in value)
  2034. this.Add(item);
  2035. }
  2036. }
  2037. }
  2038. [Test]
  2039. public void IgnoreIndexedProperties()
  2040. {
  2041. ThisGenericTest<KeyValueId> g = new ThisGenericTest<KeyValueId>();
  2042. g.Add(new KeyValueId {Id = 1, Key = "key1", Value = "value1"});
  2043. g.Add(new KeyValueId {Id = 2, Key = "key2", Value = "value2"});
  2044. g.MyProperty = "some value";
  2045. string json = g.ToJson();
  2046. Assert.AreEqual(@"{
  2047. ""MyProperty"": ""some value"",
  2048. ""TheItems"": [
  2049. {
  2050. ""Id"": 1,
  2051. ""Key"": ""key1"",
  2052. ""Value"": ""value1""
  2053. },
  2054. {
  2055. ""Id"": 2,
  2056. ""Key"": ""key2"",
  2057. ""Value"": ""value2""
  2058. }
  2059. ]
  2060. }", json);
  2061. ThisGenericTest<KeyValueId> gen = JsonConvert.DeserializeObject<ThisGenericTest<KeyValueId>>(json);
  2062. Assert.AreEqual("some value", gen.MyProperty);
  2063. }
  2064. public class JRawValueTestObject
  2065. {
  2066. public JRaw Value { get; set; }
  2067. }
  2068. [Test]
  2069. public void JRawValue()
  2070. {
  2071. JRawValueTestObject deserialized = JsonConvert.DeserializeObject<JRawValueTestObject>("{value:3}");
  2072. Assert.AreEqual("3", deserialized.Value.ToString());
  2073. deserialized = JsonConvert.DeserializeObject<JRawValueTestObject>("{value:'3'}");
  2074. Assert.AreEqual(@"""3""", deserialized.Value.ToString());
  2075. }
  2076. [Test]
  2077. [ExpectedException(typeof (JsonSerializationException)
  2078. #if !NETFX_CORE
  2079. , ExpectedMessage = "Unable to find a default constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Line 1, position 6."
  2080. #endif
  2081. )]
  2082. public void DeserializeDictionaryWithNoDefaultConstructor()
  2083. {
  2084. string json = "{key1:'value',key2:'value',key3:'value'}";
  2085. JsonConvert.DeserializeObject<DictionaryWithNoDefaultConstructor>(json);
  2086. }
  2087. public class DictionaryWithNoDefaultConstructor : Dictionary<string, string>
  2088. {
  2089. public DictionaryWithNoDefaultConstructor(IEnumerable<KeyValuePair<string, string>> initial)
  2090. {
  2091. foreach (KeyValuePair<string, string> pair in initial)
  2092. {
  2093. Add(pair.Key, pair.Value);
  2094. }
  2095. }
  2096. }
  2097. [JsonObject(MemberSerialization.OptIn)]
  2098. public class A
  2099. {
  2100. [JsonProperty("A1")] private string _A1;
  2101. public string A1
  2102. {
  2103. get { return _A1; }
  2104. set { _A1 = value; }
  2105. }
  2106. [JsonProperty("A2")]
  2107. private string A2 { get; set; }
  2108. }
  2109. [JsonObject(MemberSerialization.OptIn)]
  2110. public class B : A
  2111. {
  2112. public string B1 { get; set; }
  2113. [JsonProperty("B2")] private string _B2;
  2114. public string B2
  2115. {
  2116. get { return _B2; }
  2117. set { _B2 = value; }
  2118. }
  2119. [JsonProperty("B3")]
  2120. private string B3 { get; set; }
  2121. }
  2122. [Test]
  2123. public void SerializeNonPublicBaseJsonProperties()
  2124. {
  2125. B value = new B();
  2126. string json = JsonConvert.SerializeObject(value, Formatting.Indented);
  2127. Assert.AreEqual(@"{
  2128. ""B2"": null,
  2129. ""A1"": null,
  2130. ""B3"": null,
  2131. ""A2"": null
  2132. }", json);
  2133. }
  2134. public class TestClass
  2135. {
  2136. public string Key { get; set; }
  2137. public object Value { get; set; }
  2138. }
  2139. [Test]
  2140. public void DeserializeToObjectProperty()
  2141. {
  2142. var json = "{ Key: 'abc', Value: 123 }";
  2143. var item = JsonConvert.DeserializeObject<TestClass>(json);
  2144. Assert.AreEqual(123L, item.Value);
  2145. }
  2146. public abstract class Animal
  2147. {
  2148. public abstract string Name { get; }
  2149. }
  2150. public class Human : Animal
  2151. {
  2152. public override string Name
  2153. {
  2154. get { return typeof (Human).Name; }
  2155. }
  2156. public string Ethnicity { get; set; }
  2157. }
  2158. #if !NET20 && !PocketPC && !WINDOWS_PHONE
  2159. public class DataContractJsonSerializerTestClass
  2160. {
  2161. public TimeSpan TimeSpanProperty { get; set; }
  2162. public Guid GuidProperty { get; set; }
  2163. public Animal AnimalProperty { get; set; }
  2164. public Exception ExceptionProperty { get; set; }
  2165. }
  2166. [Test]
  2167. public void DataContractJsonSerializerTest()
  2168. {
  2169. Exception ex = new Exception("Blah blah blah");
  2170. DataContractJsonSerializerTestClass c = new DataContractJsonSerializerTestClass();
  2171. c.TimeSpanProperty = new TimeSpan(200, 20, 59, 30, 900);
  2172. c.GuidProperty = new Guid("66143115-BE2A-4a59-AF0A-348E1EA15B1E");
  2173. c.AnimalProperty = new Human() {Ethnicity = "European"};
  2174. c.ExceptionProperty = ex;
  2175. MemoryStream ms = new MemoryStream();
  2176. DataContractJsonSerializer serializer = new DataContractJsonSerializer(
  2177. typeof (DataContractJsonSerializerTestClass),
  2178. new Type[] {typeof (Human)});
  2179. serializer.WriteObject(ms, c);
  2180. byte[] jsonBytes = ms.ToArray();
  2181. string json = Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length);
  2182. //Console.WriteLine(JObject.Parse(json).ToString());
  2183. //Console.WriteLine();
  2184. //Console.WriteLine(JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings
  2185. // {
  2186. // // TypeNameHandling = TypeNameHandling.Objects
  2187. // }));
  2188. }
  2189. #endif
  2190. public class ModelStateDictionary<T> : IDictionary<string, T>
  2191. {
  2192. private readonly Dictionary<string, T> _innerDictionary = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
  2193. public ModelStateDictionary()
  2194. {
  2195. }
  2196. public ModelStateDictionary(ModelStateDictionary<T> dictionary)
  2197. {
  2198. if (dictionary == null)
  2199. {
  2200. throw new ArgumentNullException("dictionary");
  2201. }
  2202. foreach (var entry in dictionary)
  2203. {
  2204. _innerDictionary.Add(entry.Key, entry.Value);
  2205. }
  2206. }
  2207. public int Count
  2208. {
  2209. get { return _innerDictionary.Count; }
  2210. }
  2211. public bool IsReadOnly
  2212. {
  2213. get { return ((IDictionary<string, T>) _innerDictionary).IsReadOnly; }
  2214. }
  2215. public ICollection<string> Keys
  2216. {
  2217. get { return _innerDictionary.Keys; }
  2218. }
  2219. public T this[string key]
  2220. {
  2221. get
  2222. {
  2223. T value;
  2224. _innerDictionary.TryGetValue(key, out value);
  2225. return value;
  2226. }
  2227. set { _innerDictionary[key] = value; }
  2228. }
  2229. public ICollection<T> Values
  2230. {
  2231. get { return _innerDictionary.Values; }
  2232. }
  2233. public void Add(KeyValuePair<string, T> item)
  2234. {
  2235. ((IDictionary<string, T>) _innerDictionary).Add(item);
  2236. }
  2237. public void Add(string key, T value)
  2238. {
  2239. _innerDictionary.Add(key, value);
  2240. }
  2241. public void Clear()
  2242. {
  2243. _innerDictionary.Clear();
  2244. }
  2245. public bool Contains(KeyValuePair<string, T> item)
  2246. {
  2247. return ((IDictionary<string, T>) _innerDictionary).Contains(item);
  2248. }
  2249. public bool ContainsKey(string key)
  2250. {
  2251. return _innerDictionary.ContainsKey(key);
  2252. }
  2253. public void CopyTo(KeyValuePair<string, T>[] array, int arrayIndex)
  2254. {
  2255. ((IDictionary<string, T>) _innerDictionary).CopyTo(array, arrayIndex);
  2256. }
  2257. public IEnumerator<KeyValuePair<string, T>> GetEnumerator()
  2258. {
  2259. return _innerDictionary.GetEnumerator();
  2260. }
  2261. public void Merge(ModelStateDictionary<T> dictionary)
  2262. {
  2263. if (dictionary == null)
  2264. {
  2265. return;
  2266. }
  2267. foreach (var entry in dictionary)
  2268. {
  2269. this[entry.Key] = entry.Value;
  2270. }
  2271. }
  2272. public bool Remove(KeyValuePair<string, T> item)
  2273. {
  2274. return ((IDictionary<string, T>) _innerDictionary).Remove(item);
  2275. }
  2276. public bool Remove(string key)
  2277. {
  2278. return _innerDictionary.Remove(key);
  2279. }
  2280. public bool TryGetValue(string key, out T value)
  2281. {
  2282. return _innerDictionary.TryGetValue(key, out value);
  2283. }
  2284. IEnumerator IEnumerable.GetEnumerator()
  2285. {
  2286. return ((IEnumerable) _innerDictionary).GetEnumerator();
  2287. }
  2288. }
  2289. [Test]
  2290. public void SerializeNonIDictionary()
  2291. {
  2292. ModelStateDictionary<string> modelStateDictionary = new ModelStateDictionary<string>();
  2293. modelStateDictionary.Add("key", "value");
  2294. string json = JsonConvert.SerializeObject(modelStateDictionary);
  2295. Assert.AreEqual(@"{""key"":""value""}", json);
  2296. ModelStateDictionary<string> newModelStateDictionary = JsonConvert.DeserializeObject<ModelStateDictionary<string>>(json);
  2297. Assert.AreEqual(1, newModelStateDictionary.Count);
  2298. Assert.AreEqual("value", newModelStateDictionary["key"]);
  2299. }
  2300. #if !SILVERLIGHT && !PocketPC && !NETFX_CORE
  2301. public class ISerializableTestObject : ISerializable
  2302. {
  2303. internal string _stringValue;
  2304. internal int _intValue;
  2305. internal DateTimeOffset _dateTimeOffsetValue;
  2306. internal Person _personValue;
  2307. internal Person _nullPersonValue;
  2308. internal int? _nullableInt;
  2309. internal bool _booleanValue;
  2310. internal byte _byteValue;
  2311. internal char _charValue;
  2312. internal DateTime _dateTimeValue;
  2313. internal decimal _decimalValue;
  2314. internal short _shortValue;
  2315. internal long _longValue;
  2316. internal sbyte _sbyteValue;
  2317. internal float _floatValue;
  2318. internal ushort _ushortValue;
  2319. internal uint _uintValue;
  2320. internal ulong _ulongValue;
  2321. public ISerializableTestObject(string stringValue, int intValue, DateTimeOffset dateTimeOffset, Person personValue)
  2322. {
  2323. _stringValue = stringValue;
  2324. _intValue = intValue;
  2325. _dateTimeOffsetValue = dateTimeOffset;
  2326. _personValue = personValue;
  2327. _dateTimeValue = new DateTime(0, DateTimeKind.Utc);
  2328. }
  2329. protected ISerializableTestObject(SerializationInfo info, StreamingContext context)
  2330. {
  2331. _stringValue = info.GetString("stringValue");
  2332. _intValue = info.GetInt32("intValue");
  2333. _dateTimeOffsetValue = (DateTimeOffset) info.GetValue("dateTimeOffsetValue", typeof (DateTimeOffset));
  2334. _personValue = (Person) info.GetValue("personValue", typeof (Person));
  2335. _nullPersonValue = (Person) info.GetValue("nullPersonValue", typeof (Person));
  2336. _nullableInt = (int?) info.GetValue("nullableInt", typeof (int?));
  2337. _booleanValue = info.GetBoolean("booleanValue");
  2338. _byteValue = info.GetByte("byteValue");
  2339. _charValue = info.GetChar("charValue");
  2340. _dateTimeValue = info.GetDateTime("dateTimeValue");
  2341. _decimalValue = info.GetDecimal("decimalValue");
  2342. _shortValue = info.GetInt16("shortValue");
  2343. _longValue = info.GetInt64("longValue");
  2344. _sbyteValue = info.GetSByte("sbyteValue");
  2345. _floatValue = info.GetSingle("floatValue");
  2346. _ushortValue = info.GetUInt16("ushortValue");
  2347. _uintValue = info.GetUInt32("uintValue");
  2348. _ulongValue = info.GetUInt64("ulongValue");
  2349. }
  2350. public void GetObjectData(SerializationInfo info, StreamingContext context)
  2351. {
  2352. info.AddValue("stringValue", _stringValue);
  2353. info.AddValue("intValue", _intValue);
  2354. info.AddValue("dateTimeOffsetValue", _dateTimeOffsetValue);
  2355. info.AddValue("personValue", _personValue);
  2356. info.AddValue("nullPersonValue", _nullPersonValue);
  2357. info.AddValue("nullableInt", null);
  2358. info.AddValue("booleanValue", _booleanValue);
  2359. info.AddValue("byteValue", _byteValue);
  2360. info.AddValue("charValue", _charValue);
  2361. info.AddValue("dateTimeValue", _dateTimeValue);
  2362. info.AddValue("decimalValue", _decimalValue);
  2363. info.AddValue("shortValue", _shortValue);
  2364. info.AddValue("longValue", _longValue);
  2365. info.AddValue("sbyteValue", _sbyteValue);
  2366. info.AddValue("floatValue", _floatValue);
  2367. info.AddValue("ushortValue", _ushortValue);
  2368. info.AddValue("uintValue", _uintValue);
  2369. info.AddValue("ulongValue", _ulongValue);
  2370. }
  2371. }
  2372. #if DEBUG
  2373. [Test]
  2374. public void SerializeISerializableInPartialTrustWithIgnoreInterface()
  2375. {
  2376. try
  2377. {
  2378. JsonTypeReflector.SetFullyTrusted(false);
  2379. ISerializableTestObject value = new ISerializableTestObject("string!", 0, default(DateTimeOffset), null);
  2380. string json = JsonConvert.SerializeObject(value, new JsonSerializerSettings
  2381. {
  2382. ContractResolver = new DefaultContractResolver(false)
  2383. {
  2384. IgnoreSerializableInterface = true
  2385. }
  2386. });
  2387. Assert.AreEqual("{}", json);
  2388. value = JsonConvert.DeserializeObject<ISerializableTestObject>("{booleanValue:true}", new JsonSerializerSettings
  2389. {
  2390. ContractResolver = new DefaultContractResolver(false)
  2391. {
  2392. IgnoreSerializableInterface = true
  2393. }
  2394. });
  2395. Assert.IsNotNull(value);
  2396. Assert.AreEqual(false, value._booleanValue);
  2397. }
  2398. finally
  2399. {
  2400. JsonTypeReflector.SetFullyTrusted(true);
  2401. }
  2402. }
  2403. [Test]
  2404. public void SerializeISerializableInPartialTrust()
  2405. {
  2406. try
  2407. {
  2408. ExceptionAssert.Throws<JsonSerializationException>(
  2409. @"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.
  2410. To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add to JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true. Line 1, position 14.",
  2411. () =>
  2412. {
  2413. JsonTypeReflector.SetFullyTrusted(false);
  2414. JsonConvert.DeserializeObject<ISerializableTestObject>("{booleanValue:true}");
  2415. });
  2416. }
  2417. finally
  2418. {
  2419. JsonTypeReflector.SetFullyTrusted(true);
  2420. }
  2421. }
  2422. [Test]
  2423. public void DeserializeISerializableInPartialTrust()
  2424. {
  2425. try
  2426. {
  2427. ExceptionAssert.Throws<JsonSerializationException>(
  2428. @"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.
  2429. To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add to JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.",
  2430. () =>
  2431. {
  2432. JsonTypeReflector.SetFullyTrusted(false);
  2433. ISerializableTestObject value = new ISerializableTestObject("string!", 0, default(DateTimeOffset), null);
  2434. JsonConvert.SerializeObject(value);
  2435. });
  2436. }
  2437. finally
  2438. {
  2439. JsonTypeReflector.SetFullyTrusted(true);
  2440. }
  2441. }
  2442. #endif
  2443. [Test]
  2444. public void SerializeISerializableTestObject_IsoDate()
  2445. {
  2446. Person person = new Person();
  2447. person.BirthDate = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
  2448. person.LastModified = person.BirthDate;
  2449. person.Department = "Department!";
  2450. person.Name = "Name!";
  2451. DateTimeOffset dateTimeOffset = new DateTimeOffset(2000, 12, 20, 22, 59, 59, TimeSpan.FromHours(2));
  2452. string dateTimeOffsetText;
  2453. #if !NET20
  2454. dateTimeOffsetText = @"2000-12-20T22:59:59+02:00";
  2455. #else
  2456. dateTimeOffsetText = @"12/20/2000 22:59:59 +02:00";
  2457. #endif
  2458. ISerializableTestObject o = new ISerializableTestObject("String!", int.MinValue, dateTimeOffset, person);
  2459. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  2460. Assert.AreEqual(@"{
  2461. ""stringValue"": ""String!"",
  2462. ""intValue"": -2147483648,
  2463. ""dateTimeOffsetValue"": """ + dateTimeOffsetText + @""",
  2464. ""personValue"": {
  2465. ""Name"": ""Name!"",
  2466. ""BirthDate"": ""2000-01-01T01:01:01Z"",
  2467. ""LastModified"": ""2000-01-01T01:01:01Z""
  2468. },
  2469. ""nullPersonValue"": null,
  2470. ""nullableInt"": null,
  2471. ""booleanValue"": false,
  2472. ""byteValue"": 0,
  2473. ""charValue"": ""\u0000"",
  2474. ""dateTimeValue"": ""0001-01-01T00:00:00Z"",
  2475. ""decimalValue"": 0.0,
  2476. ""shortValue"": 0,
  2477. ""longValue"": 0,
  2478. ""sbyteValue"": 0,
  2479. ""floatValue"": 0.0,
  2480. ""ushortValue"": 0,
  2481. ""uintValue"": 0,
  2482. ""ulongValue"": 0
  2483. }", json);
  2484. ISerializableTestObject o2 = JsonConvert.DeserializeObject<ISerializableTestObject>(json);
  2485. Assert.AreEqual("String!", o2._stringValue);
  2486. Assert.AreEqual(int.MinValue, o2._intValue);
  2487. Assert.AreEqual(dateTimeOffset, o2._dateTimeOffsetValue);
  2488. Assert.AreEqual("Name!", o2._personValue.Name);
  2489. Assert.AreEqual(null, o2._nullPersonValue);
  2490. Assert.AreEqual(null, o2._nullableInt);
  2491. }
  2492. [Test]
  2493. public void SerializeISerializableTestObject_MsAjax()
  2494. {
  2495. Person person = new Person();
  2496. person.BirthDate = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
  2497. person.LastModified = person.BirthDate;
  2498. person.Department = "Department!";
  2499. person.Name = "Name!";
  2500. DateTimeOffset dateTimeOffset = new DateTimeOffset(2000, 12, 20, 22, 59, 59, TimeSpan.FromHours(2));
  2501. string dateTimeOffsetText;
  2502. #if !NET20
  2503. dateTimeOffsetText = @"\/Date(977345999000+0200)\/";
  2504. #else
  2505. dateTimeOffsetText = @"12/20/2000 22:59:59 +02:00";
  2506. #endif
  2507. ISerializableTestObject o = new ISerializableTestObject("String!", int.MinValue, dateTimeOffset, person);
  2508. string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
  2509. {
  2510. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  2511. });
  2512. Assert.AreEqual(@"{
  2513. ""stringValue"": ""String!"",
  2514. ""intValue"": -2147483648,
  2515. ""dateTimeOffsetValue"": """ + dateTimeOffsetText + @""",
  2516. ""personValue"": {
  2517. ""Name"": ""Name!"",
  2518. ""BirthDate"": ""\/Date(946688461000)\/"",
  2519. ""LastModified"": ""\/Date(946688461000)\/""
  2520. },
  2521. ""nullPersonValue"": null,
  2522. ""nullableInt"": null,
  2523. ""booleanValue"": false,
  2524. ""byteValue"": 0,
  2525. ""charValue"": ""\u0000"",
  2526. ""dateTimeValue"": ""\/Date(-62135596800000)\/"",
  2527. ""decimalValue"": 0.0,
  2528. ""shortValue"": 0,
  2529. ""longValue"": 0,
  2530. ""sbyteValue"": 0,
  2531. ""floatValue"": 0.0,
  2532. ""ushortValue"": 0,
  2533. ""uintValue"": 0,
  2534. ""ulongValue"": 0
  2535. }", json);
  2536. ISerializableTestObject o2 = JsonConvert.DeserializeObject<ISerializableTestObject>(json);
  2537. Assert.AreEqual("String!", o2._stringValue);
  2538. Assert.AreEqual(int.MinValue, o2._intValue);
  2539. Assert.AreEqual(dateTimeOffset, o2._dateTimeOffsetValue);
  2540. Assert.AreEqual("Name!", o2._personValue.Name);
  2541. Assert.AreEqual(null, o2._nullPersonValue);
  2542. Assert.AreEqual(null, o2._nullableInt);
  2543. }
  2544. #endif
  2545. public class KVPair<TKey, TValue>
  2546. {
  2547. public TKey Key { get; set; }
  2548. public TValue Value { get; set; }
  2549. public KVPair(TKey k, TValue v)
  2550. {
  2551. Key = k;
  2552. Value = v;
  2553. }
  2554. }
  2555. [Test]
  2556. public void DeserializeUsingNonDefaultConstructorWithLeftOverValues()
  2557. {
  2558. List<KVPair<string, string>> kvPairs =
  2559. JsonConvert.DeserializeObject<List<KVPair<string, string>>>(
  2560. "[{\"Key\":\"Two\",\"Value\":\"2\"},{\"Key\":\"One\",\"Value\":\"1\"}]");
  2561. Assert.AreEqual(2, kvPairs.Count);
  2562. Assert.AreEqual("Two", kvPairs[0].Key);
  2563. Assert.AreEqual("2", kvPairs[0].Value);
  2564. Assert.AreEqual("One", kvPairs[1].Key);
  2565. Assert.AreEqual("1", kvPairs[1].Value);
  2566. }
  2567. [Test]
  2568. public void SerializeClassWithInheritedProtectedMember()
  2569. {
  2570. AA myA = new AA(2);
  2571. string json = JsonConvert.SerializeObject(myA, Formatting.Indented);
  2572. Assert.AreEqual(@"{
  2573. ""AA_field1"": 2,
  2574. ""AA_property1"": 2,
  2575. ""AA_property2"": 2,
  2576. ""AA_property3"": 2,
  2577. ""AA_property4"": 2
  2578. }", json);
  2579. BB myB = new BB(3, 4);
  2580. json = JsonConvert.SerializeObject(myB, Formatting.Indented);
  2581. Assert.AreEqual(@"{
  2582. ""BB_field1"": 4,
  2583. ""BB_field2"": 4,
  2584. ""AA_field1"": 3,
  2585. ""BB_property1"": 4,
  2586. ""BB_property2"": 4,
  2587. ""BB_property3"": 4,
  2588. ""BB_property4"": 4,
  2589. ""BB_property5"": 4,
  2590. ""BB_property7"": 4,
  2591. ""AA_property1"": 3,
  2592. ""AA_property2"": 3,
  2593. ""AA_property3"": 3,
  2594. ""AA_property4"": 3
  2595. }", json);
  2596. }
  2597. [Test]
  2598. public void DeserializeClassWithInheritedProtectedMember()
  2599. {
  2600. AA myA = JsonConvert.DeserializeObject<AA>(
  2601. @"{
  2602. ""AA_field1"": 2,
  2603. ""AA_field2"": 2,
  2604. ""AA_property1"": 2,
  2605. ""AA_property2"": 2,
  2606. ""AA_property3"": 2,
  2607. ""AA_property4"": 2,
  2608. ""AA_property5"": 2,
  2609. ""AA_property6"": 2
  2610. }");
  2611. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof (AA).GetField("AA_field1", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2612. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof (AA).GetField("AA_field2", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2613. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof (AA).GetProperty("AA_property1", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2614. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof (AA).GetProperty("AA_property2", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2615. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof (AA).GetProperty("AA_property3", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2616. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof (AA).GetProperty("AA_property4", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2617. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof (AA).GetProperty("AA_property5", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2618. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof (AA).GetProperty("AA_property6", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2619. BB myB = JsonConvert.DeserializeObject<BB>(
  2620. @"{
  2621. ""BB_field1"": 4,
  2622. ""BB_field2"": 4,
  2623. ""AA_field1"": 3,
  2624. ""AA_field2"": 3,
  2625. ""AA_property1"": 2,
  2626. ""AA_property2"": 2,
  2627. ""AA_property3"": 2,
  2628. ""AA_property4"": 2,
  2629. ""AA_property5"": 2,
  2630. ""AA_property6"": 2,
  2631. ""BB_property1"": 3,
  2632. ""BB_property2"": 3,
  2633. ""BB_property3"": 3,
  2634. ""BB_property4"": 3,
  2635. ""BB_property5"": 3,
  2636. ""BB_property6"": 3,
  2637. ""BB_property7"": 3,
  2638. ""BB_property8"": 3
  2639. }");
  2640. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof (AA).GetField("AA_field1", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2641. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof (AA).GetField("AA_field2", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2642. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof (AA).GetProperty("AA_property1", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2643. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof (AA).GetProperty("AA_property2", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2644. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof (AA).GetProperty("AA_property3", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2645. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof (AA).GetProperty("AA_property4", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2646. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof (AA).GetProperty("AA_property5", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2647. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof (AA).GetProperty("AA_property6", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2648. Assert.AreEqual(4, myB.BB_field1);
  2649. Assert.AreEqual(4, myB.BB_field2);
  2650. Assert.AreEqual(3, myB.BB_property1);
  2651. Assert.AreEqual(3, myB.BB_property2);
  2652. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof (BB).GetProperty("BB_property3", BindingFlags.Instance | BindingFlags.Public), myB));
  2653. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof (BB).GetProperty("BB_property4", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2654. Assert.AreEqual(0, myB.BB_property5);
  2655. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof (BB).GetProperty("BB_property6", BindingFlags.Instance | BindingFlags.Public), myB));
  2656. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof (BB).GetProperty("BB_property7", BindingFlags.Instance | BindingFlags.Public), myB));
  2657. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof (BB).GetProperty("BB_property8", BindingFlags.Instance | BindingFlags.Public), myB));
  2658. }
  2659. public class AA
  2660. {
  2661. [JsonProperty] protected int AA_field1;
  2662. protected int AA_field2;
  2663. [JsonProperty]
  2664. protected int AA_property1 { get; set; }
  2665. [JsonProperty]
  2666. protected int AA_property2 { get; private set; }
  2667. [JsonProperty]
  2668. protected int AA_property3 { private get; set; }
  2669. [JsonProperty]
  2670. private int AA_property4 { get; set; }
  2671. protected int AA_property5 { get; private set; }
  2672. protected int AA_property6 { private get; set; }
  2673. public AA()
  2674. {
  2675. }
  2676. public AA(int f)
  2677. {
  2678. AA_field1 = f;
  2679. AA_field2 = f;
  2680. AA_property1 = f;
  2681. AA_property2 = f;
  2682. AA_property3 = f;
  2683. AA_property4 = f;
  2684. AA_property5 = f;
  2685. AA_property6 = f;
  2686. }
  2687. }
  2688. public class BB : AA
  2689. {
  2690. [JsonProperty] public int BB_field1;
  2691. public int BB_field2;
  2692. [JsonProperty]
  2693. public int BB_property1 { get; set; }
  2694. [JsonProperty]
  2695. public int BB_property2 { get; private set; }
  2696. [JsonProperty]
  2697. public int BB_property3 { private get; set; }
  2698. [JsonProperty]
  2699. private int BB_property4 { get; set; }
  2700. public int BB_property5 { get; private set; }
  2701. public int BB_property6 { private get; set; }
  2702. [JsonProperty]
  2703. public int BB_property7 { protected get; set; }
  2704. public int BB_property8 { protected get; set; }
  2705. public BB()
  2706. {
  2707. }
  2708. public BB(int f, int g)
  2709. : base(f)
  2710. {
  2711. BB_field1 = g;
  2712. BB_field2 = g;
  2713. BB_property1 = g;
  2714. BB_property2 = g;
  2715. BB_property3 = g;
  2716. BB_property4 = g;
  2717. BB_property5 = g;
  2718. BB_property6 = g;
  2719. BB_property7 = g;
  2720. BB_property8 = g;
  2721. }
  2722. }
  2723. #if !NET20 && !SILVERLIGHT
  2724. public class XNodeTestObject
  2725. {
  2726. public XDocument Document { get; set; }
  2727. public XElement Element { get; set; }
  2728. }
  2729. #endif
  2730. #if !SILVERLIGHT && !NETFX_CORE
  2731. public class XmlNodeTestObject
  2732. {
  2733. public XmlDocument Document { get; set; }
  2734. }
  2735. #endif
  2736. #if !NET20 && !SILVERLIGHT
  2737. [Test]
  2738. public void SerializeDeserializeXNodeProperties()
  2739. {
  2740. XNodeTestObject testObject = new XNodeTestObject();
  2741. testObject.Document = XDocument.Parse("<root>hehe, root</root>");
  2742. testObject.Element = XElement.Parse(@"<fifth xmlns:json=""http://json.org"" json:Awesome=""true"">element</fifth>");
  2743. string json = JsonConvert.SerializeObject(testObject, Formatting.Indented);
  2744. string expected = @"{
  2745. ""Document"": {
  2746. ""root"": ""hehe, root""
  2747. },
  2748. ""Element"": {
  2749. ""fifth"": {
  2750. ""@xmlns:json"": ""http://json.org"",
  2751. ""@json:Awesome"": ""true"",
  2752. ""#text"": ""element""
  2753. }
  2754. }
  2755. }";
  2756. Assert.AreEqual(expected, json);
  2757. XNodeTestObject newTestObject = JsonConvert.DeserializeObject<XNodeTestObject>(json);
  2758. Assert.AreEqual(testObject.Document.ToString(), newTestObject.Document.ToString());
  2759. Assert.AreEqual(testObject.Element.ToString(), newTestObject.Element.ToString());
  2760. Assert.IsNull(newTestObject.Element.Parent);
  2761. }
  2762. #endif
  2763. #if !SILVERLIGHT && !NETFX_CORE
  2764. [Test]
  2765. public void SerializeDeserializeXmlNodeProperties()
  2766. {
  2767. XmlNodeTestObject testObject = new XmlNodeTestObject();
  2768. XmlDocument document = new XmlDocument();
  2769. document.LoadXml("<root>hehe, root</root>");
  2770. testObject.Document = document;
  2771. string json = JsonConvert.SerializeObject(testObject, Formatting.Indented);
  2772. string expected = @"{
  2773. ""Document"": {
  2774. ""root"": ""hehe, root""
  2775. }
  2776. }";
  2777. Assert.AreEqual(expected, json);
  2778. XmlNodeTestObject newTestObject = JsonConvert.DeserializeObject<XmlNodeTestObject>(json);
  2779. Assert.AreEqual(testObject.Document.InnerXml, newTestObject.Document.InnerXml);
  2780. }
  2781. #endif
  2782. [Test]
  2783. public void FullClientMapSerialization()
  2784. {
  2785. ClientMap source = new ClientMap()
  2786. {
  2787. position = new Pos() {X = 100, Y = 200},
  2788. center = new PosDouble() {X = 251.6, Y = 361.3}
  2789. };
  2790. string json = JsonConvert.SerializeObject(source, new PosConverter(), new PosDoubleConverter());
  2791. Assert.AreEqual("{\"position\":new Pos(100,200),\"center\":new PosD(251.6,361.3)}", json);
  2792. }
  2793. public class ClientMap
  2794. {
  2795. public Pos position { get; set; }
  2796. public PosDouble center { get; set; }
  2797. }
  2798. public class Pos
  2799. {
  2800. public int X { get; set; }
  2801. public int Y { get; set; }
  2802. }
  2803. public class PosDouble
  2804. {
  2805. public double X { get; set; }
  2806. public double Y { get; set; }
  2807. }
  2808. public class PosConverter : JsonConverter
  2809. {
  2810. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  2811. {
  2812. Pos p = (Pos) value;
  2813. if (p != null)
  2814. writer.WriteRawValue(String.Format("new Pos({0},{1})", p.X, p.Y));
  2815. else
  2816. writer.WriteNull();
  2817. }
  2818. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  2819. {
  2820. throw new NotImplementedException();
  2821. }
  2822. public override bool CanConvert(Type objectType)
  2823. {
  2824. return objectType.IsAssignableFrom(typeof (Pos));
  2825. }
  2826. }
  2827. public class PosDoubleConverter : JsonConverter
  2828. {
  2829. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  2830. {
  2831. PosDouble p = (PosDouble) value;
  2832. if (p != null)
  2833. writer.WriteRawValue(String.Format(CultureInfo.InvariantCulture, "new PosD({0},{1})", p.X, p.Y));
  2834. else
  2835. writer.WriteNull();
  2836. }
  2837. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  2838. {
  2839. throw new NotImplementedException();
  2840. }
  2841. public override bool CanConvert(Type objectType)
  2842. {
  2843. return objectType.IsAssignableFrom(typeof (PosDouble));
  2844. }
  2845. }
  2846. [Test]
  2847. public void TestEscapeDictionaryStrings()
  2848. {
  2849. const string s = @"host\user";
  2850. string serialized = JsonConvert.SerializeObject(s);
  2851. Assert.AreEqual(@"""host\\user""", serialized);
  2852. Dictionary<int, object> d1 = new Dictionary<int, object>();
  2853. d1.Add(5, s);
  2854. Assert.AreEqual(@"{""5"":""host\\user""}", JsonConvert.SerializeObject(d1));
  2855. Dictionary<string, object> d2 = new Dictionary<string, object>();
  2856. d2.Add(s, 5);
  2857. Assert.AreEqual(@"{""host\\user"":5}", JsonConvert.SerializeObject(d2));
  2858. }
  2859. public class GenericListTestClass
  2860. {
  2861. public List<string> GenericList { get; set; }
  2862. public GenericListTestClass()
  2863. {
  2864. GenericList = new List<string>();
  2865. }
  2866. }
  2867. [Test]
  2868. public void DeserializeExistingGenericList()
  2869. {
  2870. GenericListTestClass c = new GenericListTestClass();
  2871. c.GenericList.Add("1");
  2872. c.GenericList.Add("2");
  2873. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  2874. GenericListTestClass newValue = JsonConvert.DeserializeObject<GenericListTestClass>(json);
  2875. Assert.AreEqual(2, newValue.GenericList.Count);
  2876. Assert.AreEqual(typeof (List<string>), newValue.GenericList.GetType());
  2877. }
  2878. [Test]
  2879. public void DeserializeSimpleKeyValuePair()
  2880. {
  2881. List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
  2882. list.Add(new KeyValuePair<string, string>("key1", "value1"));
  2883. list.Add(new KeyValuePair<string, string>("key2", "value2"));
  2884. string json = JsonConvert.SerializeObject(list);
  2885. Assert.AreEqual(@"[{""Key"":""key1"",""Value"":""value1""},{""Key"":""key2"",""Value"":""value2""}]", json);
  2886. List<KeyValuePair<string, string>> result = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(json);
  2887. Assert.AreEqual(2, result.Count);
  2888. Assert.AreEqual("key1", result[0].Key);
  2889. Assert.AreEqual("value1", result[0].Value);
  2890. Assert.AreEqual("key2", result[1].Key);
  2891. Assert.AreEqual("value2", result[1].Value);
  2892. }
  2893. [Test]
  2894. public void DeserializeComplexKeyValuePair()
  2895. {
  2896. DateTime dateTime = new DateTime(2000, 12, 1, 23, 1, 1, DateTimeKind.Utc);
  2897. List<KeyValuePair<string, WagePerson>> list = new List<KeyValuePair<string, WagePerson>>();
  2898. list.Add(new KeyValuePair<string, WagePerson>("key1", new WagePerson
  2899. {
  2900. BirthDate = dateTime,
  2901. Department = "Department1",
  2902. LastModified = dateTime,
  2903. HourlyWage = 1
  2904. }));
  2905. list.Add(new KeyValuePair<string, WagePerson>("key2", new WagePerson
  2906. {
  2907. BirthDate = dateTime,
  2908. Department = "Department2",
  2909. LastModified = dateTime,
  2910. HourlyWage = 2
  2911. }));
  2912. string json = JsonConvert.SerializeObject(list, Formatting.Indented);
  2913. Assert.AreEqual(@"[
  2914. {
  2915. ""Key"": ""key1"",
  2916. ""Value"": {
  2917. ""HourlyWage"": 1.0,
  2918. ""Name"": null,
  2919. ""BirthDate"": ""2000-12-01T23:01:01Z"",
  2920. ""LastModified"": ""2000-12-01T23:01:01Z""
  2921. }
  2922. },
  2923. {
  2924. ""Key"": ""key2"",
  2925. ""Value"": {
  2926. ""HourlyWage"": 2.0,
  2927. ""Name"": null,
  2928. ""BirthDate"": ""2000-12-01T23:01:01Z"",
  2929. ""LastModified"": ""2000-12-01T23:01:01Z""
  2930. }
  2931. }
  2932. ]", json);
  2933. List<KeyValuePair<string, WagePerson>> result = JsonConvert.DeserializeObject<List<KeyValuePair<string, WagePerson>>>(json);
  2934. Assert.AreEqual(2, result.Count);
  2935. Assert.AreEqual("key1", result[0].Key);
  2936. Assert.AreEqual(1, result[0].Value.HourlyWage);
  2937. Assert.AreEqual("key2", result[1].Key);
  2938. Assert.AreEqual(2, result[1].Value.HourlyWage);
  2939. }
  2940. public class StringListAppenderConverter : JsonConverter
  2941. {
  2942. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  2943. {
  2944. writer.WriteValue(value);
  2945. }
  2946. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  2947. {
  2948. List<string> existingStrings = (List<string>) existingValue;
  2949. List<string> newStrings = new List<string>(existingStrings);
  2950. reader.Read();
  2951. while (reader.TokenType != JsonToken.EndArray)
  2952. {
  2953. string s = (string) reader.Value;
  2954. newStrings.Add(s);
  2955. reader.Read();
  2956. }
  2957. return newStrings;
  2958. }
  2959. public override bool CanConvert(Type objectType)
  2960. {
  2961. return (objectType == typeof (List<string>));
  2962. }
  2963. }
  2964. [Test]
  2965. public void StringListAppenderConverterTest()
  2966. {
  2967. Movie p = new Movie();
  2968. p.ReleaseCountries = new List<string> {"Existing"};
  2969. JsonConvert.PopulateObject("{'ReleaseCountries':['Appended']}", p, new JsonSerializerSettings
  2970. {
  2971. Converters = new List<JsonConverter> {new StringListAppenderConverter()}
  2972. });
  2973. Assert.AreEqual(2, p.ReleaseCountries.Count);
  2974. Assert.AreEqual("Existing", p.ReleaseCountries[0]);
  2975. Assert.AreEqual("Appended", p.ReleaseCountries[1]);
  2976. }
  2977. public class StringAppenderConverter : JsonConverter
  2978. {
  2979. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  2980. {
  2981. writer.WriteValue(value);
  2982. }
  2983. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  2984. {
  2985. string existingString = (string) existingValue;
  2986. string newString = existingString + (string) reader.Value;
  2987. return newString;
  2988. }
  2989. public override bool CanConvert(Type objectType)
  2990. {
  2991. return (objectType == typeof (string));
  2992. }
  2993. }
  2994. [Test]
  2995. public void StringAppenderConverterTest()
  2996. {
  2997. Movie p = new Movie();
  2998. p.Name = "Existing,";
  2999. JsonConvert.PopulateObject("{'Name':'Appended'}", p, new JsonSerializerSettings
  3000. {
  3001. Converters = new List<JsonConverter> {new StringAppenderConverter()}
  3002. });
  3003. Assert.AreEqual("Existing,Appended", p.Name);
  3004. }
  3005. [Test]
  3006. [ExpectedException(typeof (JsonSerializationException)
  3007. #if !NETFX_CORE
  3008. , ExpectedMessage = "Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Line 6, position 11."
  3009. #endif
  3010. )]
  3011. public void SerializeRefAdditionalContent()
  3012. {
  3013. //Additional text found in JSON string after finishing deserializing object.
  3014. //Test 1
  3015. var reference = new Dictionary<string, object>();
  3016. reference.Add("$ref", "Persons");
  3017. reference.Add("$id", 1);
  3018. var child = new Dictionary<string, object>();
  3019. child.Add("_id", 2);
  3020. child.Add("Name", "Isabell");
  3021. child.Add("Father", reference);
  3022. var json = JsonConvert.SerializeObject(child, Formatting.Indented);
  3023. JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  3024. }
  3025. [Test]
  3026. public void SerializeRefBadType()
  3027. {
  3028. ExceptionAssert.Throws<JsonSerializationException>("JSON reference $ref property must have a string or null value. Line 5, position 14.",
  3029. () =>
  3030. {
  3031. //Additional text found in JSON string after finishing deserializing object.
  3032. //Test 1
  3033. var reference = new Dictionary<string, object>();
  3034. reference.Add("$ref", 1);
  3035. reference.Add("$id", 1);
  3036. var child = new Dictionary<string, object>();
  3037. child.Add("_id", 2);
  3038. child.Add("Name", "Isabell");
  3039. child.Add("Father", reference);
  3040. var json = JsonConvert.SerializeObject(child, Formatting.Indented);
  3041. JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  3042. });
  3043. }
  3044. [Test]
  3045. public void SerializeRefNull()
  3046. {
  3047. var reference = new Dictionary<string, object>();
  3048. reference.Add("$ref", null);
  3049. reference.Add("$id", null);
  3050. reference.Add("blah", "blah!");
  3051. var child = new Dictionary<string, object>();
  3052. child.Add("_id", 2);
  3053. child.Add("Name", "Isabell");
  3054. child.Add("Father", reference);
  3055. var json = JsonConvert.SerializeObject(child);
  3056. Dictionary<string, object> result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  3057. Assert.AreEqual(3, result.Count);
  3058. Assert.AreEqual(1, ((JObject) result["Father"]).Count);
  3059. Assert.AreEqual("blah!", (string) ((JObject) result["Father"])["blah"]);
  3060. }
  3061. public class ConstructorCompexIgnoredProperty
  3062. {
  3063. [JsonIgnore]
  3064. public Product Ignored { get; set; }
  3065. public string First { get; set; }
  3066. public int Second { get; set; }
  3067. public ConstructorCompexIgnoredProperty(string first, int second)
  3068. {
  3069. First = first;
  3070. Second = second;
  3071. }
  3072. }
  3073. [Test]
  3074. public void DeserializeIgnoredPropertyInConstructor()
  3075. {
  3076. string json = @"{""First"":""First"",""Second"":2,""Ignored"":{""Name"":""James""},""AdditionalContent"":{""LOL"":true}}";
  3077. ConstructorCompexIgnoredProperty cc = JsonConvert.DeserializeObject<ConstructorCompexIgnoredProperty>(json);
  3078. Assert.AreEqual("First", cc.First);
  3079. Assert.AreEqual(2, cc.Second);
  3080. Assert.AreEqual(null, cc.Ignored);
  3081. }
  3082. public class ShouldSerializeTestClass
  3083. {
  3084. internal bool _shouldSerializeName;
  3085. public string Name { get; set; }
  3086. public int Age { get; set; }
  3087. public void ShouldSerializeAge()
  3088. {
  3089. // dummy. should never be used because it doesn't return bool
  3090. }
  3091. public bool ShouldSerializeName()
  3092. {
  3093. return _shouldSerializeName;
  3094. }
  3095. }
  3096. [Test]
  3097. public void ShouldSerializeTest()
  3098. {
  3099. ShouldSerializeTestClass c = new ShouldSerializeTestClass();
  3100. c.Name = "James";
  3101. c.Age = 27;
  3102. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3103. Assert.AreEqual(@"{
  3104. ""Age"": 27
  3105. }", json);
  3106. c._shouldSerializeName = true;
  3107. json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3108. Assert.AreEqual(@"{
  3109. ""Name"": ""James"",
  3110. ""Age"": 27
  3111. }", json);
  3112. ShouldSerializeTestClass deserialized = JsonConvert.DeserializeObject<ShouldSerializeTestClass>(json);
  3113. Assert.AreEqual("James", deserialized.Name);
  3114. Assert.AreEqual(27, deserialized.Age);
  3115. }
  3116. public class Employee
  3117. {
  3118. public string Name { get; set; }
  3119. public Employee Manager { get; set; }
  3120. public bool ShouldSerializeManager()
  3121. {
  3122. return (Manager != this);
  3123. }
  3124. }
  3125. [Test]
  3126. public void ShouldSerializeExample()
  3127. {
  3128. Employee joe = new Employee();
  3129. joe.Name = "Joe Employee";
  3130. Employee mike = new Employee();
  3131. mike.Name = "Mike Manager";
  3132. joe.Manager = mike;
  3133. mike.Manager = mike;
  3134. string json = JsonConvert.SerializeObject(new[] {joe, mike}, Formatting.Indented);
  3135. // [
  3136. // {
  3137. // "Name": "Joe Employee",
  3138. // "Manager": {
  3139. // "Name": "Mike Manager"
  3140. // }
  3141. // },
  3142. // {
  3143. // "Name": "Mike Manager"
  3144. // }
  3145. // ]
  3146. Console.WriteLine(json);
  3147. }
  3148. public class SpecifiedTestClass
  3149. {
  3150. private bool _nameSpecified;
  3151. public string Name { get; set; }
  3152. public int Age { get; set; }
  3153. public int Weight { get; set; }
  3154. public int Height { get; set; }
  3155. public int FavoriteNumber { get; set; }
  3156. // dummy. should never be used because it isn't of type bool
  3157. [JsonIgnore]
  3158. public long AgeSpecified { get; set; }
  3159. [JsonIgnore]
  3160. public bool NameSpecified
  3161. {
  3162. get { return _nameSpecified; }
  3163. set { _nameSpecified = value; }
  3164. }
  3165. [JsonIgnore] public bool WeightSpecified;
  3166. [JsonIgnore] [System.Xml.Serialization.XmlIgnoreAttribute] public bool HeightSpecified;
  3167. [JsonIgnore]
  3168. public bool FavoriteNumberSpecified
  3169. {
  3170. // get only example
  3171. get { return FavoriteNumber != 0; }
  3172. }
  3173. }
  3174. [Test]
  3175. public void SpecifiedTest()
  3176. {
  3177. SpecifiedTestClass c = new SpecifiedTestClass();
  3178. c.Name = "James";
  3179. c.Age = 27;
  3180. c.NameSpecified = false;
  3181. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3182. Assert.AreEqual(@"{
  3183. ""Age"": 27
  3184. }", json);
  3185. SpecifiedTestClass deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json);
  3186. Assert.IsNull(deserialized.Name);
  3187. Assert.IsFalse(deserialized.NameSpecified);
  3188. Assert.IsFalse(deserialized.WeightSpecified);
  3189. Assert.IsFalse(deserialized.HeightSpecified);
  3190. Assert.IsFalse(deserialized.FavoriteNumberSpecified);
  3191. Assert.AreEqual(27, deserialized.Age);
  3192. c.NameSpecified = true;
  3193. c.WeightSpecified = true;
  3194. c.HeightSpecified = true;
  3195. c.FavoriteNumber = 23;
  3196. json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3197. Assert.AreEqual(@"{
  3198. ""Name"": ""James"",
  3199. ""Age"": 27,
  3200. ""Weight"": 0,
  3201. ""Height"": 0,
  3202. ""FavoriteNumber"": 23
  3203. }", json);
  3204. deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json);
  3205. Assert.AreEqual("James", deserialized.Name);
  3206. Assert.IsTrue(deserialized.NameSpecified);
  3207. Assert.IsTrue(deserialized.WeightSpecified);
  3208. Assert.IsTrue(deserialized.HeightSpecified);
  3209. Assert.IsTrue(deserialized.FavoriteNumberSpecified);
  3210. Assert.AreEqual(27, deserialized.Age);
  3211. Assert.AreEqual(23, deserialized.FavoriteNumber);
  3212. }
  3213. // [Test]
  3214. // public void XmlSerializerSpecifiedTrueTest()
  3215. // {
  3216. // XmlSerializer s = new XmlSerializer(typeof(OptionalOrder));
  3217. // StringWriter sw = new StringWriter();
  3218. // s.Serialize(sw, new OptionalOrder() { FirstOrder = "First", FirstOrderSpecified = true });
  3219. // Console.WriteLine(sw.ToString());
  3220. // string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
  3221. //<OptionalOrder xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  3222. // <FirstOrder>First</FirstOrder>
  3223. //</OptionalOrder>";
  3224. // OptionalOrder o = (OptionalOrder)s.Deserialize(new StringReader(xml));
  3225. // Console.WriteLine(o.FirstOrder);
  3226. // Console.WriteLine(o.FirstOrderSpecified);
  3227. // }
  3228. // [Test]
  3229. // public void XmlSerializerSpecifiedFalseTest()
  3230. // {
  3231. // XmlSerializer s = new XmlSerializer(typeof(OptionalOrder));
  3232. // StringWriter sw = new StringWriter();
  3233. // s.Serialize(sw, new OptionalOrder() { FirstOrder = "First", FirstOrderSpecified = false });
  3234. // Console.WriteLine(sw.ToString());
  3235. // // string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
  3236. // //<OptionalOrder xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  3237. // // <FirstOrder>First</FirstOrder>
  3238. // //</OptionalOrder>";
  3239. // // OptionalOrder o = (OptionalOrder)s.Deserialize(new StringReader(xml));
  3240. // // Console.WriteLine(o.FirstOrder);
  3241. // // Console.WriteLine(o.FirstOrderSpecified);
  3242. // }
  3243. public class OptionalOrder
  3244. {
  3245. // This field shouldn't be serialized
  3246. // if it is uninitialized.
  3247. public string FirstOrder;
  3248. // Use the XmlIgnoreAttribute to ignore the
  3249. // special field named "FirstOrderSpecified".
  3250. [System.Xml.Serialization.XmlIgnoreAttribute] public bool FirstOrderSpecified;
  3251. }
  3252. public class FamilyDetails
  3253. {
  3254. public string Name { get; set; }
  3255. public int NumberOfChildren { get; set; }
  3256. [JsonIgnore]
  3257. public bool NumberOfChildrenSpecified { get; set; }
  3258. }
  3259. [Test]
  3260. public void SpecifiedExample()
  3261. {
  3262. FamilyDetails joe = new FamilyDetails();
  3263. joe.Name = "Joe Family Details";
  3264. joe.NumberOfChildren = 4;
  3265. joe.NumberOfChildrenSpecified = true;
  3266. FamilyDetails martha = new FamilyDetails();
  3267. martha.Name = "Martha Family Details";
  3268. martha.NumberOfChildren = 3;
  3269. martha.NumberOfChildrenSpecified = false;
  3270. string json = JsonConvert.SerializeObject(new[] {joe, martha}, Formatting.Indented);
  3271. //[
  3272. // {
  3273. // "Name": "Joe Family Details",
  3274. // "NumberOfChildren": 4
  3275. // },
  3276. // {
  3277. // "Name": "Martha Family Details"
  3278. // }
  3279. //]
  3280. Console.WriteLine(json);
  3281. string mikeString = "{\"Name\": \"Mike Person\"}";
  3282. FamilyDetails mike = JsonConvert.DeserializeObject<FamilyDetails>(mikeString);
  3283. Console.WriteLine("mikeString specifies number of children: {0}", mike.NumberOfChildrenSpecified);
  3284. string mikeFullDisclosureString = "{\"Name\": \"Mike Person\", \"NumberOfChildren\": \"0\"}";
  3285. mike = JsonConvert.DeserializeObject<FamilyDetails>(mikeFullDisclosureString);
  3286. Console.WriteLine("mikeString specifies number of children: {0}", mike.NumberOfChildrenSpecified);
  3287. }
  3288. public class DictionaryKey
  3289. {
  3290. public string Value { get; set; }
  3291. public override string ToString()
  3292. {
  3293. return Value;
  3294. }
  3295. public static implicit operator DictionaryKey(string value)
  3296. {
  3297. return new DictionaryKey() {Value = value};
  3298. }
  3299. }
  3300. [Test]
  3301. public void SerializeDeserializeDictionaryKey()
  3302. {
  3303. Dictionary<DictionaryKey, string> dictionary = new Dictionary<DictionaryKey, string>();
  3304. dictionary.Add(new DictionaryKey() {Value = "First!"}, "First");
  3305. dictionary.Add(new DictionaryKey() {Value = "Second!"}, "Second");
  3306. string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
  3307. Assert.AreEqual(@"{
  3308. ""First!"": ""First"",
  3309. ""Second!"": ""Second""
  3310. }", json);
  3311. Dictionary<DictionaryKey, string> newDictionary =
  3312. JsonConvert.DeserializeObject<Dictionary<DictionaryKey, string>>(json);
  3313. Assert.AreEqual(2, newDictionary.Count);
  3314. }
  3315. [Test]
  3316. public void SerializeNullableArray()
  3317. {
  3318. string jsonText = JsonConvert.SerializeObject(new double?[] {2.4, 4.3, null}, Formatting.Indented);
  3319. Assert.AreEqual(@"[
  3320. 2.4,
  3321. 4.3,
  3322. null
  3323. ]", jsonText);
  3324. double?[] d = (double?[]) JsonConvert.DeserializeObject(jsonText, typeof (double?[]));
  3325. Assert.AreEqual(3, d.Length);
  3326. Assert.AreEqual(2.4, d[0]);
  3327. Assert.AreEqual(4.3, d[1]);
  3328. Assert.AreEqual(null, d[2]);
  3329. }
  3330. #if !SILVERLIGHT && !NET20 && !PocketPC
  3331. [Test]
  3332. public void SerializeHashSet()
  3333. {
  3334. string jsonText = JsonConvert.SerializeObject(new HashSet<string>()
  3335. {
  3336. "One",
  3337. "2",
  3338. "III"
  3339. }, Formatting.Indented);
  3340. Assert.AreEqual(@"[
  3341. ""One"",
  3342. ""2"",
  3343. ""III""
  3344. ]", jsonText);
  3345. HashSet<string> d = JsonConvert.DeserializeObject<HashSet<string>>(jsonText);
  3346. Assert.AreEqual(3, d.Count);
  3347. Assert.IsTrue(d.Contains("One"));
  3348. Assert.IsTrue(d.Contains("2"));
  3349. Assert.IsTrue(d.Contains("III"));
  3350. }
  3351. #endif
  3352. private class MyClass
  3353. {
  3354. public byte[] Prop1 { get; set; }
  3355. public MyClass()
  3356. {
  3357. Prop1 = new byte[0];
  3358. }
  3359. }
  3360. [Test]
  3361. public void DeserializeByteArray()
  3362. {
  3363. JsonSerializer serializer1 = new JsonSerializer();
  3364. serializer1.Converters.Add(new IsoDateTimeConverter());
  3365. serializer1.NullValueHandling = NullValueHandling.Ignore;
  3366. string json = @"[{""Prop1"":""""},{""Prop1"":""""}]";
  3367. JsonTextReader reader = new JsonTextReader(new StringReader(json));
  3368. MyClass[] z = (MyClass[]) serializer1.Deserialize(reader, typeof (MyClass[]));
  3369. Assert.AreEqual(2, z.Length);
  3370. Assert.AreEqual(0, z[0].Prop1.Length);
  3371. Assert.AreEqual(0, z[1].Prop1.Length);
  3372. }
  3373. #if !NET20 && !PocketPC && !SILVERLIGHT && !NETFX_CORE
  3374. public class StringDictionaryTestClass
  3375. {
  3376. public StringDictionary StringDictionaryProperty { get; set; }
  3377. }
  3378. [Test]
  3379. [ExpectedException(typeof (Exception), ExpectedMessage = "Cannot create and populate list type System.Collections.Specialized.StringDictionary.")]
  3380. public void StringDictionaryTest()
  3381. {
  3382. StringDictionaryTestClass s1 = new StringDictionaryTestClass()
  3383. {
  3384. StringDictionaryProperty = new StringDictionary()
  3385. {
  3386. {"1", "One"},
  3387. {"2", "II"},
  3388. {"3", "3"}
  3389. }
  3390. };
  3391. string json = JsonConvert.SerializeObject(s1, Formatting.Indented);
  3392. JsonConvert.DeserializeObject<StringDictionaryTestClass>(json);
  3393. }
  3394. #endif
  3395. [JsonObject(MemberSerialization.OptIn)]
  3396. public struct StructWithAttribute
  3397. {
  3398. public string MyString { get; set; }
  3399. [JsonProperty]
  3400. public int MyInt { get; set; }
  3401. }
  3402. [Test]
  3403. public void SerializeStructWithJsonObjectAttribute()
  3404. {
  3405. StructWithAttribute testStruct = new StructWithAttribute
  3406. {
  3407. MyInt = int.MaxValue
  3408. };
  3409. string json = JsonConvert.SerializeObject(testStruct, Formatting.Indented);
  3410. Assert.AreEqual(@"{
  3411. ""MyInt"": 2147483647
  3412. }", json);
  3413. StructWithAttribute newStruct = JsonConvert.DeserializeObject<StructWithAttribute>(json);
  3414. Assert.AreEqual(int.MaxValue, newStruct.MyInt);
  3415. }
  3416. public class TimeZoneOffsetObject
  3417. {
  3418. public DateTimeOffset Offset { get; set; }
  3419. }
  3420. #if !NET20
  3421. [Test]
  3422. public void ReadWriteTimeZoneOffsetIso()
  3423. {
  3424. var serializeObject = JsonConvert.SerializeObject(new TimeZoneOffsetObject
  3425. {
  3426. Offset = new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6))
  3427. });
  3428. Assert.AreEqual("{\"Offset\":\"2000-01-01T00:00:00+06:00\"}", serializeObject);
  3429. var deserializeObject = JsonConvert.DeserializeObject<TimeZoneOffsetObject>(serializeObject);
  3430. Assert.AreEqual(TimeSpan.FromHours(6), deserializeObject.Offset.Offset);
  3431. Assert.AreEqual(new DateTime(2000, 1, 1), deserializeObject.Offset.Date);
  3432. }
  3433. [Test]
  3434. public void DeserializePropertyNullableDateTimeOffsetExactIso()
  3435. {
  3436. NullableDateTimeTestClass d = JsonConvert.DeserializeObject<NullableDateTimeTestClass>("{\"DateTimeOffsetField\":\"2000-01-01T00:00:00+06:00\"}");
  3437. Assert.AreEqual(new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6)), d.DateTimeOffsetField);
  3438. }
  3439. [Test]
  3440. public void ReadWriteTimeZoneOffsetMsAjax()
  3441. {
  3442. var serializeObject = JsonConvert.SerializeObject(new TimeZoneOffsetObject
  3443. {
  3444. Offset = new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6))
  3445. }, Formatting.None, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
  3446. Assert.AreEqual("{\"Offset\":\"\\/Date(946663200000+0600)\\/\"}", serializeObject);
  3447. var deserializeObject = JsonConvert.DeserializeObject<TimeZoneOffsetObject>(serializeObject);
  3448. Assert.AreEqual(TimeSpan.FromHours(6), deserializeObject.Offset.Offset);
  3449. Assert.AreEqual(new DateTime(2000, 1, 1), deserializeObject.Offset.Date);
  3450. }
  3451. [Test]
  3452. public void DeserializePropertyNullableDateTimeOffsetExactMsAjax()
  3453. {
  3454. NullableDateTimeTestClass d = JsonConvert.DeserializeObject<NullableDateTimeTestClass>("{\"DateTimeOffsetField\":\"\\/Date(946663200000+0600)\\/\"}");
  3455. Assert.AreEqual(new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6)), d.DateTimeOffsetField);
  3456. }
  3457. #endif
  3458. public abstract class LogEvent
  3459. {
  3460. [JsonProperty("event")]
  3461. public abstract string EventName { get; }
  3462. }
  3463. public class DerivedEvent : LogEvent
  3464. {
  3465. public override string EventName
  3466. {
  3467. get { return "derived"; }
  3468. }
  3469. }
  3470. [Test]
  3471. public void OverridenPropertyMembers()
  3472. {
  3473. string json = JsonConvert.SerializeObject(new DerivedEvent(), Formatting.Indented);
  3474. Assert.AreEqual(@"{
  3475. ""event"": ""derived""
  3476. }", json);
  3477. }
  3478. #if !(NET35 || NET20 || WINDOWS_PHONE)
  3479. [Test]
  3480. public void SerializeExpandoObject()
  3481. {
  3482. dynamic expando = new ExpandoObject();
  3483. expando.Int = 1;
  3484. expando.Decimal = 99.9d;
  3485. expando.Complex = new ExpandoObject();
  3486. expando.Complex.String = "I am a string";
  3487. expando.Complex.DateTime = new DateTime(2000, 12, 20, 18, 55, 0, DateTimeKind.Utc);
  3488. string json = JsonConvert.SerializeObject(expando, Formatting.Indented);
  3489. Assert.AreEqual(@"{
  3490. ""Int"": 1,
  3491. ""Decimal"": 99.9,
  3492. ""Complex"": {
  3493. ""String"": ""I am a string"",
  3494. ""DateTime"": ""2000-12-20T18:55:00Z""
  3495. }
  3496. }", json);
  3497. IDictionary<string, object> newExpando = JsonConvert.DeserializeObject<ExpandoObject>(json);
  3498. CustomAssert.IsInstanceOfType(typeof (long), newExpando["Int"]);
  3499. Assert.AreEqual((long)expando.Int, newExpando["Int"]);
  3500. CustomAssert.IsInstanceOfType(typeof (double), newExpando["Decimal"]);
  3501. Assert.AreEqual(expando.Decimal, newExpando["Decimal"]);
  3502. CustomAssert.IsInstanceOfType(typeof (ExpandoObject), newExpando["Complex"]);
  3503. IDictionary<string, object> o = (ExpandoObject) newExpando["Complex"];
  3504. CustomAssert.IsInstanceOfType(typeof (string), o["String"]);
  3505. Assert.AreEqual(expando.Complex.String, o["String"]);
  3506. CustomAssert.IsInstanceOfType(typeof (DateTime), o["DateTime"]);
  3507. Assert.AreEqual(expando.Complex.DateTime, o["DateTime"]);
  3508. }
  3509. #endif
  3510. [Test]
  3511. public void DeserializeDecimalExact()
  3512. {
  3513. decimal d = JsonConvert.DeserializeObject<decimal>("123456789876543.21");
  3514. Assert.AreEqual(123456789876543.21m, d);
  3515. }
  3516. [Test]
  3517. public void DeserializeNullableDecimalExact()
  3518. {
  3519. decimal? d = JsonConvert.DeserializeObject<decimal?>("123456789876543.21");
  3520. Assert.AreEqual(123456789876543.21m, d);
  3521. }
  3522. [Test]
  3523. public void DeserializeDecimalPropertyExact()
  3524. {
  3525. string json = "{Amount:123456789876543.21}";
  3526. Invoice i = JsonConvert.DeserializeObject<Invoice>(json);
  3527. Assert.AreEqual(123456789876543.21m, i.Amount);
  3528. }
  3529. [Test]
  3530. public void DeserializeDecimalArrayExact()
  3531. {
  3532. string json = "[123456789876543.21]";
  3533. IList<decimal> a = JsonConvert.DeserializeObject<IList<decimal>>(json);
  3534. Assert.AreEqual(123456789876543.21m, a[0]);
  3535. }
  3536. [Test]
  3537. public void DeserializeDecimalDictionaryExact()
  3538. {
  3539. string json = "{'Value':123456789876543.21}";
  3540. IDictionary<string, decimal> d = JsonConvert.DeserializeObject<IDictionary<string, decimal>>(json);
  3541. Assert.AreEqual(123456789876543.21m, d["Value"]);
  3542. }
  3543. public struct Vector
  3544. {
  3545. public float X;
  3546. public float Y;
  3547. public float Z;
  3548. public override string ToString()
  3549. {
  3550. return string.Format("({0},{1},{2})", X, Y, Z);
  3551. }
  3552. }
  3553. public class VectorParent
  3554. {
  3555. public Vector Position;
  3556. }
  3557. [Test]
  3558. public void DeserializeStructProperty()
  3559. {
  3560. VectorParent obj = new VectorParent();
  3561. obj.Position = new Vector {X = 1, Y = 2, Z = 3};
  3562. string str = JsonConvert.SerializeObject(obj);
  3563. obj = JsonConvert.DeserializeObject<VectorParent>(str);
  3564. Assert.AreEqual(1, obj.Position.X);
  3565. Assert.AreEqual(2, obj.Position.Y);
  3566. Assert.AreEqual(3, obj.Position.Z);
  3567. }
  3568. [JsonObject(MemberSerialization.OptIn)]
  3569. public class Derived : Base
  3570. {
  3571. [JsonProperty]
  3572. public string IDoWork { get; private set; }
  3573. private Derived()
  3574. {
  3575. }
  3576. internal Derived(string dontWork, string doWork)
  3577. : base(dontWork)
  3578. {
  3579. IDoWork = doWork;
  3580. }
  3581. }
  3582. [JsonObject(MemberSerialization.OptIn)]
  3583. public class Base
  3584. {
  3585. [JsonProperty]
  3586. public string IDontWork { get; private set; }
  3587. protected Base()
  3588. {
  3589. }
  3590. internal Base(string dontWork)
  3591. {
  3592. IDontWork = dontWork;
  3593. }
  3594. }
  3595. [Test]
  3596. public void PrivateSetterOnBaseClassProperty()
  3597. {
  3598. var derived = new Derived("meh", "woo");
  3599. var settings = new JsonSerializerSettings
  3600. {
  3601. TypeNameHandling = TypeNameHandling.Objects,
  3602. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
  3603. };
  3604. string json = JsonConvert.SerializeObject(derived, Formatting.Indented, settings);
  3605. var meh = JsonConvert.DeserializeObject<Base>(json, settings);
  3606. Assert.AreEqual(((Derived) meh).IDoWork, "woo");
  3607. Assert.AreEqual(meh.IDontWork, "meh");
  3608. }
  3609. #if !(SILVERLIGHT || PocketPC || NET20 || NETFX_CORE)
  3610. [DataContract]
  3611. public struct StructISerializable : ISerializable
  3612. {
  3613. private string _name;
  3614. public StructISerializable(SerializationInfo info, StreamingContext context)
  3615. {
  3616. _name = info.GetString("Name");
  3617. }
  3618. [DataMember]
  3619. public string Name
  3620. {
  3621. get { return _name; }
  3622. set { _name = value; }
  3623. }
  3624. public void GetObjectData(SerializationInfo info, StreamingContext context)
  3625. {
  3626. info.AddValue("Name", _name);
  3627. }
  3628. }
  3629. [DataContract]
  3630. public class NullableStructPropertyClass
  3631. {
  3632. private StructISerializable _foo1;
  3633. private StructISerializable? _foo2;
  3634. [DataMember]
  3635. public StructISerializable Foo1
  3636. {
  3637. get { return _foo1; }
  3638. set { _foo1 = value; }
  3639. }
  3640. [DataMember]
  3641. public StructISerializable? Foo2
  3642. {
  3643. get { return _foo2; }
  3644. set { _foo2 = value; }
  3645. }
  3646. }
  3647. [Test]
  3648. public void DeserializeNullableStruct()
  3649. {
  3650. NullableStructPropertyClass nullableStructPropertyClass = new NullableStructPropertyClass();
  3651. nullableStructPropertyClass.Foo1 = new StructISerializable() {Name = "foo 1"};
  3652. nullableStructPropertyClass.Foo2 = new StructISerializable() {Name = "foo 2"};
  3653. NullableStructPropertyClass barWithNull = new NullableStructPropertyClass();
  3654. barWithNull.Foo1 = new StructISerializable() {Name = "foo 1"};
  3655. barWithNull.Foo2 = null;
  3656. //throws error on deserialization because bar1.Foo2 is of type Foo?
  3657. string s = JsonConvert.SerializeObject(nullableStructPropertyClass);
  3658. NullableStructPropertyClass deserialized = deserialize(s);
  3659. Assert.AreEqual(deserialized.Foo1.Name, "foo 1");
  3660. Assert.AreEqual(deserialized.Foo2.Value.Name, "foo 2");
  3661. //no error Foo2 is null
  3662. s = JsonConvert.SerializeObject(barWithNull);
  3663. deserialized = deserialize(s);
  3664. Assert.AreEqual(deserialized.Foo1.Name, "foo 1");
  3665. Assert.AreEqual(deserialized.Foo2, null);
  3666. }
  3667. private static NullableStructPropertyClass deserialize(string serStr)
  3668. {
  3669. return JsonConvert.DeserializeObject<NullableStructPropertyClass>(
  3670. serStr,
  3671. new JsonSerializerSettings
  3672. {
  3673. NullValueHandling = NullValueHandling.Ignore,
  3674. MissingMemberHandling = MissingMemberHandling.Ignore
  3675. });
  3676. }
  3677. #endif
  3678. public class Response
  3679. {
  3680. public string Name { get; set; }
  3681. public JToken Data { get; set; }
  3682. }
  3683. [Test]
  3684. public void DeserializeJToken()
  3685. {
  3686. Response response = new Response
  3687. {
  3688. Name = "Success",
  3689. Data = new JObject(new JProperty("First", "Value1"), new JProperty("Second", "Value2"))
  3690. };
  3691. string json = JsonConvert.SerializeObject(response, Formatting.Indented);
  3692. Response deserializedResponse = JsonConvert.DeserializeObject<Response>(json);
  3693. Assert.AreEqual("Success", deserializedResponse.Name);
  3694. Assert.IsTrue(deserializedResponse.Data.DeepEquals(response.Data));
  3695. }
  3696. public abstract class Test<T>
  3697. {
  3698. public abstract T Value { get; set; }
  3699. }
  3700. [JsonObject(MemberSerialization.OptIn)]
  3701. public class DecimalTest : Test<decimal>
  3702. {
  3703. protected DecimalTest()
  3704. {
  3705. }
  3706. public DecimalTest(decimal val)
  3707. {
  3708. Value = val;
  3709. }
  3710. [JsonProperty]
  3711. public override decimal Value { get; set; }
  3712. }
  3713. [Test]
  3714. public void OnError()
  3715. {
  3716. var data = new DecimalTest(decimal.MinValue);
  3717. var json = JsonConvert.SerializeObject(data);
  3718. var obj = JsonConvert.DeserializeObject<DecimalTest>(json);
  3719. Assert.AreEqual(decimal.MinValue, obj.Value);
  3720. }
  3721. public class NonPublicConstructorWithJsonConstructor
  3722. {
  3723. public string Value { get; private set; }
  3724. public string Constructor { get; private set; }
  3725. [JsonConstructor]
  3726. private NonPublicConstructorWithJsonConstructor()
  3727. {
  3728. Constructor = "NonPublic";
  3729. }
  3730. public NonPublicConstructorWithJsonConstructor(string value)
  3731. {
  3732. Value = value;
  3733. Constructor = "Public Paramatized";
  3734. }
  3735. }
  3736. [Test]
  3737. public void NonPublicConstructorWithJsonConstructorTest()
  3738. {
  3739. NonPublicConstructorWithJsonConstructor c = JsonConvert.DeserializeObject<NonPublicConstructorWithJsonConstructor>("{}");
  3740. Assert.AreEqual("NonPublic", c.Constructor);
  3741. }
  3742. public class PublicConstructorOverridenByJsonConstructor
  3743. {
  3744. public string Value { get; private set; }
  3745. public string Constructor { get; private set; }
  3746. public PublicConstructorOverridenByJsonConstructor()
  3747. {
  3748. Constructor = "NonPublic";
  3749. }
  3750. [JsonConstructor]
  3751. public PublicConstructorOverridenByJsonConstructor(string value)
  3752. {
  3753. Value = value;
  3754. Constructor = "Public Paramatized";
  3755. }
  3756. }
  3757. [Test]
  3758. public void PublicConstructorOverridenByJsonConstructorTest()
  3759. {
  3760. PublicConstructorOverridenByJsonConstructor c = JsonConvert.DeserializeObject<PublicConstructorOverridenByJsonConstructor>("{Value:'value!'}");
  3761. Assert.AreEqual("Public Paramatized", c.Constructor);
  3762. Assert.AreEqual("value!", c.Value);
  3763. }
  3764. public class MultipleParamatrizedConstructorsJsonConstructor
  3765. {
  3766. public string Value { get; private set; }
  3767. public int Age { get; private set; }
  3768. public string Constructor { get; private set; }
  3769. public MultipleParamatrizedConstructorsJsonConstructor(string value)
  3770. {
  3771. Value = value;
  3772. Constructor = "Public Paramatized 1";
  3773. }
  3774. [JsonConstructor]
  3775. public MultipleParamatrizedConstructorsJsonConstructor(string value, int age)
  3776. {
  3777. Value = value;
  3778. Age = age;
  3779. Constructor = "Public Paramatized 2";
  3780. }
  3781. }
  3782. [Test]
  3783. public void MultipleParamatrizedConstructorsJsonConstructorTest()
  3784. {
  3785. MultipleParamatrizedConstructorsJsonConstructor c = JsonConvert.DeserializeObject<MultipleParamatrizedConstructorsJsonConstructor>("{Value:'value!', Age:1}");
  3786. Assert.AreEqual("Public Paramatized 2", c.Constructor);
  3787. Assert.AreEqual("value!", c.Value);
  3788. Assert.AreEqual(1, c.Age);
  3789. }
  3790. public class EnumerableClass
  3791. {
  3792. public IEnumerable<string> Enumerable { get; set; }
  3793. }
  3794. [Test]
  3795. public void DeserializeEnumerable()
  3796. {
  3797. EnumerableClass c = new EnumerableClass
  3798. {
  3799. Enumerable = new List<string> {"One", "Two", "Three"}
  3800. };
  3801. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3802. Assert.AreEqual(@"{
  3803. ""Enumerable"": [
  3804. ""One"",
  3805. ""Two"",
  3806. ""Three""
  3807. ]
  3808. }", json);
  3809. EnumerableClass c2 = JsonConvert.DeserializeObject<EnumerableClass>(json);
  3810. Assert.AreEqual("One", c2.Enumerable.ElementAt(0));
  3811. Assert.AreEqual("Two", c2.Enumerable.ElementAt(1));
  3812. Assert.AreEqual("Three", c2.Enumerable.ElementAt(2));
  3813. }
  3814. [JsonObject(MemberSerialization.OptIn)]
  3815. public class ItemBase
  3816. {
  3817. [JsonProperty]
  3818. public string Name { get; set; }
  3819. }
  3820. public class ComplexItem : ItemBase
  3821. {
  3822. public Stream Source { get; set; }
  3823. }
  3824. [Test]
  3825. public void SerializeAttributesOnBase()
  3826. {
  3827. ComplexItem i = new ComplexItem();
  3828. string json = JsonConvert.SerializeObject(i, Formatting.Indented);
  3829. Assert.AreEqual(@"{
  3830. ""Name"": null
  3831. }", json);
  3832. }
  3833. public class DeserializeStringConvert
  3834. {
  3835. public string Name { get; set; }
  3836. public int Age { get; set; }
  3837. public double Height { get; set; }
  3838. public decimal Price { get; set; }
  3839. }
  3840. [Test]
  3841. public void DeserializeStringEnglish()
  3842. {
  3843. string json = @"{
  3844. 'Name': 'James Hughes',
  3845. 'Age': '40',
  3846. 'Height': '44.4',
  3847. 'Price': '4'
  3848. }";
  3849. DeserializeStringConvert p = JsonConvert.DeserializeObject<DeserializeStringConvert>(json);
  3850. Assert.AreEqual(40, p.Age);
  3851. Assert.AreEqual(44.4, p.Height);
  3852. Assert.AreEqual(4m, p.Price);
  3853. }
  3854. [Test]
  3855. [ExpectedException(typeof (JsonSerializationException)
  3856. #if !NETFX_CORE
  3857. , ExpectedMessage = "Error converting value {null} to type 'System.DateTime'. Line 1, position 4."
  3858. #endif
  3859. )]
  3860. public void DeserializeNullDateTimeValueTest()
  3861. {
  3862. JsonConvert.DeserializeObject("null", typeof (DateTime));
  3863. }
  3864. [Test]
  3865. public void DeserializeNullNullableDateTimeValueTest()
  3866. {
  3867. object dateTime = JsonConvert.DeserializeObject("null", typeof (DateTime?));
  3868. Assert.IsNull(dateTime);
  3869. }
  3870. [Test]
  3871. public void MultiIndexSuperTest()
  3872. {
  3873. MultiIndexSuper e = new MultiIndexSuper();
  3874. string json = JsonConvert.SerializeObject(e, Formatting.Indented);
  3875. Assert.AreEqual(@"{}", json);
  3876. }
  3877. public class MultiIndexSuper : MultiIndexBase
  3878. {
  3879. }
  3880. public abstract class MultiIndexBase
  3881. {
  3882. protected internal object this[string propertyName]
  3883. {
  3884. get { return null; }
  3885. set { }
  3886. }
  3887. protected internal object this[object property]
  3888. {
  3889. get { return null; }
  3890. set { }
  3891. }
  3892. }
  3893. public class CommentTestClass
  3894. {
  3895. public bool Indexed { get; set; }
  3896. public int StartYear { get; set; }
  3897. public IList<decimal> Values { get; set; }
  3898. }
  3899. [Test]
  3900. public void CommentTestClassTest()
  3901. {
  3902. string json = @"{""indexed"":true, ""startYear"":1939, ""values"":
  3903. [ 3000, /* 1940-1949 */
  3904. 3000, 3600, 3600, 3600, 3600, 4200, 4200, 4200, 4200, 4800, /* 1950-1959 */
  3905. 4800, 4800, 4800, 4800, 4800, 4800, 6600, 6600, 7800, 7800, /* 1960-1969 */
  3906. 7800, 7800, 9000, 10800, 13200, 14100, 15300, 16500, 17700, 22900, /* 1970-1979 */
  3907. 25900, 29700, 32400, 35700, 37800, 39600, 42000, 43800, 45000, 48000, /* 1980-1989 */
  3908. 51300, 53400, 55500, 57600, 60600, 61200, 62700, 65400, 68400, 72600, /* 1990-1999 */
  3909. 76200, 80400, 84900, 87000, 87900, 90000, 94200, 97500, 102000, 106800, /* 2000-2009 */
  3910. 106800, 106800] /* 2010-2011 */
  3911. }";
  3912. CommentTestClass commentTestClass = JsonConvert.DeserializeObject<CommentTestClass>(json);
  3913. Assert.AreEqual(true, commentTestClass.Indexed);
  3914. Assert.AreEqual(1939, commentTestClass.StartYear);
  3915. Assert.AreEqual(63, commentTestClass.Values.Count);
  3916. }
  3917. private class DTOWithParameterisedConstructor
  3918. {
  3919. public DTOWithParameterisedConstructor(string A)
  3920. {
  3921. this.A = A;
  3922. B = 2;
  3923. }
  3924. public string A { get; set; }
  3925. public int? B { get; set; }
  3926. }
  3927. private class DTOWithoutParameterisedConstructor
  3928. {
  3929. public DTOWithoutParameterisedConstructor()
  3930. {
  3931. B = 2;
  3932. }
  3933. public string A { get; set; }
  3934. public int? B { get; set; }
  3935. }
  3936. [Test]
  3937. public void PopulationBehaviourForOmittedPropertiesIsTheSameForParameterisedConstructorAsForDefaultConstructor()
  3938. {
  3939. string json = @"{A:""Test""}";
  3940. var withoutParameterisedConstructor = JsonConvert.DeserializeObject<DTOWithoutParameterisedConstructor>(json);
  3941. var withParameterisedConstructor = JsonConvert.DeserializeObject<DTOWithParameterisedConstructor>(json);
  3942. Assert.AreEqual(withoutParameterisedConstructor.B, withParameterisedConstructor.B);
  3943. }
  3944. public class EnumerableArrayPropertyClass
  3945. {
  3946. public IEnumerable<int> Numbers
  3947. {
  3948. get
  3949. {
  3950. return new[] {1, 2, 3}; //fails
  3951. //return new List<int>(new[] { 1, 2, 3 }); //works
  3952. }
  3953. }
  3954. }
  3955. [Test]
  3956. public void SkipPopulatingArrayPropertyClass()
  3957. {
  3958. string json = JsonConvert.SerializeObject(new EnumerableArrayPropertyClass());
  3959. JsonConvert.DeserializeObject<EnumerableArrayPropertyClass>(json);
  3960. }
  3961. #if !NET20
  3962. [DataContract]
  3963. public class BaseDataContract
  3964. {
  3965. [DataMember(Name = "virtualMember")]
  3966. public virtual string VirtualMember { get; set; }
  3967. [DataMember(Name = "nonVirtualMember")]
  3968. public string NonVirtualMember { get; set; }
  3969. }
  3970. public class ChildDataContract : BaseDataContract
  3971. {
  3972. public override string VirtualMember { get; set; }
  3973. public string NewMember { get; set; }
  3974. }
  3975. [Test]
  3976. public void ChildDataContractTest()
  3977. {
  3978. ChildDataContract cc = new ChildDataContract
  3979. {
  3980. VirtualMember = "VirtualMember!",
  3981. NonVirtualMember = "NonVirtualMember!"
  3982. };
  3983. string result = JsonConvert.SerializeObject(cc);
  3984. Assert.AreEqual(@"{""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  3985. }
  3986. #endif
  3987. [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
  3988. public class BaseObject
  3989. {
  3990. [JsonProperty(PropertyName = "virtualMember")]
  3991. public virtual string VirtualMember { get; set; }
  3992. [JsonProperty(PropertyName = "nonVirtualMember")]
  3993. public string NonVirtualMember { get; set; }
  3994. }
  3995. public class ChildObject : BaseObject
  3996. {
  3997. public override string VirtualMember { get; set; }
  3998. public string NewMember { get; set; }
  3999. }
  4000. public class ChildWithDifferentOverrideObject : BaseObject
  4001. {
  4002. [JsonProperty(PropertyName = "differentVirtualMember")]
  4003. public override string VirtualMember { get; set; }
  4004. }
  4005. [Test]
  4006. public void ChildObjectTest()
  4007. {
  4008. ChildObject cc = new ChildObject
  4009. {
  4010. VirtualMember = "VirtualMember!",
  4011. NonVirtualMember = "NonVirtualMember!"
  4012. };
  4013. string result = JsonConvert.SerializeObject(cc);
  4014. Assert.AreEqual(@"{""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  4015. }
  4016. [Test]
  4017. public void ChildWithDifferentOverrideObjectTest()
  4018. {
  4019. ChildWithDifferentOverrideObject cc = new ChildWithDifferentOverrideObject
  4020. {
  4021. VirtualMember = "VirtualMember!",
  4022. NonVirtualMember = "NonVirtualMember!"
  4023. };
  4024. string result = JsonConvert.SerializeObject(cc);
  4025. Assert.AreEqual(@"{""differentVirtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  4026. }
  4027. [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
  4028. public interface IInterfaceObject
  4029. {
  4030. [JsonProperty(PropertyName = "virtualMember")]
  4031. [JsonConverter(typeof (IsoDateTimeConverter))]
  4032. DateTime InterfaceMember { get; set; }
  4033. }
  4034. public class ImplementInterfaceObject : IInterfaceObject
  4035. {
  4036. public DateTime InterfaceMember { get; set; }
  4037. public string NewMember { get; set; }
  4038. [JsonProperty(PropertyName = "newMemberWithProperty")]
  4039. public string NewMemberWithProperty { get; set; }
  4040. }
  4041. [Test]
  4042. public void ImplementInterfaceObjectTest()
  4043. {
  4044. ImplementInterfaceObject cc = new ImplementInterfaceObject
  4045. {
  4046. InterfaceMember = new DateTime(2010, 12, 31, 0, 0, 0, DateTimeKind.Utc),
  4047. NewMember = "NewMember!"
  4048. };
  4049. string result = JsonConvert.SerializeObject(cc, Formatting.Indented);
  4050. Assert.AreEqual(@"{
  4051. ""virtualMember"": ""2010-12-31T00:00:00Z"",
  4052. ""newMemberWithProperty"": null
  4053. }", result);
  4054. }
  4055. public class NonDefaultConstructorWithReadOnlyCollectionProperty
  4056. {
  4057. public string Title { get; set; }
  4058. public IList<string> Categories { get; private set; }
  4059. public NonDefaultConstructorWithReadOnlyCollectionProperty(string title)
  4060. {
  4061. Title = title;
  4062. Categories = new List<string>();
  4063. }
  4064. }
  4065. [Test]
  4066. public void NonDefaultConstructorWithReadOnlyCollectionPropertyTest()
  4067. {
  4068. NonDefaultConstructorWithReadOnlyCollectionProperty c1 = new NonDefaultConstructorWithReadOnlyCollectionProperty("blah");
  4069. c1.Categories.Add("one");
  4070. c1.Categories.Add("two");
  4071. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4072. Assert.AreEqual(@"{
  4073. ""Title"": ""blah"",
  4074. ""Categories"": [
  4075. ""one"",
  4076. ""two""
  4077. ]
  4078. }", json);
  4079. NonDefaultConstructorWithReadOnlyCollectionProperty c2 = JsonConvert.DeserializeObject<NonDefaultConstructorWithReadOnlyCollectionProperty>(json);
  4080. Assert.AreEqual(c1.Title, c2.Title);
  4081. Assert.AreEqual(c1.Categories.Count, c2.Categories.Count);
  4082. Assert.AreEqual("one", c2.Categories[0]);
  4083. Assert.AreEqual("two", c2.Categories[1]);
  4084. }
  4085. public class NonDefaultConstructorWithReadOnlyDictionaryProperty
  4086. {
  4087. public string Title { get; set; }
  4088. public IDictionary<string, int> Categories { get; private set; }
  4089. public NonDefaultConstructorWithReadOnlyDictionaryProperty(string title)
  4090. {
  4091. Title = title;
  4092. Categories = new Dictionary<string, int>();
  4093. }
  4094. }
  4095. [Test]
  4096. public void NonDefaultConstructorWithReadOnlyDictionaryPropertyTest()
  4097. {
  4098. NonDefaultConstructorWithReadOnlyDictionaryProperty c1 = new NonDefaultConstructorWithReadOnlyDictionaryProperty("blah");
  4099. c1.Categories.Add("one", 1);
  4100. c1.Categories.Add("two", 2);
  4101. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4102. Assert.AreEqual(@"{
  4103. ""Title"": ""blah"",
  4104. ""Categories"": {
  4105. ""one"": 1,
  4106. ""two"": 2
  4107. }
  4108. }", json);
  4109. NonDefaultConstructorWithReadOnlyDictionaryProperty c2 = JsonConvert.DeserializeObject<NonDefaultConstructorWithReadOnlyDictionaryProperty>(json);
  4110. Assert.AreEqual(c1.Title, c2.Title);
  4111. Assert.AreEqual(c1.Categories.Count, c2.Categories.Count);
  4112. Assert.AreEqual(1, c2.Categories["one"]);
  4113. Assert.AreEqual(2, c2.Categories["two"]);
  4114. }
  4115. [JsonObject(MemberSerialization.OptIn)]
  4116. public class ClassAttributeBase
  4117. {
  4118. [JsonProperty]
  4119. public string BaseClassValue { get; set; }
  4120. }
  4121. public class ClassAttributeDerived : ClassAttributeBase
  4122. {
  4123. [JsonProperty]
  4124. public string DerivedClassValue { get; set; }
  4125. public string NonSerialized { get; set; }
  4126. }
  4127. public class CollectionClassAttributeDerived : ClassAttributeBase, ICollection<object>
  4128. {
  4129. [JsonProperty]
  4130. public string CollectionDerivedClassValue { get; set; }
  4131. public void Add(object item)
  4132. {
  4133. throw new NotImplementedException();
  4134. }
  4135. public void Clear()
  4136. {
  4137. throw new NotImplementedException();
  4138. }
  4139. public bool Contains(object item)
  4140. {
  4141. throw new NotImplementedException();
  4142. }
  4143. public void CopyTo(object[] array, int arrayIndex)
  4144. {
  4145. throw new NotImplementedException();
  4146. }
  4147. public int Count
  4148. {
  4149. get { throw new NotImplementedException(); }
  4150. }
  4151. public bool IsReadOnly
  4152. {
  4153. get { throw new NotImplementedException(); }
  4154. }
  4155. public bool Remove(object item)
  4156. {
  4157. throw new NotImplementedException();
  4158. }
  4159. public IEnumerator<object> GetEnumerator()
  4160. {
  4161. throw new NotImplementedException();
  4162. }
  4163. IEnumerator IEnumerable.GetEnumerator()
  4164. {
  4165. throw new NotImplementedException();
  4166. }
  4167. }
  4168. [Test]
  4169. public void ClassAttributesInheritance()
  4170. {
  4171. string json = JsonConvert.SerializeObject(new ClassAttributeDerived
  4172. {
  4173. BaseClassValue = "BaseClassValue!",
  4174. DerivedClassValue = "DerivedClassValue!",
  4175. NonSerialized = "NonSerialized!"
  4176. }, Formatting.Indented);
  4177. Assert.AreEqual(@"{
  4178. ""DerivedClassValue"": ""DerivedClassValue!"",
  4179. ""BaseClassValue"": ""BaseClassValue!""
  4180. }", json);
  4181. json = JsonConvert.SerializeObject(new CollectionClassAttributeDerived
  4182. {
  4183. BaseClassValue = "BaseClassValue!",
  4184. CollectionDerivedClassValue = "CollectionDerivedClassValue!"
  4185. }, Formatting.Indented);
  4186. Assert.AreEqual(@"{
  4187. ""CollectionDerivedClassValue"": ""CollectionDerivedClassValue!"",
  4188. ""BaseClassValue"": ""BaseClassValue!""
  4189. }", json);
  4190. }
  4191. public class PrivateMembersClassWithAttributes
  4192. {
  4193. public PrivateMembersClassWithAttributes(string privateString, string internalString, string readonlyString)
  4194. {
  4195. _privateString = privateString;
  4196. _readonlyString = readonlyString;
  4197. _internalString = internalString;
  4198. }
  4199. public PrivateMembersClassWithAttributes()
  4200. {
  4201. _readonlyString = "default!";
  4202. }
  4203. [JsonProperty] private string _privateString;
  4204. [JsonProperty] private readonly string _readonlyString;
  4205. [JsonProperty] internal string _internalString;
  4206. public string UseValue()
  4207. {
  4208. return _readonlyString;
  4209. }
  4210. }
  4211. [Test]
  4212. public void PrivateMembersClassWithAttributesTest()
  4213. {
  4214. PrivateMembersClassWithAttributes c1 = new PrivateMembersClassWithAttributes("privateString!", "internalString!", "readonlyString!");
  4215. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4216. Assert.AreEqual(@"{
  4217. ""_privateString"": ""privateString!"",
  4218. ""_readonlyString"": ""readonlyString!"",
  4219. ""_internalString"": ""internalString!""
  4220. }", json);
  4221. PrivateMembersClassWithAttributes c2 = JsonConvert.DeserializeObject<PrivateMembersClassWithAttributes>(json);
  4222. Assert.AreEqual("readonlyString!", c2.UseValue());
  4223. }
  4224. public partial class BusRun
  4225. {
  4226. public IEnumerable<Nullable<DateTime>> Departures { get; set; }
  4227. public Boolean WheelchairAccessible { get; set; }
  4228. }
  4229. [Test]
  4230. public void DeserializeGenericEnumerableProperty()
  4231. {
  4232. BusRun r = JsonConvert.DeserializeObject<BusRun>("{\"Departures\":[\"\\/Date(1309874148734-0400)\\/\",\"\\/Date(1309874148739-0400)\\/\",null],\"WheelchairAccessible\":true}");
  4233. Assert.AreEqual(3, r.Departures.Count());
  4234. Assert.IsNotNull(r.Departures.ElementAt(0));
  4235. Assert.IsNotNull(r.Departures.ElementAt(1));
  4236. Assert.IsNull(r.Departures.ElementAt(2));
  4237. }
  4238. #if !(NET20)
  4239. [DataContract]
  4240. public class BaseType
  4241. {
  4242. [DataMember] public string zebra;
  4243. }
  4244. [DataContract]
  4245. public class DerivedType : BaseType
  4246. {
  4247. [DataMember(Order = 0)] public string bird;
  4248. [DataMember(Order = 1)] public string parrot;
  4249. [DataMember] public string dog;
  4250. [DataMember(Order = 3)] public string antelope;
  4251. [DataMember] public string cat;
  4252. [JsonProperty(Order = 1)] public string albatross;
  4253. [JsonProperty(Order = -2)] public string dinosaur;
  4254. }
  4255. [Test]
  4256. public void JsonPropertyDataMemberOrder()
  4257. {
  4258. DerivedType d = new DerivedType();
  4259. string json = JsonConvert.SerializeObject(d, Formatting.Indented);
  4260. Assert.AreEqual(@"{
  4261. ""dinosaur"": null,
  4262. ""dog"": null,
  4263. ""cat"": null,
  4264. ""zebra"": null,
  4265. ""bird"": null,
  4266. ""parrot"": null,
  4267. ""albatross"": null,
  4268. ""antelope"": null
  4269. }", json);
  4270. }
  4271. #endif
  4272. public class ClassWithException
  4273. {
  4274. public IList<Exception> Exceptions { get; set; }
  4275. public ClassWithException()
  4276. {
  4277. Exceptions = new List<Exception>();
  4278. }
  4279. }
  4280. #if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE)
  4281. [Test]
  4282. public void SerializeException1()
  4283. {
  4284. ClassWithException classWithException = new ClassWithException();
  4285. try
  4286. {
  4287. throw new Exception("Test Exception");
  4288. }
  4289. catch (Exception ex)
  4290. {
  4291. classWithException.Exceptions.Add(ex);
  4292. }
  4293. string sex = JsonConvert.SerializeObject(classWithException);
  4294. ClassWithException dex = JsonConvert.DeserializeObject<ClassWithException>(sex);
  4295. Assert.AreEqual(dex.Exceptions[0].ToString(), dex.Exceptions[0].ToString());
  4296. sex = JsonConvert.SerializeObject(classWithException, Formatting.Indented);
  4297. dex = JsonConvert.DeserializeObject<ClassWithException>(sex); // this fails!
  4298. Assert.AreEqual(dex.Exceptions[0].ToString(), dex.Exceptions[0].ToString());
  4299. }
  4300. #endif
  4301. public void DeserializeIDictionary()
  4302. {
  4303. IDictionary dictionary = JsonConvert.DeserializeObject<IDictionary>("{'name':'value!'}");
  4304. Assert.AreEqual(1, dictionary.Count);
  4305. Assert.AreEqual("value!", dictionary["name"]);
  4306. }
  4307. public void DeserializeIList()
  4308. {
  4309. IList list = JsonConvert.DeserializeObject<IList>("['1', 'two', 'III']");
  4310. Assert.AreEqual(3, list.Count);
  4311. }
  4312. public void UriGuidTimeSpanTestClassEmptyTest()
  4313. {
  4314. UriGuidTimeSpanTestClass c1 = new UriGuidTimeSpanTestClass();
  4315. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4316. Assert.AreEqual(@"{
  4317. ""Guid"": ""00000000-0000-0000-0000-000000000000"",
  4318. ""NullableGuid"": null,
  4319. ""TimeSpan"": ""00:00:00"",
  4320. ""NullableTimeSpan"": null,
  4321. ""Uri"": null
  4322. }", json);
  4323. UriGuidTimeSpanTestClass c2 = JsonConvert.DeserializeObject<UriGuidTimeSpanTestClass>(json);
  4324. Assert.AreEqual(c1.Guid, c2.Guid);
  4325. Assert.AreEqual(c1.NullableGuid, c2.NullableGuid);
  4326. Assert.AreEqual(c1.TimeSpan, c2.TimeSpan);
  4327. Assert.AreEqual(c1.NullableTimeSpan, c2.NullableTimeSpan);
  4328. Assert.AreEqual(c1.Uri, c2.Uri);
  4329. }
  4330. public void UriGuidTimeSpanTestClassValuesTest()
  4331. {
  4332. UriGuidTimeSpanTestClass c1 = new UriGuidTimeSpanTestClass
  4333. {
  4334. Guid = new Guid("1924129C-F7E0-40F3-9607-9939C531395A"),
  4335. NullableGuid = new Guid("9E9F3ADF-E017-4F72-91E0-617EBE85967D"),
  4336. TimeSpan = TimeSpan.FromDays(1),
  4337. NullableTimeSpan = TimeSpan.FromHours(1),
  4338. Uri = new Uri("http://testuri.com")
  4339. };
  4340. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4341. Assert.AreEqual(@"{
  4342. ""Guid"": ""1924129c-f7e0-40f3-9607-9939c531395a"",
  4343. ""NullableGuid"": ""9e9f3adf-e017-4f72-91e0-617ebe85967d"",
  4344. ""TimeSpan"": ""1.00:00:00"",
  4345. ""NullableTimeSpan"": ""01:00:00"",
  4346. ""Uri"": ""http://testuri.com/""
  4347. }", json);
  4348. UriGuidTimeSpanTestClass c2 = JsonConvert.DeserializeObject<UriGuidTimeSpanTestClass>(json);
  4349. Assert.AreEqual(c1.Guid, c2.Guid);
  4350. Assert.AreEqual(c1.NullableGuid, c2.NullableGuid);
  4351. Assert.AreEqual(c1.TimeSpan, c2.TimeSpan);
  4352. Assert.AreEqual(c1.NullableTimeSpan, c2.NullableTimeSpan);
  4353. Assert.AreEqual(c1.Uri, c2.Uri);
  4354. }
  4355. [Test]
  4356. public void NullableValueGenericDictionary()
  4357. {
  4358. IDictionary<string, int?> v1 = new Dictionary<string, int?>
  4359. {
  4360. {"First", 1},
  4361. {"Second", null},
  4362. {"Third", 3}
  4363. };
  4364. string json = JsonConvert.SerializeObject(v1, Formatting.Indented);
  4365. Assert.AreEqual(@"{
  4366. ""First"": 1,
  4367. ""Second"": null,
  4368. ""Third"": 3
  4369. }", json);
  4370. IDictionary<string, int?> v2 = JsonConvert.DeserializeObject<IDictionary<string, int?>>(json);
  4371. Assert.AreEqual(3, v2.Count);
  4372. Assert.AreEqual(1, v2["First"]);
  4373. Assert.AreEqual(null, v2["Second"]);
  4374. Assert.AreEqual(3, v2["Third"]);
  4375. }
  4376. [Test]
  4377. public void UsingJsonTextWriter()
  4378. {
  4379. // The property of the object has to be a number for the cast exception to occure
  4380. object o = new {p = 1};
  4381. var json = JObject.FromObject(o);
  4382. using (var sw = new StringWriter())
  4383. using (var jw = new JsonTextWriter(sw))
  4384. {
  4385. jw.WriteToken(json.CreateReader());
  4386. jw.Flush();
  4387. string result = sw.ToString();
  4388. Assert.AreEqual(@"{""p"":1}", result);
  4389. }
  4390. }
  4391. #if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE)
  4392. [Test]
  4393. public void DeserializeConcurrentDictionary()
  4394. {
  4395. IDictionary<string, Component> components = new Dictionary<string, Component>
  4396. {
  4397. {"Key!", new Component()}
  4398. };
  4399. GameObject go = new GameObject
  4400. {
  4401. Components = new ConcurrentDictionary<string, Component>(components),
  4402. Id = "Id!",
  4403. Name = "Name!"
  4404. };
  4405. string originalJson = JsonConvert.SerializeObject(go, Formatting.Indented);
  4406. Assert.AreEqual(@"{
  4407. ""Components"": {
  4408. ""Key!"": {}
  4409. },
  4410. ""Id"": ""Id!"",
  4411. ""Name"": ""Name!""
  4412. }", originalJson);
  4413. GameObject newObject = JsonConvert.DeserializeObject<GameObject>(originalJson);
  4414. Assert.AreEqual(1, newObject.Components.Count);
  4415. Assert.AreEqual("Id!", newObject.Id);
  4416. Assert.AreEqual("Name!", newObject.Name);
  4417. }
  4418. #endif
  4419. [Test]
  4420. public void DeserializeKeyValuePairArray()
  4421. {
  4422. string json = @"[ { ""Value"": [ ""1"", ""2"" ], ""Key"": ""aaa"", ""BadContent"": [ 0 ] }, { ""Value"": [ ""3"", ""4"" ], ""Key"": ""bbb"" } ]";
  4423. IList<KeyValuePair<string, IList<string>>> values = JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json);
  4424. Assert.AreEqual(2, values.Count);
  4425. Assert.AreEqual("aaa", values[0].Key);
  4426. Assert.AreEqual(2, values[0].Value.Count);
  4427. Assert.AreEqual("1", values[0].Value[0]);
  4428. Assert.AreEqual("2", values[0].Value[1]);
  4429. Assert.AreEqual("bbb", values[1].Key);
  4430. Assert.AreEqual(2, values[1].Value.Count);
  4431. Assert.AreEqual("3", values[1].Value[0]);
  4432. Assert.AreEqual("4", values[1].Value[1]);
  4433. }
  4434. [Test]
  4435. public void DeserializeNullableKeyValuePairArray()
  4436. {
  4437. string json = @"[ { ""Value"": [ ""1"", ""2"" ], ""Key"": ""aaa"", ""BadContent"": [ 0 ] }, null, { ""Value"": [ ""3"", ""4"" ], ""Key"": ""bbb"" } ]";
  4438. IList<KeyValuePair<string, IList<string>>?> values = JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>?>>(json);
  4439. Assert.AreEqual(3, values.Count);
  4440. Assert.AreEqual("aaa", values[0].Value.Key);
  4441. Assert.AreEqual(2, values[0].Value.Value.Count);
  4442. Assert.AreEqual("1", values[0].Value.Value[0]);
  4443. Assert.AreEqual("2", values[0].Value.Value[1]);
  4444. Assert.AreEqual(null, values[1]);
  4445. Assert.AreEqual("bbb", values[2].Value.Key);
  4446. Assert.AreEqual(2, values[2].Value.Value.Count);
  4447. Assert.AreEqual("3", values[2].Value.Value[0]);
  4448. Assert.AreEqual("4", values[2].Value.Value[1]);
  4449. }
  4450. [Test]
  4451. [ExpectedException(typeof (Exception)
  4452. #if !NETFX_CORE
  4453. , ExpectedMessage = "Could not deserialize Null to KeyValuePair."
  4454. #endif
  4455. )]
  4456. public void DeserializeNullToNonNullableKeyValuePairArray()
  4457. {
  4458. string json = @"[ null ]";
  4459. JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json);
  4460. }
  4461. [Test]
  4462. public void SerializeUriWithQuotes()
  4463. {
  4464. string input = "http://test.com/%22foo+bar%22";
  4465. Uri uri = new Uri(input);
  4466. string json = JsonConvert.SerializeObject(uri);
  4467. Uri output = JsonConvert.DeserializeObject<Uri>(json);
  4468. Assert.AreEqual(uri, output);
  4469. }
  4470. [Test]
  4471. public void SerializeUriWithSlashes()
  4472. {
  4473. string input = @"http://tes/?a=b\\c&d=e\";
  4474. Uri uri = new Uri(input);
  4475. string json = JsonConvert.SerializeObject(uri);
  4476. Uri output = JsonConvert.DeserializeObject<Uri>(json);
  4477. Assert.AreEqual(uri, output);
  4478. }
  4479. [Test]
  4480. public void DeserializeByteArrayWithTypeNameHandling()
  4481. {
  4482. TestObject test = new TestObject("Test", new byte[] {72, 63, 62, 71, 92, 55});
  4483. JsonSerializer serializer = new JsonSerializer();
  4484. serializer.TypeNameHandling = TypeNameHandling.All;
  4485. byte[] objectBytes;
  4486. using (MemoryStream bsonStream = new MemoryStream())
  4487. using (JsonWriter bsonWriter = new JsonTextWriter(new StreamWriter(bsonStream)))
  4488. {
  4489. serializer.Serialize(bsonWriter, test);
  4490. bsonWriter.Flush();
  4491. objectBytes = bsonStream.ToArray();
  4492. }
  4493. using (MemoryStream bsonStream = new MemoryStream(objectBytes))
  4494. using (JsonReader bsonReader = new JsonTextReader(new StreamReader(bsonStream)))
  4495. {
  4496. // Get exception here
  4497. TestObject newObject = (TestObject) serializer.Deserialize(bsonReader);
  4498. Assert.AreEqual("Test", newObject.Name);
  4499. CollectionAssert.AreEquivalent(new byte[] {72, 63, 62, 71, 92, 55}, newObject.Data);
  4500. }
  4501. }
  4502. #if !(SILVERLIGHT || WINDOWS_PHONE || NET20 || NETFX_CORE)
  4503. [Test]
  4504. public void DeserializeDecimalsWithCulture()
  4505. {
  4506. CultureInfo initialCulture = Thread.CurrentThread.CurrentCulture;
  4507. try
  4508. {
  4509. CultureInfo testCulture = CultureInfo.CreateSpecificCulture("nb-NO");
  4510. Thread.CurrentThread.CurrentCulture = testCulture;
  4511. Thread.CurrentThread.CurrentUICulture = testCulture;
  4512. string json = @"{ 'Quantity': '1.5', 'OptionalQuantity': '2.2' }";
  4513. DecimalTestClass c = JsonConvert.DeserializeObject<DecimalTestClass>(json);
  4514. Assert.AreEqual(1.5m, c.Quantity);
  4515. Assert.AreEqual(2.2d, c.OptionalQuantity);
  4516. }
  4517. finally
  4518. {
  4519. Thread.CurrentThread.CurrentCulture = initialCulture;
  4520. Thread.CurrentThread.CurrentUICulture = initialCulture;
  4521. }
  4522. }
  4523. #endif
  4524. [Test]
  4525. public void ReadForTypeHackFixDecimal()
  4526. {
  4527. IList<decimal> d1 = new List<decimal> {1.1m};
  4528. string json = JsonConvert.SerializeObject(d1);
  4529. IList<decimal> d2 = JsonConvert.DeserializeObject<IList<decimal>>(json);
  4530. Assert.AreEqual(d1.Count, d2.Count);
  4531. Assert.AreEqual(d1[0], d2[0]);
  4532. }
  4533. [Test]
  4534. public void ReadForTypeHackFixDateTimeOffset()
  4535. {
  4536. IList<DateTimeOffset?> d1 = new List<DateTimeOffset?> {null};
  4537. string json = JsonConvert.SerializeObject(d1);
  4538. IList<DateTimeOffset?> d2 = JsonConvert.DeserializeObject<IList<DateTimeOffset?>>(json);
  4539. Assert.AreEqual(d1.Count, d2.Count);
  4540. Assert.AreEqual(d1[0], d2[0]);
  4541. }
  4542. [Test]
  4543. public void ReadForTypeHackFixByteArray()
  4544. {
  4545. IList<byte[]> d1 = new List<byte[]> {null};
  4546. string json = JsonConvert.SerializeObject(d1);
  4547. IList<byte[]> d2 = JsonConvert.DeserializeObject<IList<byte[]>>(json);
  4548. Assert.AreEqual(d1.Count, d2.Count);
  4549. Assert.AreEqual(d1[0], d2[0]);
  4550. }
  4551. [Test]
  4552. public void SerializeInheritanceHierarchyWithDuplicateProperty()
  4553. {
  4554. Bb b = new Bb();
  4555. b.no = true;
  4556. Aa a = b;
  4557. a.no = int.MaxValue;
  4558. string json = JsonConvert.SerializeObject(b);
  4559. Assert.AreEqual(@"{""no"":true}", json);
  4560. Bb b2 = JsonConvert.DeserializeObject<Bb>(json);
  4561. Assert.AreEqual(true, b2.no);
  4562. }
  4563. [Test]
  4564. [ExpectedException(typeof (JsonSerializationException)
  4565. #if !NETFX_CORE
  4566. , ExpectedMessage = "Error converting value {null} to type 'System.Int32'. Line 5, position 7."
  4567. #endif
  4568. )]
  4569. public void DeserializeNullInt()
  4570. {
  4571. string json = @"[
  4572. 1,
  4573. 2,
  4574. 3,
  4575. null
  4576. ]";
  4577. List<int> numbers = JsonConvert.DeserializeObject<List<int>>(json);
  4578. // JsonSerializationException : Error converting value {null} to type 'System.Int32'. Line 5, position 7.
  4579. }
  4580. [Test]
  4581. public void SerializeNullableWidgetStruct()
  4582. {
  4583. Widget widget = new Widget {Id = new WidgetId {Value = "id"}};
  4584. string json = JsonConvert.SerializeObject(widget);
  4585. Assert.AreEqual(@"{""Id"":{""Value"":""id""}}", json);
  4586. }
  4587. [Test]
  4588. public void DeserializeNullableWidgetStruct()
  4589. {
  4590. string json = @"{""Id"":{""Value"":""id""}}";
  4591. Widget w = JsonConvert.DeserializeObject<Widget>(json);
  4592. Assert.AreEqual(new WidgetId {Value = "id"}, w.Id);
  4593. Assert.AreEqual(new WidgetId {Value = "id"}, w.Id.Value);
  4594. Assert.AreEqual("id", w.Id.Value.Value);
  4595. }
  4596. [Test]
  4597. public void DeserializeBoolInt()
  4598. {
  4599. ExceptionAssert.Throws<JsonReaderException>("Error reading integer. Unexpected token: Boolean. Line 2, position 22.",
  4600. () =>
  4601. {
  4602. string json = @"{
  4603. ""PreProperty"": true,
  4604. ""PostProperty"": ""-1""
  4605. }";
  4606. JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
  4607. });
  4608. }
  4609. [Test]
  4610. public void DeserializeUnexpectedEndInt()
  4611. {
  4612. ExceptionAssert.Throws<JsonSerializationException>("Unexpected end when setting PreProperty's value. Line 2, position 18.",
  4613. () =>
  4614. {
  4615. string json = @"{
  4616. ""PreProperty"": ";
  4617. JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
  4618. });
  4619. }
  4620. [Test]
  4621. public void DeserializeNullableGuid()
  4622. {
  4623. string json = @"{""Id"":null}";
  4624. var c = JsonConvert.DeserializeObject<NullableGuid>(json);
  4625. Assert.AreEqual(null, c.Id);
  4626. json = @"{""Id"":""d8220a4b-75b1-4b7a-8112-b7bdae956a45""}";
  4627. c = JsonConvert.DeserializeObject<NullableGuid>(json);
  4628. Assert.AreEqual(new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"), c.Id);
  4629. }
  4630. [Test]
  4631. public void DeserializeGuid()
  4632. {
  4633. Item expected = new Item()
  4634. {
  4635. SourceTypeID = new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"),
  4636. BrokerID = new Guid("951663c4-924e-4c86-a57a-7ed737501dbd"),
  4637. Latitude = 33.657145,
  4638. Longitude = -117.766684,
  4639. TimeStamp = new DateTime(2000, 3, 1, 23, 59, 59, DateTimeKind.Utc),
  4640. Payload = new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  4641. };
  4642. string jsonString = JsonConvert.SerializeObject(expected, Formatting.Indented);
  4643. Assert.AreEqual(@"{
  4644. ""SourceTypeID"": ""d8220a4b-75b1-4b7a-8112-b7bdae956a45"",
  4645. ""BrokerID"": ""951663c4-924e-4c86-a57a-7ed737501dbd"",
  4646. ""Latitude"": 33.657145,
  4647. ""Longitude"": -117.766684,
  4648. ""TimeStamp"": ""2000-03-01T23:59:59Z"",
  4649. ""Payload"": {
  4650. ""$type"": ""System.Byte[], mscorlib"",
  4651. ""$value"": ""AAECAwQFBgcICQ==""
  4652. }
  4653. }", jsonString);
  4654. Item actual = JsonConvert.DeserializeObject<Item>(jsonString);
  4655. Assert.AreEqual(new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"), actual.SourceTypeID);
  4656. Assert.AreEqual(new Guid("951663c4-924e-4c86-a57a-7ed737501dbd"), actual.BrokerID);
  4657. byte[] bytes = (byte[])actual.Payload;
  4658. CollectionAssert.AreEquivalent((new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }).ToList(), bytes.ToList());
  4659. }
  4660. [Test]
  4661. public void DeserializeObjectDictionary()
  4662. {
  4663. var serializer = JsonSerializer.Create(new JsonSerializerSettings());
  4664. var dict = serializer.Deserialize<Dictionary<string, string>>(new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}")));
  4665. Assert.AreEqual("", dict["k1"]);
  4666. Assert.AreEqual("v2", dict["k2"]);
  4667. }
  4668. [Test]
  4669. public void DeserializeNullableEnum()
  4670. {
  4671. string json = JsonConvert.SerializeObject(new WithEnums
  4672. {
  4673. Id = 7,
  4674. NullableEnum = null
  4675. });
  4676. Assert.AreEqual(@"{""Id"":7,""NullableEnum"":null}", json);
  4677. WithEnums e = JsonConvert.DeserializeObject<WithEnums>(json);
  4678. Assert.AreEqual(null, e.NullableEnum);
  4679. json = JsonConvert.SerializeObject(new WithEnums
  4680. {
  4681. Id = 7,
  4682. NullableEnum = MyEnum.Value2
  4683. });
  4684. Assert.AreEqual(@"{""Id"":7,""NullableEnum"":1}", json);
  4685. e = JsonConvert.DeserializeObject<WithEnums>(json);
  4686. Assert.AreEqual(MyEnum.Value2, e.NullableEnum);
  4687. }
  4688. [Test]
  4689. public void NullableStructWithConverter()
  4690. {
  4691. string json = JsonConvert.SerializeObject(new Widget1 {Id = new WidgetId1 {Value = 1234}});
  4692. Assert.AreEqual(@"{""Id"":""1234""}", json);
  4693. Widget1 w = JsonConvert.DeserializeObject<Widget1>(@"{""Id"":""1234""}");
  4694. Assert.AreEqual(new WidgetId1 {Value = 1234}, w.Id);
  4695. }
  4696. [Test]
  4697. public void SerializeDictionaryStringStringAndStringObject()
  4698. {
  4699. var serializer = JsonSerializer.Create(new JsonSerializerSettings());
  4700. var dict = serializer.Deserialize<Dictionary<string, string>>(new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}")));
  4701. var reader = new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}"));
  4702. var dict2 = serializer.Deserialize<Dictionary<string, object>>(reader);
  4703. Assert.AreEqual(dict["k1"], dict2["k1"]);
  4704. }
  4705. [Test]
  4706. public void DeserializeEmptyStrings()
  4707. {
  4708. object v = JsonConvert.DeserializeObject<double?>("");
  4709. Assert.IsNull(v);
  4710. v = JsonConvert.DeserializeObject<char?>("");
  4711. Assert.IsNull(v);
  4712. v = JsonConvert.DeserializeObject<int?>("");
  4713. Assert.IsNull(v);
  4714. v = JsonConvert.DeserializeObject<decimal?>("");
  4715. Assert.IsNull(v);
  4716. v = JsonConvert.DeserializeObject<DateTime?>("");
  4717. Assert.IsNull(v);
  4718. v = JsonConvert.DeserializeObject<DateTimeOffset?>("");
  4719. Assert.IsNull(v);
  4720. v = JsonConvert.DeserializeObject<byte[]>("");
  4721. Assert.IsNull(v);
  4722. }
  4723. public class Sdfsdf
  4724. {
  4725. public double Id { get; set; }
  4726. }
  4727. [Test]
  4728. [ExpectedException(typeof (JsonSerializationException)
  4729. #if !NETFX_CORE
  4730. , ExpectedMessage = "No JSON content found and type 'System.Double' is not nullable. Line 0, position 0."
  4731. #endif
  4732. )]
  4733. public void DeserializeDoubleFromEmptyString()
  4734. {
  4735. JsonConvert.DeserializeObject<double>("");
  4736. }
  4737. [Test]
  4738. [ExpectedException(typeof (JsonSerializationException)
  4739. #if !NETFX_CORE
  4740. , ExpectedMessage = "No JSON content found and type 'System.StringComparison' is not nullable. Line 0, position 0."
  4741. #endif
  4742. )]
  4743. public void DeserializeEnumFromEmptyString()
  4744. {
  4745. JsonConvert.DeserializeObject<StringComparison>("");
  4746. }
  4747. [Test]
  4748. [ExpectedException(typeof (JsonSerializationException)
  4749. #if !NETFX_CORE
  4750. , ExpectedMessage = "No JSON content found and type 'System.Int32' is not nullable. Line 0, position 0."
  4751. #endif
  4752. )]
  4753. public void DeserializeInt32FromEmptyString()
  4754. {
  4755. JsonConvert.DeserializeObject<int>("");
  4756. }
  4757. [Test]
  4758. public void DeserializeByteArrayFromEmptyString()
  4759. {
  4760. byte[] b = JsonConvert.DeserializeObject<byte[]>("");
  4761. Assert.IsNull(b);
  4762. }
  4763. [Test]
  4764. [ExpectedException(typeof (ArgumentNullException)
  4765. #if !NETFX_CORE
  4766. , ExpectedMessage = @"Value cannot be null.
  4767. Parameter name: value"
  4768. #endif
  4769. )]
  4770. public void DeserializeDoubleFromNullString()
  4771. {
  4772. JsonConvert.DeserializeObject<double>(null);
  4773. }
  4774. [Test]
  4775. [ExpectedException(typeof (ArgumentNullException)
  4776. #if !NETFX_CORE
  4777. , ExpectedMessage = @"Value cannot be null.
  4778. Parameter name: value"
  4779. #endif
  4780. )]
  4781. public void DeserializeFromNullString()
  4782. {
  4783. JsonConvert.DeserializeObject(null);
  4784. }
  4785. [Test]
  4786. public void DeserializeIsoDatesWithIsoConverter()
  4787. {
  4788. string jsonIsoText =
  4789. @"{""Value"":""2012-02-25T19:55:50.6095676+13:00""}";
  4790. DateTimeWrapper c = JsonConvert.DeserializeObject<DateTimeWrapper>(jsonIsoText, new IsoDateTimeConverter());
  4791. Assert.AreEqual(DateTimeKind.Local, c.Value.Kind);
  4792. }
  4793. #if !NET20
  4794. [Test]
  4795. public void DeserializeUTC()
  4796. {
  4797. DateTimeTestClass c =
  4798. JsonConvert.DeserializeObject<DateTimeTestClass>(
  4799. @"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12Z"",""PostField"":""Post""}",
  4800. new JsonSerializerSettings
  4801. {
  4802. DateTimeZoneHandling = DateTimeZoneHandling.Local
  4803. });
  4804. Assert.AreEqual(new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime(), c.DateTimeField);
  4805. Assert.AreEqual(new DateTimeOffset(2008, 12, 12, 12, 12, 12, 0, TimeSpan.Zero), c.DateTimeOffsetField);
  4806. Assert.AreEqual("Pre", c.PreField);
  4807. Assert.AreEqual("Post", c.PostField);
  4808. DateTimeTestClass c2 =
  4809. JsonConvert.DeserializeObject<DateTimeTestClass>(
  4810. @"{""PreField"":""Pre"",""DateTimeField"":""2008-01-01T01:01:01Z"",""DateTimeOffsetField"":""2008-01-01T01:01:01Z"",""PostField"":""Post""}",
  4811. new JsonSerializerSettings
  4812. {
  4813. DateTimeZoneHandling = DateTimeZoneHandling.Local
  4814. });
  4815. Assert.AreEqual(new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc).ToLocalTime(), c2.DateTimeField);
  4816. Assert.AreEqual(new DateTimeOffset(2008, 1, 1, 1, 1, 1, 0, TimeSpan.Zero), c2.DateTimeOffsetField);
  4817. Assert.AreEqual("Pre", c2.PreField);
  4818. Assert.AreEqual("Post", c2.PostField);
  4819. }
  4820. [Test]
  4821. public void NullableDeserializeUTC()
  4822. {
  4823. NullableDateTimeTestClass c =
  4824. JsonConvert.DeserializeObject<NullableDateTimeTestClass>(
  4825. @"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12Z"",""PostField"":""Post""}",
  4826. new JsonSerializerSettings
  4827. {
  4828. DateTimeZoneHandling = DateTimeZoneHandling.Local
  4829. });
  4830. Assert.AreEqual(new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime(), c.DateTimeField);
  4831. Assert.AreEqual(new DateTimeOffset(2008, 12, 12, 12, 12, 12, 0, TimeSpan.Zero), c.DateTimeOffsetField);
  4832. Assert.AreEqual("Pre", c.PreField);
  4833. Assert.AreEqual("Post", c.PostField);
  4834. NullableDateTimeTestClass c2 =
  4835. JsonConvert.DeserializeObject<NullableDateTimeTestClass>(
  4836. @"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}");
  4837. Assert.AreEqual(null, c2.DateTimeField);
  4838. Assert.AreEqual(null, c2.DateTimeOffsetField);
  4839. Assert.AreEqual("Pre", c2.PreField);
  4840. Assert.AreEqual("Post", c2.PostField);
  4841. }
  4842. [Test]
  4843. public void PrivateConstructor()
  4844. {
  4845. var person = PersonWithPrivateConstructor.CreatePerson();
  4846. person.Name = "John Doe";
  4847. person.Age = 25;
  4848. var serializedPerson = JsonConvert.SerializeObject(person);
  4849. var roundtrippedPerson = JsonConvert.DeserializeObject<PersonWithPrivateConstructor>(serializedPerson);
  4850. Assert.AreEqual(person.Name, roundtrippedPerson.Name);
  4851. }
  4852. #endif
  4853. #if !(SILVERLIGHT || NETFX_CORE)
  4854. [Test]
  4855. public void MetroBlogPost()
  4856. {
  4857. Product product = new Product();
  4858. product.Name = "Apple";
  4859. product.ExpiryDate = new DateTime(2012, 4, 1);
  4860. product.Price = 3.99M;
  4861. product.Sizes = new []{"Small", "Medium", "Large"};
  4862. string json = JsonConvert.SerializeObject(product);
  4863. //{
  4864. // "Name": "Apple",
  4865. // "ExpiryDate": "2012-04-01T00:00:00",
  4866. // "Price": 3.99,
  4867. // "Sizes": [ "Small", "Medium", "Large" ]
  4868. //}
  4869. string metroJson = JsonConvert.SerializeObject(product, new JsonSerializerSettings
  4870. {
  4871. ContractResolver = new MetroPropertyNameResolver(),
  4872. Converters = { new MetroStringConverter() },
  4873. Formatting = Formatting.Indented
  4874. });
  4875. Assert.AreEqual(metroJson, @"{
  4876. "":::NAME:::"": "":::APPLE:::"",
  4877. "":::EXPIRYDATE:::"": ""2012-04-01T00:00:00"",
  4878. "":::PRICE:::"": 3.99,
  4879. "":::SIZES:::"": [
  4880. "":::SMALL:::"",
  4881. "":::MEDIUM:::"",
  4882. "":::LARGE:::""
  4883. ]
  4884. }");
  4885. //{
  4886. // ":::NAME:::": ":::APPLE:::",
  4887. // ":::EXPIRYDATE:::": "2012-04-01T00:00:00",
  4888. // ":::PRICE:::": 3.99,
  4889. // ":::SIZES:::": [ ":::SMALL:::", ":::MEDIUM:::", ":::LARGE:::" ]
  4890. //}
  4891. Color[] colors = new []{ Color.Blue, Color.Red, Color.Yellow, Color.Green, Color.Black, Color.Brown };
  4892. string json1 = JsonConvert.SerializeObject(colors);
  4893. //[":::GRAY:::", ":::GRAY:::", ":::GRAY:::", ":::GRAY:::", ":::BLACK:::", ":::GRAY:::"]
  4894. Assert.AreEqual(json1, @"[""Blue"",""Red"",""Yellow"",""Green"",""Black"",""Brown""]");
  4895. string json2 = JsonConvert.SerializeObject(colors, new JsonSerializerSettings
  4896. {
  4897. ContractResolver = new MetroPropertyNameResolver(),
  4898. Converters = { new MetroStringConverter(), new MetroColorConverter() },
  4899. Formatting = Formatting.Indented
  4900. });
  4901. Assert.AreEqual(json2, @"[
  4902. "":::GRAY:::"",
  4903. "":::GRAY:::"",
  4904. "":::GRAY:::"",
  4905. "":::GRAY:::"",
  4906. "":::BLACK:::"",
  4907. "":::GRAY:::""
  4908. ]");
  4909. }
  4910. public class MetroStringConverter : JsonConverter
  4911. {
  4912. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  4913. {
  4914. writer.WriteValue(":::" + value.ToString().ToUpper(CultureInfo.InvariantCulture) + ":::");
  4915. }
  4916. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  4917. {
  4918. return existingValue;
  4919. }
  4920. public override bool CanConvert(Type objectType)
  4921. {
  4922. return objectType == typeof (string);
  4923. }
  4924. }
  4925. public class MetroPropertyNameResolver : DefaultContractResolver
  4926. {
  4927. protected internal override string ResolvePropertyName(string propertyName)
  4928. {
  4929. return ":::" + propertyName.ToUpper(CultureInfo.InvariantCulture) + ":::";
  4930. }
  4931. }
  4932. public class MetroColorConverter : JsonConverter
  4933. {
  4934. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  4935. {
  4936. Color color = (Color) value;
  4937. Color fixedColor = (color == Color.White || color == Color.Black) ? color : Color.Gray;
  4938. writer.WriteValue(":::" + fixedColor.ToKnownColor().ToString().ToUpper() + ":::");
  4939. }
  4940. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  4941. {
  4942. return Enum.Parse(typeof (Color), reader.Value.ToString());
  4943. }
  4944. public override bool CanConvert(Type objectType)
  4945. {
  4946. return objectType == typeof (Color);
  4947. }
  4948. }
  4949. #endif
  4950. }
  4951. public class PersonWithPrivateConstructor
  4952. {
  4953. private PersonWithPrivateConstructor()
  4954. { }
  4955. public static PersonWithPrivateConstructor CreatePerson()
  4956. {
  4957. return new PersonWithPrivateConstructor();
  4958. }
  4959. public string Name { get; set; }
  4960. public int Age { get; set; }
  4961. }
  4962. public class DateTimeWrapper
  4963. {
  4964. public DateTime Value { get; set; }
  4965. }
  4966. public class Widget1
  4967. {
  4968. public WidgetId1? Id { get; set; }
  4969. }
  4970. [JsonConverter(typeof(WidgetIdJsonConverter))]
  4971. public struct WidgetId1
  4972. {
  4973. public long Value { get; set; }
  4974. }
  4975. public class WidgetIdJsonConverter : JsonConverter
  4976. {
  4977. public override bool CanConvert(Type objectType)
  4978. {
  4979. return objectType == typeof(WidgetId1) || objectType == typeof(WidgetId1?);
  4980. }
  4981. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  4982. {
  4983. WidgetId1 id = (WidgetId1)value;
  4984. writer.WriteValue(id.Value.ToString());
  4985. }
  4986. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  4987. {
  4988. if (reader.TokenType == JsonToken.Null)
  4989. return null;
  4990. return new WidgetId1 { Value = int.Parse(reader.Value.ToString()) };
  4991. }
  4992. }
  4993. public enum MyEnum
  4994. {
  4995. Value1,
  4996. Value2,
  4997. Value3
  4998. }
  4999. public class WithEnums
  5000. {
  5001. public int Id { get; set; }
  5002. public MyEnum? NullableEnum { get; set; }
  5003. }
  5004. public class Item
  5005. {
  5006. public Guid SourceTypeID { get; set; }
  5007. public Guid BrokerID { get; set; }
  5008. public double Latitude { get; set; }
  5009. public double Longitude { get; set; }
  5010. public DateTime TimeStamp { get; set; }
  5011. [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
  5012. public object Payload { get; set; }
  5013. }
  5014. public class NullableGuid
  5015. {
  5016. public Guid? Id { get; set; }
  5017. }
  5018. public class Widget
  5019. {
  5020. public WidgetId? Id { get; set; }
  5021. }
  5022. public struct WidgetId
  5023. {
  5024. public string Value { get; set; }
  5025. }
  5026. public class DecimalTestClass
  5027. {
  5028. public decimal Quantity { get; set; }
  5029. public double OptionalQuantity { get; set; }
  5030. }
  5031. public class TestObject
  5032. {
  5033. public TestObject()
  5034. {
  5035. }
  5036. public TestObject(string name, byte[] data)
  5037. {
  5038. Name = name;
  5039. Data = data;
  5040. }
  5041. public string Name { get; set; }
  5042. public byte[] Data { get; set; }
  5043. }
  5044. public class UriGuidTimeSpanTestClass
  5045. {
  5046. public Guid Guid { get; set; }
  5047. public Guid? NullableGuid { get; set; }
  5048. public TimeSpan TimeSpan { get; set; }
  5049. public TimeSpan? NullableTimeSpan { get; set; }
  5050. public Uri Uri { get; set; }
  5051. }
  5052. internal class Aa
  5053. {
  5054. public int no;
  5055. }
  5056. internal class Bb : Aa
  5057. {
  5058. public bool no;
  5059. }
  5060. #if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE)
  5061. [JsonObject(MemberSerialization.OptIn)]
  5062. public class GameObject
  5063. {
  5064. [JsonProperty]
  5065. public string Id { get; set; }
  5066. [JsonProperty]
  5067. public string Name { get; set; }
  5068. [JsonProperty] public ConcurrentDictionary<string, Component> Components;
  5069. public GameObject()
  5070. {
  5071. Components = new ConcurrentDictionary<string, Component>();
  5072. }
  5073. }
  5074. [JsonObject(MemberSerialization.OptIn)]
  5075. public class Component
  5076. {
  5077. [JsonIgnore] // Ignore circular reference
  5078. public GameObject GameObject { get; set; }
  5079. public Component()
  5080. {
  5081. }
  5082. }
  5083. [JsonObject(MemberSerialization.OptIn)]
  5084. public class TestComponent : Component
  5085. {
  5086. [JsonProperty]
  5087. public int MyProperty { get; set; }
  5088. public TestComponent()
  5089. {
  5090. }
  5091. }
  5092. #endif
  5093. }