PageRenderTime 95ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://github.com/advancedrei/Newtonsoft.Json
C# | 7906 lines | 7136 code | 636 blank | 134 comment | 68 complexity | 85ec14f216654ad3a49e7b98baf6f63d MD5 | raw file
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 && !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.TestPlatform.UnitTestFramework;
  43. using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
  44. using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.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 !NET20 && !WINDOWS_PHONE
  56. using System.Runtime.Serialization.Json;
  57. #endif
  58. using Newtonsoft.Json.Serialization;
  59. using Newtonsoft.Json.Tests.Linq;
  60. using Newtonsoft.Json.Tests.TestObjects;
  61. using System.Runtime.Serialization;
  62. using System.Globalization;
  63. using Newtonsoft.Json.Utilities;
  64. using System.Reflection;
  65. #if !NET20 && !SILVERLIGHT
  66. using System.Xml.Linq;
  67. using System.Text.RegularExpressions;
  68. using System.Collections.Specialized;
  69. using System.Linq.Expressions;
  70. #endif
  71. #if !(NET35 || NET20 || WINDOWS_PHONE)
  72. using System.Dynamic;
  73. using System.ComponentModel;
  74. #endif
  75. #if NET20
  76. using Newtonsoft.Json.Utilities.LinqBridge;
  77. #else
  78. using System.Linq;
  79. #endif
  80. #if !(SILVERLIGHT || NETFX_CORE)
  81. using System.Drawing;
  82. #endif
  83. namespace Newtonsoft.Json.Tests.Serialization
  84. {
  85. [TestFixture]
  86. public class JsonSerializerTest : TestFixtureBase
  87. {
  88. [Test]
  89. public void PersonTypedObjectDeserialization()
  90. {
  91. Store store = new Store();
  92. string jsonText = JsonConvert.SerializeObject(store);
  93. Store deserializedStore = (Store)JsonConvert.DeserializeObject(jsonText, typeof(Store));
  94. Assert.AreEqual(store.Establised, deserializedStore.Establised);
  95. Assert.AreEqual(store.product.Count, deserializedStore.product.Count);
  96. Console.WriteLine(jsonText);
  97. }
  98. [Test]
  99. public void TypedObjectDeserialization()
  100. {
  101. Product product = new Product();
  102. product.Name = "Apple";
  103. product.ExpiryDate = new DateTime(2008, 12, 28);
  104. product.Price = 3.99M;
  105. product.Sizes = new string[] { "Small", "Medium", "Large" };
  106. string output = JsonConvert.SerializeObject(product);
  107. //{
  108. // "Name": "Apple",
  109. // "ExpiryDate": "\/Date(1230375600000+1300)\/",
  110. // "Price": 3.99,
  111. // "Sizes": [
  112. // "Small",
  113. // "Medium",
  114. // "Large"
  115. // ]
  116. //}
  117. Product deserializedProduct = (Product)JsonConvert.DeserializeObject(output, typeof(Product));
  118. Assert.AreEqual("Apple", deserializedProduct.Name);
  119. Assert.AreEqual(new DateTime(2008, 12, 28), deserializedProduct.ExpiryDate);
  120. Assert.AreEqual(3.99m, deserializedProduct.Price);
  121. Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
  122. Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
  123. Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
  124. }
  125. //[Test]
  126. //public void Advanced()
  127. //{
  128. // Product product = new Product();
  129. // product.ExpiryDate = new DateTime(2008, 12, 28);
  130. // JsonSerializer serializer = new JsonSerializer();
  131. // serializer.Converters.Add(new JavaScriptDateTimeConverter());
  132. // serializer.NullValueHandling = NullValueHandling.Ignore;
  133. // using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
  134. // using (JsonWriter writer = new JsonTextWriter(sw))
  135. // {
  136. // serializer.Serialize(writer, product);
  137. // // {"ExpiryDate":new Date(1230375600000),"Price":0}
  138. // }
  139. //}
  140. [Test]
  141. public void JsonConvertSerializer()
  142. {
  143. string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
  144. Product p = JsonConvert.DeserializeObject(value, typeof(Product)) as Product;
  145. Assert.AreEqual("Orange", p.Name);
  146. Assert.AreEqual(new DateTime(2010, 1, 24, 12, 0, 0), p.ExpiryDate);
  147. Assert.AreEqual(3.99m, p.Price);
  148. }
  149. [Test]
  150. public void DeserializeJavaScriptDate()
  151. {
  152. DateTime dateValue = new DateTime(2010, 3, 30);
  153. Dictionary<string, object> testDictionary = new Dictionary<string, object>();
  154. testDictionary["date"] = dateValue;
  155. string jsonText = JsonConvert.SerializeObject(testDictionary);
  156. #if !NET20 && !WINDOWS_PHONE
  157. MemoryStream ms = new MemoryStream();
  158. DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<string, object>));
  159. serializer.WriteObject(ms, testDictionary);
  160. byte[] data = ms.ToArray();
  161. string output = Encoding.UTF8.GetString(data, 0, data.Length);
  162. #endif
  163. Dictionary<string, object> deserializedDictionary = (Dictionary<string, object>)JsonConvert.DeserializeObject(jsonText, typeof(Dictionary<string, object>));
  164. DateTime deserializedDate = (DateTime)deserializedDictionary["date"];
  165. Assert.AreEqual(dateValue, deserializedDate);
  166. }
  167. [Test]
  168. public void TestMethodExecutorObject()
  169. {
  170. MethodExecutorObject executorObject = new MethodExecutorObject();
  171. executorObject.serverClassName = "BanSubs";
  172. executorObject.serverMethodParams = new object[] { "21321546", "101", "1236", "D:\\1.txt" };
  173. executorObject.clientGetResultFunction = "ClientBanSubsCB";
  174. string output = JsonConvert.SerializeObject(executorObject);
  175. MethodExecutorObject executorObject2 = JsonConvert.DeserializeObject(output, typeof(MethodExecutorObject)) as MethodExecutorObject;
  176. Assert.AreNotSame(executorObject, executorObject2);
  177. Assert.AreEqual(executorObject2.serverClassName, "BanSubs");
  178. Assert.AreEqual(executorObject2.serverMethodParams.Length, 4);
  179. CustomAssert.Contains(executorObject2.serverMethodParams, "101");
  180. Assert.AreEqual(executorObject2.clientGetResultFunction, "ClientBanSubsCB");
  181. }
  182. #if !SILVERLIGHT && !NETFX_CORE
  183. [Test]
  184. public void HashtableDeserialization()
  185. {
  186. string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
  187. Hashtable p = JsonConvert.DeserializeObject(value, typeof(Hashtable)) as Hashtable;
  188. Assert.AreEqual("Orange", p["Name"].ToString());
  189. }
  190. [Test]
  191. public void TypedHashtableDeserialization()
  192. {
  193. string value = @"{""Name"":""Orange"", ""Hash"":{""ExpiryDate"":""01/24/2010 12:00:00"",""UntypedArray"":[""01/24/2010 12:00:00""]}}";
  194. TypedSubHashtable p = JsonConvert.DeserializeObject(value, typeof(TypedSubHashtable)) as TypedSubHashtable;
  195. Assert.AreEqual("01/24/2010 12:00:00", p.Hash["ExpiryDate"].ToString());
  196. Assert.AreEqual(@"[
  197. ""01/24/2010 12:00:00""
  198. ]", p.Hash["UntypedArray"].ToString());
  199. }
  200. #endif
  201. [Test]
  202. public void SerializeDeserializeGetOnlyProperty()
  203. {
  204. string value = JsonConvert.SerializeObject(new GetOnlyPropertyClass());
  205. GetOnlyPropertyClass c = JsonConvert.DeserializeObject<GetOnlyPropertyClass>(value);
  206. Assert.AreEqual(c.Field, "Field");
  207. Assert.AreEqual(c.GetOnlyProperty, "GetOnlyProperty");
  208. }
  209. [Test]
  210. public void SerializeDeserializeSetOnlyProperty()
  211. {
  212. string value = JsonConvert.SerializeObject(new SetOnlyPropertyClass());
  213. SetOnlyPropertyClass c = JsonConvert.DeserializeObject<SetOnlyPropertyClass>(value);
  214. Assert.AreEqual(c.Field, "Field");
  215. }
  216. [Test]
  217. public void JsonIgnoreAttributeTest()
  218. {
  219. string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeTestClass());
  220. Assert.AreEqual(@"{""Field"":0,""Property"":21}", json);
  221. JsonIgnoreAttributeTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeTestClass>(@"{""Field"":99,""Property"":-1,""IgnoredField"":-1,""IgnoredObject"":[1,2,3,4,5]}");
  222. Assert.AreEqual(0, c.IgnoredField);
  223. Assert.AreEqual(99, c.Field);
  224. }
  225. [Test]
  226. public void GoogleSearchAPI()
  227. {
  228. string json = @"{
  229. results:
  230. [
  231. {
  232. GsearchResultClass:""GwebSearch"",
  233. unescapedUrl : ""http://www.google.com/"",
  234. url : ""http://www.google.com/"",
  235. visibleUrl : ""www.google.com"",
  236. cacheUrl :
  237. ""http://www.google.com/search?q=cache:zhool8dxBV4J:www.google.com"",
  238. title : ""Google"",
  239. titleNoFormatting : ""Google"",
  240. content : ""Enables users to search the Web, Usenet, and
  241. images. Features include PageRank, caching and translation of
  242. results, and an option to find similar pages.""
  243. },
  244. {
  245. GsearchResultClass:""GwebSearch"",
  246. unescapedUrl : ""http://news.google.com/"",
  247. url : ""http://news.google.com/"",
  248. visibleUrl : ""news.google.com"",
  249. cacheUrl :
  250. ""http://www.google.com/search?q=cache:Va_XShOz_twJ:news.google.com"",
  251. title : ""Google News"",
  252. titleNoFormatting : ""Google News"",
  253. content : ""Aggregated headlines and a search engine of many of the world's news sources.""
  254. },
  255. {
  256. GsearchResultClass:""GwebSearch"",
  257. unescapedUrl : ""http://groups.google.com/"",
  258. url : ""http://groups.google.com/"",
  259. visibleUrl : ""groups.google.com"",
  260. cacheUrl :
  261. ""http://www.google.com/search?q=cache:x2uPD3hfkn0J:groups.google.com"",
  262. title : ""Google Groups"",
  263. titleNoFormatting : ""Google Groups"",
  264. content : ""Enables users to search and browse the Usenet
  265. archives which consist of over 700 million messages, and post new
  266. comments.""
  267. },
  268. {
  269. GsearchResultClass:""GwebSearch"",
  270. unescapedUrl : ""http://maps.google.com/"",
  271. url : ""http://maps.google.com/"",
  272. visibleUrl : ""maps.google.com"",
  273. cacheUrl :
  274. ""http://www.google.com/search?q=cache:dkf5u2twBXIJ:maps.google.com"",
  275. title : ""Google Maps"",
  276. titleNoFormatting : ""Google Maps"",
  277. content : ""Provides directions, interactive maps, and
  278. satellite/aerial imagery of the United States. Can also search by
  279. keyword such as type of business.""
  280. }
  281. ],
  282. adResults:
  283. [
  284. {
  285. GsearchResultClass:""GwebSearch.ad"",
  286. title : ""Gartner Symposium/ITxpo"",
  287. content1 : ""Meet brilliant Gartner IT analysts"",
  288. content2 : ""20-23 May 2007- Barcelona, Spain"",
  289. url :
  290. ""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="",
  291. impressionUrl :
  292. ""http://www.google.com/uds/css/ad-indicator-on.gif?ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB"",
  293. unescapedUrl :
  294. ""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="",
  295. visibleUrl : ""www.gartner.com""
  296. }
  297. ]
  298. }
  299. ";
  300. object o = JsonConvert.DeserializeObject(json);
  301. string s = string.Empty;
  302. s += s;
  303. }
  304. [Test]
  305. public void TorrentDeserializeTest()
  306. {
  307. string jsonText = @"{
  308. """":"""",
  309. ""label"": [
  310. [""SomeName"",6]
  311. ],
  312. ""torrents"": [
  313. [""192D99A5C943555CB7F00A852821CF6D6DB3008A"",201,""filename.avi"",178311826,1000,178311826,72815250,408,1603,7,121430,""NameOfLabelPrevioslyDefined"",3,6,0,8,128954,-1,0],
  314. ],
  315. ""torrentc"": ""1816000723""
  316. }";
  317. JObject o = (JObject)JsonConvert.DeserializeObject(jsonText);
  318. Assert.AreEqual(4, o.Children().Count());
  319. JToken torrentsArray = (JToken)o["torrents"];
  320. JToken nestedTorrentsArray = (JToken)torrentsArray[0];
  321. Assert.AreEqual(nestedTorrentsArray.Children().Count(), 19);
  322. }
  323. [Test]
  324. public void JsonPropertyClassSerialize()
  325. {
  326. JsonPropertyClass test = new JsonPropertyClass();
  327. test.Pie = "Delicious";
  328. test.SweetCakesCount = int.MaxValue;
  329. string jsonText = JsonConvert.SerializeObject(test);
  330. Assert.AreEqual(@"{""pie"":""Delicious"",""pie1"":""PieChart!"",""sweet_cakes_count"":2147483647}", jsonText);
  331. JsonPropertyClass test2 = JsonConvert.DeserializeObject<JsonPropertyClass>(jsonText);
  332. Assert.AreEqual(test.Pie, test2.Pie);
  333. Assert.AreEqual(test.SweetCakesCount, test2.SweetCakesCount);
  334. }
  335. [Test]
  336. public void BadJsonPropertyClassSerialize()
  337. {
  338. ExceptionAssert.Throws<JsonSerializationException>(
  339. @"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name.",
  340. () =>
  341. {
  342. JsonConvert.SerializeObject(new BadJsonPropertyClass());
  343. });
  344. }
  345. [Test]
  346. public void InheritedListSerialize()
  347. {
  348. Article a1 = new Article("a1");
  349. Article a2 = new Article("a2");
  350. ArticleCollection articles1 = new ArticleCollection();
  351. articles1.Add(a1);
  352. articles1.Add(a2);
  353. string jsonText = JsonConvert.SerializeObject(articles1);
  354. ArticleCollection articles2 = JsonConvert.DeserializeObject<ArticleCollection>(jsonText);
  355. Assert.AreEqual(articles1.Count, articles2.Count);
  356. Assert.AreEqual(articles1[0].Name, articles2[0].Name);
  357. }
  358. [Test]
  359. public void ReadOnlyCollectionSerialize()
  360. {
  361. ReadOnlyCollection<int> r1 = new ReadOnlyCollection<int>(new int[] { 0, 1, 2, 3, 4 });
  362. string jsonText = JsonConvert.SerializeObject(r1);
  363. ReadOnlyCollection<int> r2 = JsonConvert.DeserializeObject<ReadOnlyCollection<int>>(jsonText);
  364. CollectionAssert.AreEqual(r1, r2);
  365. }
  366. #if !NET20 && !WINDOWS_PHONE
  367. [Test]
  368. public void Unicode()
  369. {
  370. string json = @"[""PRE\u003cPOST""]";
  371. DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<string>));
  372. List<string> dataContractResult = (List<string>)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
  373. List<string> jsonNetResult = JsonConvert.DeserializeObject<List<string>>(json);
  374. Assert.AreEqual(1, jsonNetResult.Count);
  375. Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
  376. }
  377. [Test]
  378. public void BackslashEqivilence()
  379. {
  380. string json = @"[""vvv\/vvv\tvvv\""vvv\bvvv\nvvv\rvvv\\vvv\fvvv""]";
  381. #if !SILVERLIGHT && !NETFX_CORE
  382. JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
  383. List<string> javaScriptSerializerResult = javaScriptSerializer.Deserialize<List<string>>(json);
  384. #endif
  385. DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<string>));
  386. List<string> dataContractResult = (List<string>)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
  387. List<string> jsonNetResult = JsonConvert.DeserializeObject<List<string>>(json);
  388. Assert.AreEqual(1, jsonNetResult.Count);
  389. Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
  390. #if !SILVERLIGHT && !NETFX_CORE
  391. Assert.AreEqual(javaScriptSerializerResult[0], jsonNetResult[0]);
  392. #endif
  393. }
  394. [Test]
  395. public void InvalidBackslash()
  396. {
  397. string json = @"[""vvv\jvvv""]";
  398. ExceptionAssert.Throws<JsonReaderException>(
  399. @"Bad JSON escape sequence: \j. Path '', line 1, position 7.",
  400. () =>
  401. {
  402. JsonConvert.DeserializeObject<List<string>>(json);
  403. });
  404. }
  405. [Test]
  406. public void DateTimeTest()
  407. {
  408. List<DateTime> testDates = new List<DateTime>
  409. {
  410. new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Local),
  411. new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
  412. new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc),
  413. new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local),
  414. new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
  415. new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc),
  416. };
  417. MemoryStream ms = new MemoryStream();
  418. DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<DateTime>));
  419. s.WriteObject(ms, testDates);
  420. ms.Seek(0, SeekOrigin.Begin);
  421. StreamReader sr = new StreamReader(ms);
  422. string expected = sr.ReadToEnd();
  423. string result = JsonConvert.SerializeObject(testDates, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
  424. Assert.AreEqual(expected, result);
  425. }
  426. [Test]
  427. public void DateTimeOffsetIso()
  428. {
  429. List<DateTimeOffset> testDates = new List<DateTimeOffset>
  430. {
  431. new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
  432. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
  433. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
  434. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
  435. };
  436. string result = JsonConvert.SerializeObject(testDates);
  437. 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);
  438. }
  439. [Test]
  440. public void DateTimeOffsetMsAjax()
  441. {
  442. List<DateTimeOffset> testDates = new List<DateTimeOffset>
  443. {
  444. new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
  445. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
  446. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
  447. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
  448. };
  449. string result = JsonConvert.SerializeObject(testDates, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
  450. Assert.AreEqual(@"[""\/Date(-59011455539000+0000)\/"",""\/Date(946688461000+0000)\/"",""\/Date(946641661000+1300)\/"",""\/Date(946701061000-0330)\/""]", result);
  451. }
  452. #endif
  453. [Test]
  454. public void NonStringKeyDictionary()
  455. {
  456. Dictionary<int, int> values = new Dictionary<int, int>();
  457. values.Add(-5, 6);
  458. values.Add(int.MinValue, int.MaxValue);
  459. string json = JsonConvert.SerializeObject(values);
  460. Assert.AreEqual(@"{""-5"":6,""-2147483648"":2147483647}", json);
  461. Dictionary<int, int> newValues = JsonConvert.DeserializeObject<Dictionary<int, int>>(json);
  462. CollectionAssert.AreEqual(values, newValues);
  463. }
  464. [Test]
  465. public void AnonymousObjectSerialization()
  466. {
  467. var anonymous =
  468. new
  469. {
  470. StringValue = "I am a string",
  471. IntValue = int.MaxValue,
  472. NestedAnonymous = new { NestedValue = byte.MaxValue },
  473. NestedArray = new[] { 1, 2 },
  474. Product = new Product() { Name = "TestProduct" }
  475. };
  476. string json = JsonConvert.SerializeObject(anonymous);
  477. 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);
  478. anonymous = JsonConvert.DeserializeAnonymousType(json, anonymous);
  479. Assert.AreEqual("I am a string", anonymous.StringValue);
  480. Assert.AreEqual(int.MaxValue, anonymous.IntValue);
  481. Assert.AreEqual(255, anonymous.NestedAnonymous.NestedValue);
  482. Assert.AreEqual(2, anonymous.NestedArray.Length);
  483. Assert.AreEqual(1, anonymous.NestedArray[0]);
  484. Assert.AreEqual(2, anonymous.NestedArray[1]);
  485. Assert.AreEqual("TestProduct", anonymous.Product.Name);
  486. }
  487. [Test]
  488. public void CustomCollectionSerialization()
  489. {
  490. ProductCollection collection = new ProductCollection()
  491. {
  492. new Product() {Name = "Test1"},
  493. new Product() {Name = "Test2"},
  494. new Product() {Name = "Test3"}
  495. };
  496. JsonSerializer jsonSerializer = new JsonSerializer();
  497. jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  498. StringWriter sw = new StringWriter();
  499. jsonSerializer.Serialize(sw, collection);
  500. 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}]",
  501. sw.GetStringBuilder().ToString());
  502. ProductCollection collectionNew = (ProductCollection)jsonSerializer.Deserialize(new JsonTextReader(new StringReader(sw.GetStringBuilder().ToString())), typeof(ProductCollection));
  503. CollectionAssert.AreEqual(collection, collectionNew);
  504. }
  505. [Test]
  506. public void SerializeObject()
  507. {
  508. string json = JsonConvert.SerializeObject(new object());
  509. Assert.AreEqual("{}", json);
  510. }
  511. [Test]
  512. public void SerializeNull()
  513. {
  514. string json = JsonConvert.SerializeObject(null);
  515. Assert.AreEqual("null", json);
  516. }
  517. [Test]
  518. public void CanDeserializeIntArrayWhenNotFirstPropertyInJson()
  519. {
  520. string json = "{foo:'hello',bar:[1,2,3]}";
  521. ClassWithArray wibble = JsonConvert.DeserializeObject<ClassWithArray>(json);
  522. Assert.AreEqual("hello", wibble.Foo);
  523. Assert.AreEqual(4, wibble.Bar.Count);
  524. Assert.AreEqual(int.MaxValue, wibble.Bar[0]);
  525. Assert.AreEqual(1, wibble.Bar[1]);
  526. Assert.AreEqual(2, wibble.Bar[2]);
  527. Assert.AreEqual(3, wibble.Bar[3]);
  528. }
  529. [Test]
  530. public void CanDeserializeIntArray_WhenArrayIsFirstPropertyInJson()
  531. {
  532. string json = "{bar:[1,2,3], foo:'hello'}";
  533. ClassWithArray wibble = JsonConvert.DeserializeObject<ClassWithArray>(json);
  534. Assert.AreEqual("hello", wibble.Foo);
  535. Assert.AreEqual(4, wibble.Bar.Count);
  536. Assert.AreEqual(int.MaxValue, wibble.Bar[0]);
  537. Assert.AreEqual(1, wibble.Bar[1]);
  538. Assert.AreEqual(2, wibble.Bar[2]);
  539. Assert.AreEqual(3, wibble.Bar[3]);
  540. }
  541. [Test]
  542. public void ObjectCreationHandlingReplace()
  543. {
  544. string json = "{bar:[1,2,3], foo:'hello'}";
  545. JsonSerializer s = new JsonSerializer();
  546. s.ObjectCreationHandling = ObjectCreationHandling.Replace;
  547. ClassWithArray wibble = (ClassWithArray)s.Deserialize(new StringReader(json), typeof(ClassWithArray));
  548. Assert.AreEqual("hello", wibble.Foo);
  549. Assert.AreEqual(1, wibble.Bar.Count);
  550. }
  551. [Test]
  552. public void CanDeserializeSerializedJson()
  553. {
  554. ClassWithArray wibble = new ClassWithArray();
  555. wibble.Foo = "hello";
  556. wibble.Bar.Add(1);
  557. wibble.Bar.Add(2);
  558. wibble.Bar.Add(3);
  559. string json = JsonConvert.SerializeObject(wibble);
  560. ClassWithArray wibbleOut = JsonConvert.DeserializeObject<ClassWithArray>(json);
  561. Assert.AreEqual("hello", wibbleOut.Foo);
  562. Assert.AreEqual(5, wibbleOut.Bar.Count);
  563. Assert.AreEqual(int.MaxValue, wibbleOut.Bar[0]);
  564. Assert.AreEqual(int.MaxValue, wibbleOut.Bar[1]);
  565. Assert.AreEqual(1, wibbleOut.Bar[2]);
  566. Assert.AreEqual(2, wibbleOut.Bar[3]);
  567. Assert.AreEqual(3, wibbleOut.Bar[4]);
  568. }
  569. [Test]
  570. public void SerializeConverableObjects()
  571. {
  572. string json = JsonConvert.SerializeObject(new ConverableMembers(), Formatting.Indented);
  573. string expected = null;
  574. #if !(NETFX_CORE || PORTABLE)
  575. expected = @"{
  576. ""String"": ""string"",
  577. ""Int32"": 2147483647,
  578. ""UInt32"": 4294967295,
  579. ""Byte"": 255,
  580. ""SByte"": 127,
  581. ""Short"": 32767,
  582. ""UShort"": 65535,
  583. ""Long"": 9223372036854775807,
  584. ""ULong"": 9223372036854775807,
  585. ""Double"": 1.7976931348623157E+308,
  586. ""Float"": 3.40282347E+38,
  587. ""DBNull"": null,
  588. ""Bool"": true,
  589. ""Char"": ""\u0000""
  590. }";
  591. #else
  592. expected = @"{
  593. ""String"": ""string"",
  594. ""Int32"": 2147483647,
  595. ""UInt32"": 4294967295,
  596. ""Byte"": 255,
  597. ""SByte"": 127,
  598. ""Short"": 32767,
  599. ""UShort"": 65535,
  600. ""Long"": 9223372036854775807,
  601. ""ULong"": 9223372036854775807,
  602. ""Double"": 1.7976931348623157E+308,
  603. ""Float"": 3.40282347E+38,
  604. ""Bool"": true,
  605. ""Char"": ""\u0000""
  606. }";
  607. #endif
  608. Assert.AreEqual(expected, json);
  609. ConverableMembers c = JsonConvert.DeserializeObject<ConverableMembers>(json);
  610. Assert.AreEqual("string", c.String);
  611. Assert.AreEqual(double.MaxValue, c.Double);
  612. #if !(NETFX_CORE || PORTABLE)
  613. Assert.AreEqual(DBNull.Value, c.DBNull);
  614. #endif
  615. }
  616. [Test]
  617. public void SerializeStack()
  618. {
  619. Stack<object> s = new Stack<object>();
  620. s.Push(1);
  621. s.Push(2);
  622. s.Push(3);
  623. string json = JsonConvert.SerializeObject(s);
  624. Assert.AreEqual("[3,2,1]", json);
  625. }
  626. [Test]
  627. public void GuidTest()
  628. {
  629. Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
  630. string json = JsonConvert.SerializeObject(new ClassWithGuid { GuidField = guid });
  631. Assert.AreEqual(@"{""GuidField"":""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""}", json);
  632. ClassWithGuid c = JsonConvert.DeserializeObject<ClassWithGuid>(json);
  633. Assert.AreEqual(guid, c.GuidField);
  634. }
  635. [Test]
  636. public void EnumTest()
  637. {
  638. string json = JsonConvert.SerializeObject(StringComparison.CurrentCultureIgnoreCase);
  639. Assert.AreEqual(@"1", json);
  640. StringComparison s = JsonConvert.DeserializeObject<StringComparison>(json);
  641. Assert.AreEqual(StringComparison.CurrentCultureIgnoreCase, s);
  642. }
  643. public class ClassWithTimeSpan
  644. {
  645. public TimeSpan TimeSpanField;
  646. }
  647. [Test]
  648. public void TimeSpanTest()
  649. {
  650. TimeSpan ts = new TimeSpan(00, 23, 59, 1);
  651. string json = JsonConvert.SerializeObject(new ClassWithTimeSpan { TimeSpanField = ts }, Formatting.Indented);
  652. Assert.AreEqual(@"{
  653. ""TimeSpanField"": ""23:59:01""
  654. }", json);
  655. ClassWithTimeSpan c = JsonConvert.DeserializeObject<ClassWithTimeSpan>(json);
  656. Assert.AreEqual(ts, c.TimeSpanField);
  657. }
  658. [Test]
  659. public void JsonIgnoreAttributeOnClassTest()
  660. {
  661. string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeOnClassTestClass());
  662. Assert.AreEqual(@"{""TheField"":0,""Property"":21}", json);
  663. JsonIgnoreAttributeOnClassTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeOnClassTestClass>(@"{""TheField"":99,""Property"":-1,""IgnoredField"":-1}");
  664. Assert.AreEqual(0, c.IgnoredField);
  665. Assert.AreEqual(99, c.Field);
  666. }
  667. #if !SILVERLIGHT && !NETFX_CORE
  668. [Test]
  669. public void SerializeArrayAsArrayList()
  670. {
  671. string jsonText = @"[3, ""somestring"",[1,2,3],{}]";
  672. ArrayList o = JsonConvert.DeserializeObject<ArrayList>(jsonText);
  673. Assert.AreEqual(4, o.Count);
  674. Assert.AreEqual(3, ((JArray)o[2]).Count);
  675. Assert.AreEqual(0, ((JObject)o[3]).Count);
  676. }
  677. #endif
  678. [Test]
  679. public void SerializeMemberGenericList()
  680. {
  681. Name name = new Name("The Idiot in Next To Me");
  682. PhoneNumber p1 = new PhoneNumber("555-1212");
  683. PhoneNumber p2 = new PhoneNumber("444-1212");
  684. name.pNumbers.Add(p1);
  685. name.pNumbers.Add(p2);
  686. string json = JsonConvert.SerializeObject(name, Formatting.Indented);
  687. Assert.AreEqual(@"{
  688. ""personsName"": ""The Idiot in Next To Me"",
  689. ""pNumbers"": [
  690. {
  691. ""phoneNumber"": ""555-1212""
  692. },
  693. {
  694. ""phoneNumber"": ""444-1212""
  695. }
  696. ]
  697. }", json);
  698. Name newName = JsonConvert.DeserializeObject<Name>(json);
  699. Assert.AreEqual("The Idiot in Next To Me", newName.personsName);
  700. // not passed in as part of the constructor but assigned to pNumbers property
  701. Assert.AreEqual(2, newName.pNumbers.Count);
  702. Assert.AreEqual("555-1212", newName.pNumbers[0].phoneNumber);
  703. Assert.AreEqual("444-1212", newName.pNumbers[1].phoneNumber);
  704. }
  705. [Test]
  706. public void ConstructorCaseSensitivity()
  707. {
  708. ConstructorCaseSensitivityClass c = new ConstructorCaseSensitivityClass("param1", "Param1", "Param2");
  709. string json = JsonConvert.SerializeObject(c);
  710. ConstructorCaseSensitivityClass deserialized = JsonConvert.DeserializeObject<ConstructorCaseSensitivityClass>(json);
  711. Assert.AreEqual("param1", deserialized.param1);
  712. Assert.AreEqual("Param1", deserialized.Param1);
  713. Assert.AreEqual("Param2", deserialized.Param2);
  714. }
  715. [Test]
  716. public void SerializerShouldUseClassConverter()
  717. {
  718. ConverterPrecedenceClass c1 = new ConverterPrecedenceClass("!Test!");
  719. string json = JsonConvert.SerializeObject(c1);
  720. Assert.AreEqual(@"[""Class"",""!Test!""]", json);
  721. ConverterPrecedenceClass c2 = JsonConvert.DeserializeObject<ConverterPrecedenceClass>(json);
  722. Assert.AreEqual("!Test!", c2.TestValue);
  723. }
  724. [Test]
  725. public void SerializerShouldUseClassConverterOverArgumentConverter()
  726. {
  727. ConverterPrecedenceClass c1 = new ConverterPrecedenceClass("!Test!");
  728. string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
  729. Assert.AreEqual(@"[""Class"",""!Test!""]", json);
  730. ConverterPrecedenceClass c2 = JsonConvert.DeserializeObject<ConverterPrecedenceClass>(json, new ArgumentConverterPrecedenceClassConverter());
  731. Assert.AreEqual("!Test!", c2.TestValue);
  732. }
  733. [Test]
  734. public void SerializerShouldUseMemberConverter_IsoDate()
  735. {
  736. DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  737. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  738. string json = JsonConvert.SerializeObject(m1);
  739. Assert.AreEqual(@"{""DefaultConverter"":""1970-01-01T00:00:00Z"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  740. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
  741. Assert.AreEqual(testDate, m2.DefaultConverter);
  742. Assert.AreEqual(testDate, m2.MemberConverter);
  743. }
  744. [Test]
  745. public void SerializerShouldUseMemberConverter_MsDate()
  746. {
  747. DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  748. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  749. string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
  750. {
  751. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  752. });
  753. Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  754. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
  755. Assert.AreEqual(testDate, m2.DefaultConverter);
  756. Assert.AreEqual(testDate, m2.MemberConverter);
  757. }
  758. [Test]
  759. public void SerializerShouldUseMemberConverter_MsDate_DateParseNone()
  760. {
  761. DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  762. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  763. string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
  764. {
  765. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
  766. });
  767. Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  768. ExceptionAssert.Throws<JsonReaderException>(
  769. "Could not convert string to DateTime: /Date(0)/. Path 'DefaultConverter', line 1, position 33.",
  770. () =>
  771. {
  772. JsonConvert.DeserializeObject<MemberConverterClass>(json, new JsonSerializerSettings
  773. {
  774. DateParseHandling = DateParseHandling.None
  775. });
  776. });
  777. }
  778. [Test]
  779. public void SerializerShouldUseMemberConverter_IsoDate_DateParseNone()
  780. {
  781. DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  782. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  783. string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
  784. {
  785. DateFormatHandling = DateFormatHandling.IsoDateFormat,
  786. });
  787. Assert.AreEqual(@"{""DefaultConverter"":""1970-01-01T00:00:00Z"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  788. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
  789. Assert.AreEqual(testDate, m2.DefaultConverter);
  790. Assert.AreEqual(testDate, m2.MemberConverter);
  791. }
  792. [Test]
  793. public void SerializerShouldUseMemberConverterOverArgumentConverter()
  794. {
  795. DateTime testDate = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  796. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  797. string json = JsonConvert.SerializeObject(m1, new JavaScriptDateTimeConverter());
  798. Assert.AreEqual(@"{""DefaultConverter"":new Date(0),""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  799. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json, new JavaScriptDateTimeConverter());
  800. Assert.AreEqual(testDate, m2.DefaultConverter);
  801. Assert.AreEqual(testDate, m2.MemberConverter);
  802. }
  803. [Test]
  804. public void ConverterAttributeExample()
  805. {
  806. DateTime date = Convert.ToDateTime("1970-01-01T00:00:00Z").ToUniversalTime();
  807. MemberConverterClass c = new MemberConverterClass
  808. {
  809. DefaultConverter = date,
  810. MemberConverter = date
  811. };
  812. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  813. Console.WriteLine(json);
  814. //{
  815. // "DefaultConverter": "\/Date(0)\/",
  816. // "MemberConverter": "1970-01-01T00:00:00Z"
  817. //}
  818. }
  819. [Test]
  820. public void SerializerShouldUseMemberConverterOverClassAndArgumentConverter()
  821. {
  822. ClassAndMemberConverterClass c1 = new ClassAndMemberConverterClass();
  823. c1.DefaultConverter = new ConverterPrecedenceClass("DefaultConverterValue");
  824. c1.MemberConverter = new ConverterPrecedenceClass("MemberConverterValue");
  825. string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
  826. Assert.AreEqual(@"{""DefaultConverter"":[""Class"",""DefaultConverterValue""],""MemberConverter"":[""Member"",""MemberConverterValue""]}", json);
  827. ClassAndMemberConverterClass c2 = JsonConvert.DeserializeObject<ClassAndMemberConverterClass>(json, new ArgumentConverterPrecedenceClassConverter());
  828. Assert.AreEqual("DefaultConverterValue", c2.DefaultConverter.TestValue);
  829. Assert.AreEqual("MemberConverterValue", c2.MemberConverter.TestValue);
  830. }
  831. [Test]
  832. public void IncompatibleJsonAttributeShouldThrow()
  833. {
  834. ExceptionAssert.Throws<JsonSerializationException>(
  835. "Unexpected value when converting date. Expected DateTime or DateTimeOffset, got Newtonsoft.Json.Tests.TestObjects.IncompatibleJsonAttributeClass.",
  836. () =>
  837. {
  838. IncompatibleJsonAttributeClass c = new IncompatibleJsonAttributeClass();
  839. JsonConvert.SerializeObject(c);
  840. });
  841. }
  842. [Test]
  843. public void GenericAbstractProperty()
  844. {
  845. string json = JsonConvert.SerializeObject(new GenericImpl());
  846. Assert.AreEqual(@"{""Id"":0}", json);
  847. }
  848. [Test]
  849. public void DeserializeNullable()
  850. {
  851. string json;
  852. json = JsonConvert.SerializeObject((int?)null);
  853. Assert.AreEqual("null", json);
  854. json = JsonConvert.SerializeObject((int?)1);
  855. Assert.AreEqual("1", json);
  856. }
  857. [Test]
  858. public void SerializeJsonRaw()
  859. {
  860. PersonRaw personRaw = new PersonRaw
  861. {
  862. FirstName = "FirstNameValue",
  863. RawContent = new JRaw("[1,2,3,4,5]"),
  864. LastName = "LastNameValue"
  865. };
  866. string json;
  867. json = JsonConvert.SerializeObject(personRaw);
  868. Assert.AreEqual(@"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}", json);
  869. }
  870. [Test]
  871. public void DeserializeJsonRaw()
  872. {
  873. string json = @"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}";
  874. PersonRaw personRaw = JsonConvert.DeserializeObject<PersonRaw>(json);
  875. Assert.AreEqual("FirstNameValue", personRaw.FirstName);
  876. Assert.AreEqual("[1,2,3,4,5]", personRaw.RawContent.ToString());
  877. Assert.AreEqual("LastNameValue", personRaw.LastName);
  878. }
  879. [Test]
  880. public void DeserializeNullableMember()
  881. {
  882. UserNullable userNullablle = new UserNullable
  883. {
  884. Id = new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"),
  885. FName = "FirstValue",
  886. LName = "LastValue",
  887. RoleId = 5,
  888. NullableRoleId = 6,
  889. NullRoleId = null,
  890. Active = true
  891. };
  892. string json = JsonConvert.SerializeObject(userNullablle);
  893. Assert.AreEqual(@"{""Id"":""ad6205e8-0df4-465d-aea6-8ba18e93a7e7"",""FName"":""FirstValue"",""LName"":""LastValue"",""RoleId"":5,""NullableRoleId"":6,""NullRoleId"":null,""Active"":true}", json);
  894. UserNullable userNullablleDeserialized = JsonConvert.DeserializeObject<UserNullable>(json);
  895. Assert.AreEqual(new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"), userNullablleDeserialized.Id);
  896. Assert.AreEqual("FirstValue", userNullablleDeserialized.FName);
  897. Assert.AreEqual("LastValue", userNullablleDeserialized.LName);
  898. Assert.AreEqual(5, userNullablleDeserialized.RoleId);
  899. Assert.AreEqual(6, userNullablleDeserialized.NullableRoleId);
  900. Assert.AreEqual(null, userNullablleDeserialized.NullRoleId);
  901. Assert.AreEqual(true, userNullablleDeserialized.Active);
  902. }
  903. [Test]
  904. public void DeserializeInt64ToNullableDouble()
  905. {
  906. string json = @"{""Height"":1}";
  907. DoubleClass c = JsonConvert.DeserializeObject<DoubleClass>(json);
  908. Assert.AreEqual(1, c.Height);
  909. }
  910. [Test]
  911. public void SerializeTypeProperty()
  912. {
  913. string boolRef = typeof(bool).AssemblyQualifiedName;
  914. TypeClass typeClass = new TypeClass { TypeProperty = typeof(bool) };
  915. string json = JsonConvert.SerializeObject(typeClass);
  916. Assert.AreEqual(@"{""TypeProperty"":""" + boolRef + @"""}", json);
  917. TypeClass typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
  918. Assert.AreEqual(typeof(bool), typeClass2.TypeProperty);
  919. string jsonSerializerTestRef = typeof(JsonSerializerTest).AssemblyQualifiedName;
  920. typeClass = new TypeClass { TypeProperty = typeof(JsonSerializerTest) };
  921. json = JsonConvert.SerializeObject(typeClass);
  922. Assert.AreEqual(@"{""TypeProperty"":""" + jsonSerializerTestRef + @"""}", json);
  923. typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
  924. Assert.AreEqual(typeof(JsonSerializerTest), typeClass2.TypeProperty);
  925. }
  926. [Test]
  927. public void RequiredMembersClass()
  928. {
  929. RequiredMembersClass c = new RequiredMembersClass()
  930. {
  931. BirthDate = new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc),
  932. FirstName = "Bob",
  933. LastName = "Smith",
  934. MiddleName = "Cosmo"
  935. };
  936. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  937. Assert.AreEqual(@"{
  938. ""FirstName"": ""Bob"",
  939. ""MiddleName"": ""Cosmo"",
  940. ""LastName"": ""Smith"",
  941. ""BirthDate"": ""2000-12-20T10:55:55Z""
  942. }", json);
  943. RequiredMembersClass c2 = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  944. Assert.AreEqual("Bob", c2.FirstName);
  945. Assert.AreEqual(new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc), c2.BirthDate);
  946. }
  947. [Test]
  948. public void DeserializeRequiredMembersClassWithNullValues()
  949. {
  950. string json = @"{
  951. ""FirstName"": ""I can't be null bro!"",
  952. ""MiddleName"": null,
  953. ""LastName"": null,
  954. ""BirthDate"": ""\/Date(977309755000)\/""
  955. }";
  956. RequiredMembersClass c = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  957. Assert.AreEqual("I can't be null bro!", c.FirstName);
  958. Assert.AreEqual(null, c.MiddleName);
  959. Assert.AreEqual(null, c.LastName);
  960. }
  961. [Test]
  962. public void DeserializeRequiredMembersClassNullRequiredValueProperty()
  963. {
  964. ExceptionAssert.Throws<JsonSerializationException>(
  965. "Required property 'FirstName' expects a value but got null. Path '', line 6, position 2.",
  966. () =>
  967. {
  968. string json = @"{
  969. ""FirstName"": null,
  970. ""MiddleName"": null,
  971. ""LastName"": null,
  972. ""BirthDate"": ""\/Date(977309755000)\/""
  973. }";
  974. JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  975. });
  976. }
  977. [Test]
  978. public void SerializeRequiredMembersClassNullRequiredValueProperty()
  979. {
  980. ExceptionAssert.Throws<JsonSerializationException>(
  981. "Cannot write a null value for property 'FirstName'. Property requires a value. Path ''.",
  982. () =>
  983. {
  984. RequiredMembersClass requiredMembersClass = new RequiredMembersClass
  985. {
  986. FirstName = null,
  987. BirthDate = new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc),
  988. LastName = null,
  989. MiddleName = null
  990. };
  991. string json = JsonConvert.SerializeObject(requiredMembersClass);
  992. Console.WriteLine(json);
  993. });
  994. }
  995. [Test]
  996. public void RequiredMembersClassMissingRequiredProperty()
  997. {
  998. ExceptionAssert.Throws<JsonSerializationException>(
  999. "Required property 'LastName' not found in JSON. Path '', line 3, position 2.",
  1000. () =>
  1001. {
  1002. string json = @"{
  1003. ""FirstName"": ""Bob""
  1004. }";
  1005. JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  1006. });
  1007. }
  1008. [Test]
  1009. public void SerializeJaggedArray()
  1010. {
  1011. JaggedArray aa = new JaggedArray();
  1012. aa.Before = "Before!";
  1013. aa.After = "After!";
  1014. aa.Coordinates = new[] { new[] { 1, 1 }, new[] { 1, 2 }, new[] { 2, 1 }, new[] { 2, 2 } };
  1015. string json = JsonConvert.SerializeObject(aa);
  1016. Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}", json);
  1017. }
  1018. [Test]
  1019. public void DeserializeJaggedArray()
  1020. {
  1021. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}";
  1022. JaggedArray aa = JsonConvert.DeserializeObject<JaggedArray>(json);
  1023. Assert.AreEqual("Before!", aa.Before);
  1024. Assert.AreEqual("After!", aa.After);
  1025. Assert.AreEqual(4, aa.Coordinates.Length);
  1026. Assert.AreEqual(2, aa.Coordinates[0].Length);
  1027. Assert.AreEqual(1, aa.Coordinates[0][0]);
  1028. Assert.AreEqual(2, aa.Coordinates[1][1]);
  1029. string after = JsonConvert.SerializeObject(aa);
  1030. Assert.AreEqual(json, after);
  1031. }
  1032. [Test]
  1033. public void DeserializeGoogleGeoCode()
  1034. {
  1035. string json = @"{
  1036. ""name"": ""1600 Amphitheatre Parkway, Mountain View, CA, USA"",
  1037. ""Status"": {
  1038. ""code"": 200,
  1039. ""request"": ""geocode""
  1040. },
  1041. ""Placemark"": [
  1042. {
  1043. ""address"": ""1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"",
  1044. ""AddressDetails"": {
  1045. ""Country"": {
  1046. ""CountryNameCode"": ""US"",
  1047. ""AdministrativeArea"": {
  1048. ""AdministrativeAreaName"": ""CA"",
  1049. ""SubAdministrativeArea"": {
  1050. ""SubAdministrativeAreaName"": ""Santa Clara"",
  1051. ""Locality"": {
  1052. ""LocalityName"": ""Mountain View"",
  1053. ""Thoroughfare"": {
  1054. ""ThoroughfareName"": ""1600 Amphitheatre Pkwy""
  1055. },
  1056. ""PostalCode"": {
  1057. ""PostalCodeNumber"": ""94043""
  1058. }
  1059. }
  1060. }
  1061. }
  1062. },
  1063. ""Accuracy"": 8
  1064. },
  1065. ""Point"": {
  1066. ""coordinates"": [-122.083739, 37.423021, 0]
  1067. }
  1068. }
  1069. ]
  1070. }";
  1071. GoogleMapGeocoderStructure jsonGoogleMapGeocoder = JsonConvert.DeserializeObject<GoogleMapGeocoderStructure>(json);
  1072. }
  1073. [Test]
  1074. public void DeserializeInterfaceProperty()
  1075. {
  1076. InterfacePropertyTestClass testClass = new InterfacePropertyTestClass();
  1077. testClass.co = new Co();
  1078. String strFromTest = JsonConvert.SerializeObject(testClass);
  1079. ExceptionAssert.Throws<JsonSerializationException>(
  1080. @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantiated. Path 'co.Name', line 1, position 14.",
  1081. () =>
  1082. {
  1083. InterfacePropertyTestClass testFromDe = (InterfacePropertyTestClass)JsonConvert.DeserializeObject(strFromTest, typeof(InterfacePropertyTestClass));
  1084. });
  1085. }
  1086. private Person GetPerson()
  1087. {
  1088. Person person = new Person
  1089. {
  1090. Name = "Mike Manager",
  1091. BirthDate = new DateTime(1983, 8, 3, 0, 0, 0, DateTimeKind.Utc),
  1092. Department = "IT",
  1093. LastModified = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc)
  1094. };
  1095. return person;
  1096. }
  1097. [Test]
  1098. public void WriteJsonDates()
  1099. {
  1100. LogEntry entry = new LogEntry
  1101. {
  1102. LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
  1103. Details = "Application started."
  1104. };
  1105. string defaultJson = JsonConvert.SerializeObject(entry);
  1106. // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}
  1107. string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
  1108. // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00.0000000Z"}
  1109. string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
  1110. // {"Details":"Application started.","LogDate":new Date(1234656000000)}
  1111. Console.WriteLine(defaultJson);
  1112. Console.WriteLine(isoJson);
  1113. Console.WriteLine(javascriptJson);
  1114. }
  1115. public void GenericListAndDictionaryInterfaceProperties()
  1116. {
  1117. GenericListAndDictionaryInterfaceProperties o = new GenericListAndDictionaryInterfaceProperties();
  1118. o.IDictionaryProperty = new Dictionary<string, int>
  1119. {
  1120. {"one", 1},
  1121. {"two", 2},
  1122. {"three", 3}
  1123. };
  1124. o.IListProperty = new List<int>
  1125. {
  1126. 1, 2, 3
  1127. };
  1128. o.IEnumerableProperty = new List<int>
  1129. {
  1130. 4, 5, 6
  1131. };
  1132. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  1133. Assert.AreEqual(@"{
  1134. ""IEnumerableProperty"": [
  1135. 4,
  1136. 5,
  1137. 6
  1138. ],
  1139. ""IListProperty"": [
  1140. 1,
  1141. 2,
  1142. 3
  1143. ],
  1144. ""IDictionaryProperty"": {
  1145. ""one"": 1,
  1146. ""two"": 2,
  1147. ""three"": 3
  1148. }
  1149. }", json);
  1150. GenericListAndDictionaryInterfaceProperties deserializedObject = JsonConvert.DeserializeObject<GenericListAndDictionaryInterfaceProperties>(json);
  1151. Assert.IsNotNull(deserializedObject);
  1152. CollectionAssert.AreEqual(o.IListProperty.ToArray(), deserializedObject.IListProperty.ToArray());
  1153. CollectionAssert.AreEqual(o.IEnumerableProperty.ToArray(), deserializedObject.IEnumerableProperty.ToArray());
  1154. CollectionAssert.AreEqual(o.IDictionaryProperty.ToArray(), deserializedObject.IDictionaryProperty.ToArray());
  1155. }
  1156. [Test]
  1157. public void DeserializeBestMatchPropertyCase()
  1158. {
  1159. string json = @"{
  1160. ""firstName"": ""firstName"",
  1161. ""FirstName"": ""FirstName"",
  1162. ""LastName"": ""LastName"",
  1163. ""lastName"": ""lastName"",
  1164. }";
  1165. PropertyCase o = JsonConvert.DeserializeObject<PropertyCase>(json);
  1166. Assert.IsNotNull(o);
  1167. Assert.AreEqual("firstName", o.firstName);
  1168. Assert.AreEqual("FirstName", o.FirstName);
  1169. Assert.AreEqual("LastName", o.LastName);
  1170. Assert.AreEqual("lastName", o.lastName);
  1171. }
  1172. [Test]
  1173. public void DeserializePropertiesOnToNonDefaultConstructor()
  1174. {
  1175. SubKlass i = new SubKlass("my subprop");
  1176. i.SuperProp = "overrided superprop";
  1177. string json = JsonConvert.SerializeObject(i);
  1178. Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", json);
  1179. SubKlass ii = JsonConvert.DeserializeObject<SubKlass>(json);
  1180. string newJson = JsonConvert.SerializeObject(ii);
  1181. Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", newJson);
  1182. }
  1183. [Test]
  1184. public void DeserializePropertiesOnToNonDefaultConstructorWithReferenceTracking()
  1185. {
  1186. SubKlass i = new SubKlass("my subprop");
  1187. i.SuperProp = "overrided superprop";
  1188. string json = JsonConvert.SerializeObject(i, new JsonSerializerSettings
  1189. {
  1190. PreserveReferencesHandling = PreserveReferencesHandling.Objects
  1191. });
  1192. Assert.AreEqual(@"{""$id"":""1"",""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", json);
  1193. SubKlass ii = JsonConvert.DeserializeObject<SubKlass>(json, new JsonSerializerSettings
  1194. {
  1195. PreserveReferencesHandling = PreserveReferencesHandling.Objects
  1196. });
  1197. string newJson = JsonConvert.SerializeObject(ii, new JsonSerializerSettings
  1198. {
  1199. PreserveReferencesHandling = PreserveReferencesHandling.Objects
  1200. });
  1201. Assert.AreEqual(@"{""$id"":""1"",""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", newJson);
  1202. }
  1203. [Test]
  1204. public void SerializeJsonPropertyWithHandlingValues()
  1205. {
  1206. JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
  1207. o.DefaultValueHandlingIgnoreProperty = "Default!";
  1208. o.DefaultValueHandlingIncludeProperty = "Default!";
  1209. o.DefaultValueHandlingPopulateProperty = "Default!";
  1210. o.DefaultValueHandlingIgnoreAndPopulateProperty = "Default!";
  1211. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  1212. Assert.AreEqual(@"{
  1213. ""DefaultValueHandlingIncludeProperty"": ""Default!"",
  1214. ""DefaultValueHandlingPopulateProperty"": ""Default!"",
  1215. ""NullValueHandlingIncludeProperty"": null,
  1216. ""ReferenceLoopHandlingErrorProperty"": null,
  1217. ""ReferenceLoopHandlingIgnoreProperty"": null,
  1218. ""ReferenceLoopHandlingSerializeProperty"": null
  1219. }", json);
  1220. json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
  1221. Assert.AreEqual(@"{
  1222. ""DefaultValueHandlingIncludeProperty"": ""Default!"",
  1223. ""DefaultValueHandlingPopulateProperty"": ""Default!"",
  1224. ""NullValueHandlingIncludeProperty"": null
  1225. }", json);
  1226. }
  1227. [Test]
  1228. public void DeserializeJsonPropertyWithHandlingValues()
  1229. {
  1230. string json = "{}";
  1231. JsonPropertyWithHandlingValues o = JsonConvert.DeserializeObject<JsonPropertyWithHandlingValues>(json);
  1232. Assert.AreEqual("Default!", o.DefaultValueHandlingIgnoreAndPopulateProperty);
  1233. Assert.AreEqual("Default!", o.DefaultValueHandlingPopulateProperty);
  1234. Assert.AreEqual(null, o.DefaultValueHandlingIgnoreProperty);
  1235. Assert.AreEqual(null, o.DefaultValueHandlingIncludeProperty);
  1236. }
  1237. [Test]
  1238. public void JsonPropertyWithHandlingValues_ReferenceLoopError()
  1239. {
  1240. string classRef = typeof(JsonPropertyWithHandlingValues).FullName;
  1241. ExceptionAssert.Throws<JsonSerializationException>(
  1242. "Self referencing loop detected for property 'ReferenceLoopHandlingErrorProperty' with type '" + classRef + "'. Path ''.",
  1243. () =>
  1244. {
  1245. JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
  1246. o.ReferenceLoopHandlingErrorProperty = o;
  1247. JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
  1248. });
  1249. }
  1250. [Test]
  1251. public void PartialClassDeserialize()
  1252. {
  1253. string json = @"{
  1254. ""request"": ""ux.settings.update"",
  1255. ""sid"": ""14c561bd-32a8-457e-b4e5-4bba0832897f"",
  1256. ""uid"": ""30c39065-0f31-de11-9442-001e3786a8ec"",
  1257. ""fidOrder"": [
  1258. ""id"",
  1259. ""andytest_name"",
  1260. ""andytest_age"",
  1261. ""andytest_address"",
  1262. ""andytest_phone"",
  1263. ""date"",
  1264. ""title"",
  1265. ""titleId""
  1266. ],
  1267. ""entityName"": ""Andy Test"",
  1268. ""setting"": ""entity.field.order""
  1269. }";
  1270. RequestOnly r = JsonConvert.DeserializeObject<RequestOnly>(json);
  1271. Assert.AreEqual("ux.settings.update", r.Request);
  1272. NonRequest n = JsonConvert.DeserializeObject<NonRequest>(json);
  1273. Assert.AreEqual(new Guid("14c561bd-32a8-457e-b4e5-4bba0832897f"), n.Sid);
  1274. Assert.AreEqual(new Guid("30c39065-0f31-de11-9442-001e3786a8ec"), n.Uid);
  1275. Assert.AreEqual(8, n.FidOrder.Count);
  1276. Assert.AreEqual("id", n.FidOrder[0]);
  1277. Assert.AreEqual("titleId", n.FidOrder[n.FidOrder.Count - 1]);
  1278. }
  1279. #if !(SILVERLIGHT || NET20 || NETFX_CORE || PORTABLE)
  1280. [MetadataType(typeof(OptInClassMetadata))]
  1281. public class OptInClass
  1282. {
  1283. [DataContract]
  1284. public class OptInClassMetadata
  1285. {
  1286. [DataMember]
  1287. public string Name { get; set; }
  1288. [DataMember]
  1289. public int Age { get; set; }
  1290. public string NotIncluded { get; set; }
  1291. }
  1292. public string Name { get; set; }
  1293. public int Age { get; set; }
  1294. public string NotIncluded { get; set; }
  1295. }
  1296. [Test]
  1297. public void OptInClassMetadataSerialization()
  1298. {
  1299. OptInClass optInClass = new OptInClass();
  1300. optInClass.Age = 26;
  1301. optInClass.Name = "James NK";
  1302. optInClass.NotIncluded = "Poor me :(";
  1303. string json = JsonConvert.SerializeObject(optInClass, Formatting.Indented);
  1304. Assert.AreEqual(@"{
  1305. ""Name"": ""James NK"",
  1306. ""Age"": 26
  1307. }", json);
  1308. OptInClass newOptInClass = JsonConvert.DeserializeObject<OptInClass>(@"{
  1309. ""Name"": ""James NK"",
  1310. ""NotIncluded"": ""Ignore me!"",
  1311. ""Age"": 26
  1312. }");
  1313. Assert.AreEqual(26, newOptInClass.Age);
  1314. Assert.AreEqual("James NK", newOptInClass.Name);
  1315. Assert.AreEqual(null, newOptInClass.NotIncluded);
  1316. }
  1317. #endif
  1318. #if !NET20
  1319. [DataContract]
  1320. public class DataContractPrivateMembers
  1321. {
  1322. public DataContractPrivateMembers()
  1323. {
  1324. }
  1325. public DataContractPrivateMembers(string name, int age, int rank, string title)
  1326. {
  1327. _name = name;
  1328. Age = age;
  1329. Rank = rank;
  1330. Title = title;
  1331. }
  1332. [DataMember]
  1333. private string _name;
  1334. [DataMember(Name = "_age")]
  1335. private int Age { get; set; }
  1336. [JsonProperty]
  1337. private int Rank { get; set; }
  1338. [JsonProperty(PropertyName = "JsonTitle")]
  1339. [DataMember(Name = "DataTitle")]
  1340. private string Title { get; set; }
  1341. public string NotIncluded { get; set; }
  1342. public override string ToString()
  1343. {
  1344. return "_name: " + _name + ", _age: " + Age + ", Rank: " + Rank + ", JsonTitle: " + Title;
  1345. }
  1346. }
  1347. [Test]
  1348. public void SerializeDataContractPrivateMembers()
  1349. {
  1350. DataContractPrivateMembers c = new DataContractPrivateMembers("Jeff", 26, 10, "Dr");
  1351. c.NotIncluded = "Hi";
  1352. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  1353. Assert.AreEqual(@"{
  1354. ""_name"": ""Jeff"",
  1355. ""_age"": 26,
  1356. ""Rank"": 10,
  1357. ""JsonTitle"": ""Dr""
  1358. }", json);
  1359. DataContractPrivateMembers cc = JsonConvert.DeserializeObject<DataContractPrivateMembers>(json);
  1360. Assert.AreEqual("_name: Jeff, _age: 26, Rank: 10, JsonTitle: Dr", cc.ToString());
  1361. }
  1362. #endif
  1363. [Test]
  1364. public void DeserializeDictionaryInterface()
  1365. {
  1366. string json = @"{
  1367. ""Name"": ""Name!"",
  1368. ""Dictionary"": {
  1369. ""Item"": 11
  1370. }
  1371. }";
  1372. DictionaryInterfaceClass c = JsonConvert.DeserializeObject<DictionaryInterfaceClass>(
  1373. json,
  1374. new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace });
  1375. Assert.AreEqual("Name!", c.Name);
  1376. Assert.AreEqual(1, c.Dictionary.Count);
  1377. Assert.AreEqual(11, c.Dictionary["Item"]);
  1378. }
  1379. [Test]
  1380. public void DeserializeDictionaryInterfaceWithExistingValues()
  1381. {
  1382. string json = @"{
  1383. ""Random"": {
  1384. ""blah"": 1
  1385. },
  1386. ""Name"": ""Name!"",
  1387. ""Dictionary"": {
  1388. ""Item"": 11,
  1389. ""Item1"": 12
  1390. },
  1391. ""Collection"": [
  1392. 999
  1393. ],
  1394. ""Employee"": {
  1395. ""Manager"": {
  1396. ""Name"": ""ManagerName!""
  1397. }
  1398. }
  1399. }";
  1400. DictionaryInterfaceClass c = JsonConvert.DeserializeObject<DictionaryInterfaceClass>(json,
  1401. new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Reuse });
  1402. Assert.AreEqual("Name!", c.Name);
  1403. Assert.AreEqual(3, c.Dictionary.Count);
  1404. Assert.AreEqual(11, c.Dictionary["Item"]);
  1405. Assert.AreEqual(1, c.Dictionary["existing"]);
  1406. Assert.AreEqual(4, c.Collection.Count);
  1407. Assert.AreEqual(1, c.Collection.ElementAt(0));
  1408. Assert.AreEqual(999, c.Collection.ElementAt(3));
  1409. Assert.AreEqual("EmployeeName!", c.Employee.Name);
  1410. Assert.AreEqual("ManagerName!", c.Employee.Manager.Name);
  1411. Assert.IsNotNull(c.Random);
  1412. }
  1413. [Test]
  1414. public void TypedObjectDeserializationWithComments()
  1415. {
  1416. string json = @"/*comment*/ { /*comment*/
  1417. ""Name"": /*comment*/ ""Apple"" /*comment*/, /*comment*/
  1418. ""ExpiryDate"": ""\/Date(1230422400000)\/"",
  1419. ""Price"": 3.99,
  1420. ""Sizes"": /*comment*/ [ /*comment*/
  1421. ""Small"", /*comment*/
  1422. ""Medium"" /*comment*/,
  1423. /*comment*/ ""Large""
  1424. /*comment*/ ] /*comment*/
  1425. } /*comment*/";
  1426. Product deserializedProduct = (Product)JsonConvert.DeserializeObject(json, typeof(Product));
  1427. Assert.AreEqual("Apple", deserializedProduct.Name);
  1428. Assert.AreEqual(new DateTime(2008, 12, 28, 0, 0, 0, DateTimeKind.Utc), deserializedProduct.ExpiryDate);
  1429. Assert.AreEqual(3.99m, deserializedProduct.Price);
  1430. Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
  1431. Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
  1432. Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
  1433. }
  1434. [Test]
  1435. public void NestedInsideOuterObject()
  1436. {
  1437. string json = @"{
  1438. ""short"": {
  1439. ""original"": ""http://www.contrast.ie/blog/online&#45;marketing&#45;2009/"",
  1440. ""short"": ""m2sqc6"",
  1441. ""shortened"": ""http://short.ie/m2sqc6"",
  1442. ""error"": {
  1443. ""code"": 0,
  1444. ""msg"": ""No action taken""
  1445. }
  1446. }
  1447. }";
  1448. JObject o = JObject.Parse(json);
  1449. Shortie s = JsonConvert.DeserializeObject<Shortie>(o["short"].ToString());
  1450. Assert.IsNotNull(s);
  1451. Assert.AreEqual(s.Original, "http://www.contrast.ie/blog/online&#45;marketing&#45;2009/");
  1452. Assert.AreEqual(s.Short, "m2sqc6");
  1453. Assert.AreEqual(s.Shortened, "http://short.ie/m2sqc6");
  1454. }
  1455. [Test]
  1456. public void UriSerialization()
  1457. {
  1458. Uri uri = new Uri("http://codeplex.com");
  1459. string json = JsonConvert.SerializeObject(uri);
  1460. Assert.AreEqual("http://codeplex.com/", uri.ToString());
  1461. Uri newUri = JsonConvert.DeserializeObject<Uri>(json);
  1462. Assert.AreEqual(uri, newUri);
  1463. }
  1464. [Test]
  1465. public void AnonymousPlusLinqToSql()
  1466. {
  1467. var value = new
  1468. {
  1469. bar = new JObject(new JProperty("baz", 13))
  1470. };
  1471. string json = JsonConvert.SerializeObject(value);
  1472. Assert.AreEqual(@"{""bar"":{""baz"":13}}", json);
  1473. }
  1474. [Test]
  1475. public void SerializeEnumerableAsObject()
  1476. {
  1477. Content content = new Content
  1478. {
  1479. Text = "Blah, blah, blah",
  1480. Children = new List<Content>
  1481. {
  1482. new Content {Text = "First"},
  1483. new Content {Text = "Second"}
  1484. }
  1485. };
  1486. string json = JsonConvert.SerializeObject(content, Formatting.Indented);
  1487. Assert.AreEqual(@"{
  1488. ""Children"": [
  1489. {
  1490. ""Children"": null,
  1491. ""Text"": ""First""
  1492. },
  1493. {
  1494. ""Children"": null,
  1495. ""Text"": ""Second""
  1496. }
  1497. ],
  1498. ""Text"": ""Blah, blah, blah""
  1499. }", json);
  1500. }
  1501. [Test]
  1502. public void DeserializeEnumerableAsObject()
  1503. {
  1504. string json = @"{
  1505. ""Children"": [
  1506. {
  1507. ""Children"": null,
  1508. ""Text"": ""First""
  1509. },
  1510. {
  1511. ""Children"": null,
  1512. ""Text"": ""Second""
  1513. }
  1514. ],
  1515. ""Text"": ""Blah, blah, blah""
  1516. }";
  1517. Content content = JsonConvert.DeserializeObject<Content>(json);
  1518. Assert.AreEqual("Blah, blah, blah", content.Text);
  1519. Assert.AreEqual(2, content.Children.Count);
  1520. Assert.AreEqual("First", content.Children[0].Text);
  1521. Assert.AreEqual("Second", content.Children[1].Text);
  1522. }
  1523. [Test]
  1524. public void RoleTransferTest()
  1525. {
  1526. string json = @"{""Operation"":""1"",""RoleName"":""Admin"",""Direction"":""0""}";
  1527. RoleTransfer r = JsonConvert.DeserializeObject<RoleTransfer>(json);
  1528. Assert.AreEqual(RoleTransferOperation.Second, r.Operation);
  1529. Assert.AreEqual("Admin", r.RoleName);
  1530. Assert.AreEqual(RoleTransferDirection.First, r.Direction);
  1531. }
  1532. [Test]
  1533. public void PrimitiveValuesInObjectArray()
  1534. {
  1535. string json = @"{""action"":""Router"",""method"":""Navigate"",""data"":[""dashboard"",null],""type"":""rpc"",""tid"":2}";
  1536. ObjectArrayPropertyTest o = JsonConvert.DeserializeObject<ObjectArrayPropertyTest>(json);
  1537. Assert.AreEqual("Router", o.Action);
  1538. Assert.AreEqual("Navigate", o.Method);
  1539. Assert.AreEqual(2, o.Data.Length);
  1540. Assert.AreEqual("dashboard", o.Data[0]);
  1541. Assert.AreEqual(null, o.Data[1]);
  1542. }
  1543. [Test]
  1544. public void ComplexValuesInObjectArray()
  1545. {
  1546. string json = @"{""action"":""Router"",""method"":""Navigate"",""data"":[""dashboard"",[""id"", 1, ""teststring"", ""test""],{""one"":1}],""type"":""rpc"",""tid"":2}";
  1547. ObjectArrayPropertyTest o = JsonConvert.DeserializeObject<ObjectArrayPropertyTest>(json);
  1548. Assert.AreEqual("Router", o.Action);
  1549. Assert.AreEqual("Navigate", o.Method);
  1550. Assert.AreEqual(3, o.Data.Length);
  1551. Assert.AreEqual("dashboard", o.Data[0]);
  1552. CustomAssert.IsInstanceOfType(typeof(JArray), o.Data[1]);
  1553. Assert.AreEqual(4, ((JArray)o.Data[1]).Count);
  1554. CustomAssert.IsInstanceOfType(typeof(JObject), o.Data[2]);
  1555. Assert.AreEqual(1, ((JObject)o.Data[2]).Count);
  1556. Assert.AreEqual(1, (int)((JObject)o.Data[2])["one"]);
  1557. }
  1558. [Test]
  1559. public void DeserializeGenericDictionary()
  1560. {
  1561. string json = @"{""key1"":""value1"",""key2"":""value2""}";
  1562. Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  1563. Console.WriteLine(values.Count);
  1564. // 2
  1565. Console.WriteLine(values["key1"]);
  1566. // value1
  1567. Assert.AreEqual(2, values.Count);
  1568. Assert.AreEqual("value1", values["key1"]);
  1569. Assert.AreEqual("value2", values["key2"]);
  1570. }
  1571. [Test]
  1572. public void SerializeGenericList()
  1573. {
  1574. Product p1 = new Product
  1575. {
  1576. Name = "Product 1",
  1577. Price = 99.95m,
  1578. ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
  1579. };
  1580. Product p2 = new Product
  1581. {
  1582. Name = "Product 2",
  1583. Price = 12.50m,
  1584. ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
  1585. };
  1586. List<Product> products = new List<Product>();
  1587. products.Add(p1);
  1588. products.Add(p2);
  1589. string json = JsonConvert.SerializeObject(products, Formatting.Indented);
  1590. //[
  1591. // {
  1592. // "Name": "Product 1",
  1593. // "ExpiryDate": "\/Date(978048000000)\/",
  1594. // "Price": 99.95,
  1595. // "Sizes": null
  1596. // },
  1597. // {
  1598. // "Name": "Product 2",
  1599. // "ExpiryDate": "\/Date(1248998400000)\/",
  1600. // "Price": 12.50,
  1601. // "Sizes": null
  1602. // }
  1603. //]
  1604. Assert.AreEqual(@"[
  1605. {
  1606. ""Name"": ""Product 1"",
  1607. ""ExpiryDate"": ""2000-12-29T00:00:00Z"",
  1608. ""Price"": 99.95,
  1609. ""Sizes"": null
  1610. },
  1611. {
  1612. ""Name"": ""Product 2"",
  1613. ""ExpiryDate"": ""2009-07-31T00:00:00Z"",
  1614. ""Price"": 12.50,
  1615. ""Sizes"": null
  1616. }
  1617. ]", json);
  1618. }
  1619. [Test]
  1620. public void DeserializeGenericList()
  1621. {
  1622. string json = @"[
  1623. {
  1624. ""Name"": ""Product 1"",
  1625. ""ExpiryDate"": ""\/Date(978048000000)\/"",
  1626. ""Price"": 99.95,
  1627. ""Sizes"": null
  1628. },
  1629. {
  1630. ""Name"": ""Product 2"",
  1631. ""ExpiryDate"": ""\/Date(1248998400000)\/"",
  1632. ""Price"": 12.50,
  1633. ""Sizes"": null
  1634. }
  1635. ]";
  1636. List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);
  1637. Console.WriteLine(products.Count);
  1638. // 2
  1639. Product p1 = products[0];
  1640. Console.WriteLine(p1.Name);
  1641. // Product 1
  1642. Assert.AreEqual(2, products.Count);
  1643. Assert.AreEqual("Product 1", products[0].Name);
  1644. }
  1645. #if !NET20
  1646. [Test]
  1647. public void DeserializeEmptyStringToNullableDateTime()
  1648. {
  1649. string json = @"{""DateTimeField"":""""}";
  1650. NullableDateTimeTestClass c = JsonConvert.DeserializeObject<NullableDateTimeTestClass>(json);
  1651. Assert.AreEqual(null, c.DateTimeField);
  1652. }
  1653. #endif
  1654. [Test]
  1655. public void FailWhenClassWithNoDefaultConstructorHasMultipleConstructorsWithArguments()
  1656. {
  1657. 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)\/""}";
  1658. ExceptionAssert.Throws<JsonSerializationException>(
  1659. @"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Event. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'sublocation', line 1, position 15.",
  1660. () =>
  1661. {
  1662. JsonConvert.DeserializeObject<TestObjects.Event>(json);
  1663. });
  1664. }
  1665. [Test]
  1666. public void DeserializeObjectSetOnlyProperty()
  1667. {
  1668. string json = @"{'SetOnlyProperty':[1,2,3,4,5]}";
  1669. SetOnlyPropertyClass2 setOnly = JsonConvert.DeserializeObject<SetOnlyPropertyClass2>(json);
  1670. JArray a = (JArray)setOnly.GetValue();
  1671. Assert.AreEqual(5, a.Count);
  1672. Assert.AreEqual(1, (int)a[0]);
  1673. Assert.AreEqual(5, (int)a[a.Count - 1]);
  1674. }
  1675. [Test]
  1676. public void DeserializeOptInClasses()
  1677. {
  1678. string json = @"{id: ""12"", name: ""test"", items: [{id: ""112"", name: ""testing""}]}";
  1679. ListTestClass l = JsonConvert.DeserializeObject<ListTestClass>(json);
  1680. }
  1681. [Test]
  1682. public void DeserializeNullableListWithNulls()
  1683. {
  1684. List<decimal?> l = JsonConvert.DeserializeObject<List<decimal?>>("[ 3.3, null, 1.1 ] ");
  1685. Assert.AreEqual(3, l.Count);
  1686. Assert.AreEqual(3.3m, l[0]);
  1687. Assert.AreEqual(null, l[1]);
  1688. Assert.AreEqual(1.1m, l[2]);
  1689. }
  1690. [Test]
  1691. public void CannotDeserializeArrayIntoObject()
  1692. {
  1693. string json = @"[]";
  1694. ExceptionAssert.Throws<JsonSerializationException>(
  1695. @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Newtonsoft.Json.Tests.TestObjects.Person' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
  1696. To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
  1697. Path '', line 1, position 1.",
  1698. () =>
  1699. {
  1700. JsonConvert.DeserializeObject<Person>(json);
  1701. });
  1702. }
  1703. [Test]
  1704. public void CannotDeserializeArrayIntoDictionary()
  1705. {
  1706. string json = @"[]";
  1707. ExceptionAssert.Throws<JsonSerializationException>(
  1708. @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
  1709. To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
  1710. Path '', line 1, position 1.",
  1711. () =>
  1712. {
  1713. JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  1714. });
  1715. }
  1716. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  1717. [Test]
  1718. public void CannotDeserializeArrayIntoSerializable()
  1719. {
  1720. string json = @"[]";
  1721. ExceptionAssert.Throws<JsonSerializationException>(
  1722. @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Exception' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
  1723. To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
  1724. Path '', line 1, position 1.",
  1725. () =>
  1726. {
  1727. JsonConvert.DeserializeObject<Exception>(json);
  1728. });
  1729. }
  1730. #endif
  1731. [Test]
  1732. public void CannotDeserializeArrayIntoDouble()
  1733. {
  1734. string json = @"[]";
  1735. ExceptionAssert.Throws<JsonSerializationException>(
  1736. @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Double' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly.
  1737. To fix this error either change the JSON to a JSON primitive value (e.g. string, number, boolean, null) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
  1738. Path '', line 1, position 1.",
  1739. () =>
  1740. {
  1741. JsonConvert.DeserializeObject<double>(json);
  1742. });
  1743. }
  1744. #if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
  1745. [Test]
  1746. public void CannotDeserializeArrayIntoDynamic()
  1747. {
  1748. string json = @"[]";
  1749. ExceptionAssert.Throws<JsonSerializationException>(
  1750. @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Newtonsoft.Json.Tests.Linq.DynamicDictionary' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
  1751. To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
  1752. Path '', line 1, position 1.",
  1753. () =>
  1754. {
  1755. JsonConvert.DeserializeObject<DynamicDictionary>(json);
  1756. });
  1757. }
  1758. #endif
  1759. [Test]
  1760. public void CannotDeserializeArrayIntoLinqToJson()
  1761. {
  1762. string json = @"[]";
  1763. ExceptionAssert.Throws<InvalidCastException>(
  1764. @"Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.",
  1765. () =>
  1766. {
  1767. JsonConvert.DeserializeObject<JObject>(json);
  1768. });
  1769. }
  1770. [Test]
  1771. public void CannotDeserializeConstructorIntoObject()
  1772. {
  1773. string json = @"new Constructor(123)";
  1774. ExceptionAssert.Throws<JsonSerializationException>(
  1775. @"Error converting value ""Constructor"" to type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '', line 1, position 16.",
  1776. () =>
  1777. {
  1778. JsonConvert.DeserializeObject<Person>(json);
  1779. });
  1780. }
  1781. [Test]
  1782. public void CannotDeserializeConstructorIntoObjectNested()
  1783. {
  1784. string json = @"[new Constructor(123)]";
  1785. ExceptionAssert.Throws<JsonSerializationException>(
  1786. @"Error converting value ""Constructor"" to type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '[0]', line 1, position 17.",
  1787. () =>
  1788. {
  1789. JsonConvert.DeserializeObject<List<Person>>(json);
  1790. });
  1791. }
  1792. [Test]
  1793. public void CannotDeserializeObjectIntoArray()
  1794. {
  1795. string json = @"{}";
  1796. ExceptionAssert.Throws<JsonSerializationException>(
  1797. @"Cannot deserialize the current JSON object (e.g. {""name"":""value""}) into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
  1798. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
  1799. Path '', line 1, position 2.",
  1800. () =>
  1801. {
  1802. JsonConvert.DeserializeObject<List<Person>>(json);
  1803. });
  1804. }
  1805. [Test]
  1806. public void CannotPopulateArrayIntoObject()
  1807. {
  1808. string json = @"[]";
  1809. ExceptionAssert.Throws<JsonSerializationException>(
  1810. @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '', line 1, position 1.",
  1811. () =>
  1812. {
  1813. JsonConvert.PopulateObject(json, new Person());
  1814. });
  1815. }
  1816. [Test]
  1817. public void CannotPopulateObjectIntoArray()
  1818. {
  1819. string json = @"{}";
  1820. ExceptionAssert.Throws<JsonSerializationException>(
  1821. @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Path '', line 1, position 2.",
  1822. () =>
  1823. {
  1824. JsonConvert.PopulateObject(json, new List<Person>());
  1825. });
  1826. }
  1827. [Test]
  1828. public void DeserializeEmptyString()
  1829. {
  1830. string json = @"{""Name"":""""}";
  1831. Person p = JsonConvert.DeserializeObject<Person>(json);
  1832. Assert.AreEqual("", p.Name);
  1833. }
  1834. [Test]
  1835. public void SerializePropertyGetError()
  1836. {
  1837. ExceptionAssert.Throws<JsonSerializationException>(
  1838. @"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.",
  1839. () =>
  1840. {
  1841. JsonConvert.SerializeObject(new MemoryStream(), new JsonSerializerSettings
  1842. {
  1843. ContractResolver = new DefaultContractResolver
  1844. {
  1845. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  1846. IgnoreSerializableAttribute = true
  1847. #endif
  1848. }
  1849. });
  1850. });
  1851. }
  1852. [Test]
  1853. public void DeserializePropertySetError()
  1854. {
  1855. ExceptionAssert.Throws<JsonSerializationException>(
  1856. @"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'.",
  1857. () =>
  1858. {
  1859. JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:0}", new JsonSerializerSettings
  1860. {
  1861. ContractResolver = new DefaultContractResolver
  1862. {
  1863. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  1864. IgnoreSerializableAttribute = true
  1865. #endif
  1866. }
  1867. });
  1868. });
  1869. }
  1870. [Test]
  1871. public void DeserializeEnsureTypeEmptyStringToIntError()
  1872. {
  1873. ExceptionAssert.Throws<JsonSerializationException>(
  1874. @"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 15.",
  1875. () =>
  1876. {
  1877. JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}", new JsonSerializerSettings
  1878. {
  1879. ContractResolver = new DefaultContractResolver
  1880. {
  1881. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  1882. IgnoreSerializableAttribute = true
  1883. #endif
  1884. }
  1885. });
  1886. });
  1887. }
  1888. [Test]
  1889. public void DeserializeEnsureTypeNullToIntError()
  1890. {
  1891. ExceptionAssert.Throws<JsonSerializationException>(
  1892. @"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 17.",
  1893. () =>
  1894. {
  1895. JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}", new JsonSerializerSettings
  1896. {
  1897. ContractResolver = new DefaultContractResolver
  1898. {
  1899. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  1900. IgnoreSerializableAttribute = true
  1901. #endif
  1902. }
  1903. });
  1904. });
  1905. }
  1906. [Test]
  1907. public void SerializeGenericListOfStrings()
  1908. {
  1909. List<String> strings = new List<String>();
  1910. strings.Add("str_1");
  1911. strings.Add("str_2");
  1912. strings.Add("str_3");
  1913. string json = JsonConvert.SerializeObject(strings);
  1914. Assert.AreEqual(@"[""str_1"",""str_2"",""str_3""]", json);
  1915. }
  1916. [Test]
  1917. public void ConstructorReadonlyFieldsTest()
  1918. {
  1919. ConstructorReadonlyFields c1 = new ConstructorReadonlyFields("String!", int.MaxValue);
  1920. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  1921. Assert.AreEqual(@"{
  1922. ""A"": ""String!"",
  1923. ""B"": 2147483647
  1924. }", json);
  1925. ConstructorReadonlyFields c2 = JsonConvert.DeserializeObject<ConstructorReadonlyFields>(json);
  1926. Assert.AreEqual("String!", c2.A);
  1927. Assert.AreEqual(int.MaxValue, c2.B);
  1928. }
  1929. [Test]
  1930. public void SerializeStruct()
  1931. {
  1932. StructTest structTest = new StructTest
  1933. {
  1934. StringProperty = "StringProperty!",
  1935. StringField = "StringField",
  1936. IntProperty = 5,
  1937. IntField = 10
  1938. };
  1939. string json = JsonConvert.SerializeObject(structTest, Formatting.Indented);
  1940. Console.WriteLine(json);
  1941. Assert.AreEqual(@"{
  1942. ""StringField"": ""StringField"",
  1943. ""IntField"": 10,
  1944. ""StringProperty"": ""StringProperty!"",
  1945. ""IntProperty"": 5
  1946. }", json);
  1947. StructTest deserialized = JsonConvert.DeserializeObject<StructTest>(json);
  1948. Assert.AreEqual(structTest.StringProperty, deserialized.StringProperty);
  1949. Assert.AreEqual(structTest.StringField, deserialized.StringField);
  1950. Assert.AreEqual(structTest.IntProperty, deserialized.IntProperty);
  1951. Assert.AreEqual(structTest.IntField, deserialized.IntField);
  1952. }
  1953. [Test]
  1954. public void SerializeListWithJsonConverter()
  1955. {
  1956. Foo f = new Foo();
  1957. f.Bars.Add(new Bar { Id = 0 });
  1958. f.Bars.Add(new Bar { Id = 1 });
  1959. f.Bars.Add(new Bar { Id = 2 });
  1960. string json = JsonConvert.SerializeObject(f, Formatting.Indented);
  1961. Assert.AreEqual(@"{
  1962. ""Bars"": [
  1963. 0,
  1964. 1,
  1965. 2
  1966. ]
  1967. }", json);
  1968. Foo newFoo = JsonConvert.DeserializeObject<Foo>(json);
  1969. Assert.AreEqual(3, newFoo.Bars.Count);
  1970. Assert.AreEqual(0, newFoo.Bars[0].Id);
  1971. Assert.AreEqual(1, newFoo.Bars[1].Id);
  1972. Assert.AreEqual(2, newFoo.Bars[2].Id);
  1973. }
  1974. [Test]
  1975. public void SerializeGuidKeyedDictionary()
  1976. {
  1977. Dictionary<Guid, int> dictionary = new Dictionary<Guid, int>();
  1978. dictionary.Add(new Guid("F60EAEE0-AE47-488E-B330-59527B742D77"), 1);
  1979. dictionary.Add(new Guid("C2594C02-EBA1-426A-AA87-8DD8871350B0"), 2);
  1980. string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
  1981. Assert.AreEqual(@"{
  1982. ""f60eaee0-ae47-488e-b330-59527b742d77"": 1,
  1983. ""c2594c02-eba1-426a-aa87-8dd8871350b0"": 2
  1984. }", json);
  1985. }
  1986. [Test]
  1987. public void SerializePersonKeyedDictionary()
  1988. {
  1989. Dictionary<Person, int> dictionary = new Dictionary<Person, int>();
  1990. dictionary.Add(new Person { Name = "p1" }, 1);
  1991. dictionary.Add(new Person { Name = "p2" }, 2);
  1992. string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
  1993. Assert.AreEqual(@"{
  1994. ""Newtonsoft.Json.Tests.TestObjects.Person"": 1,
  1995. ""Newtonsoft.Json.Tests.TestObjects.Person"": 2
  1996. }", json);
  1997. }
  1998. [Test]
  1999. public void DeserializePersonKeyedDictionary()
  2000. {
  2001. ExceptionAssert.Throws<JsonSerializationException>("Could not convert string 'Newtonsoft.Json.Tests.TestObjects.Person' to dictionary key type 'Newtonsoft.Json.Tests.TestObjects.Person'. Create a TypeConverter to convert from the string to the key type object. Path 'Newtonsoft.Json.Tests.TestObjects.Person', line 2, position 46.",
  2002. () =>
  2003. {
  2004. string json =
  2005. @"{
  2006. ""Newtonsoft.Json.Tests.TestObjects.Person"": 1,
  2007. ""Newtonsoft.Json.Tests.TestObjects.Person"": 2
  2008. }";
  2009. JsonConvert.DeserializeObject<Dictionary<Person, int>>(json);
  2010. });
  2011. }
  2012. [Test]
  2013. public void SerializeFragment()
  2014. {
  2015. string googleSearchText = @"{
  2016. ""responseData"": {
  2017. ""results"": [
  2018. {
  2019. ""GsearchResultClass"": ""GwebSearch"",
  2020. ""unescapedUrl"": ""http://en.wikipedia.org/wiki/Paris_Hilton"",
  2021. ""url"": ""http://en.wikipedia.org/wiki/Paris_Hilton"",
  2022. ""visibleUrl"": ""en.wikipedia.org"",
  2023. ""cacheUrl"": ""http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org"",
  2024. ""title"": ""<b>Paris Hilton</b> - Wikipedia, the free encyclopedia"",
  2025. ""titleNoFormatting"": ""Paris Hilton - Wikipedia, the free encyclopedia"",
  2026. ""content"": ""[1] In 2006, she released her debut album...""
  2027. },
  2028. {
  2029. ""GsearchResultClass"": ""GwebSearch"",
  2030. ""unescapedUrl"": ""http://www.imdb.com/name/nm0385296/"",
  2031. ""url"": ""http://www.imdb.com/name/nm0385296/"",
  2032. ""visibleUrl"": ""www.imdb.com"",
  2033. ""cacheUrl"": ""http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com"",
  2034. ""title"": ""<b>Paris Hilton</b>"",
  2035. ""titleNoFormatting"": ""Paris Hilton"",
  2036. ""content"": ""Self: Zoolander. Socialite <b>Paris Hilton</b>...""
  2037. }
  2038. ],
  2039. ""cursor"": {
  2040. ""pages"": [
  2041. {
  2042. ""start"": ""0"",
  2043. ""label"": 1
  2044. },
  2045. {
  2046. ""start"": ""4"",
  2047. ""label"": 2
  2048. },
  2049. {
  2050. ""start"": ""8"",
  2051. ""label"": 3
  2052. },
  2053. {
  2054. ""start"": ""12"",
  2055. ""label"": 4
  2056. }
  2057. ],
  2058. ""estimatedResultCount"": ""59600000"",
  2059. ""currentPageIndex"": 0,
  2060. ""moreResultsUrl"": ""http://www.google.com/search?oe=utf8&ie=utf8...""
  2061. }
  2062. },
  2063. ""responseDetails"": null,
  2064. ""responseStatus"": 200
  2065. }";
  2066. JObject googleSearch = JObject.Parse(googleSearchText);
  2067. // get JSON result objects into a list
  2068. IList<JToken> results = googleSearch["responseData"]["results"].Children().ToList();
  2069. // serialize JSON results into .NET objects
  2070. IList<SearchResult> searchResults = new List<SearchResult>();
  2071. foreach (JToken result in results)
  2072. {
  2073. SearchResult searchResult = JsonConvert.DeserializeObject<SearchResult>(result.ToString());
  2074. searchResults.Add(searchResult);
  2075. }
  2076. // Title = <b>Paris Hilton</b> - Wikipedia, the free encyclopedia
  2077. // Content = [1] In 2006, she released her debut album...
  2078. // Url = http://en.wikipedia.org/wiki/Paris_Hilton
  2079. // Title = <b>Paris Hilton</b>
  2080. // Content = Self: Zoolander. Socialite <b>Paris Hilton</b>...
  2081. // Url = http://www.imdb.com/name/nm0385296/
  2082. Assert.AreEqual(2, searchResults.Count);
  2083. Assert.AreEqual("<b>Paris Hilton</b> - Wikipedia, the free encyclopedia", searchResults[0].Title);
  2084. Assert.AreEqual("<b>Paris Hilton</b>", searchResults[1].Title);
  2085. }
  2086. [Test]
  2087. public void DeserializeBaseReferenceWithDerivedValue()
  2088. {
  2089. PersonPropertyClass personPropertyClass = new PersonPropertyClass();
  2090. WagePerson wagePerson = (WagePerson)personPropertyClass.Person;
  2091. wagePerson.BirthDate = new DateTime(2000, 11, 29, 23, 59, 59, DateTimeKind.Utc);
  2092. wagePerson.Department = "McDees";
  2093. wagePerson.HourlyWage = 12.50m;
  2094. wagePerson.LastModified = new DateTime(2000, 11, 29, 23, 59, 59, DateTimeKind.Utc);
  2095. wagePerson.Name = "Jim Bob";
  2096. string json = JsonConvert.SerializeObject(personPropertyClass, Formatting.Indented);
  2097. Assert.AreEqual(
  2098. @"{
  2099. ""Person"": {
  2100. ""HourlyWage"": 12.50,
  2101. ""Name"": ""Jim Bob"",
  2102. ""BirthDate"": ""2000-11-29T23:59:59Z"",
  2103. ""LastModified"": ""2000-11-29T23:59:59Z""
  2104. }
  2105. }",
  2106. json);
  2107. PersonPropertyClass newPersonPropertyClass = JsonConvert.DeserializeObject<PersonPropertyClass>(json);
  2108. Assert.AreEqual(wagePerson.HourlyWage, ((WagePerson)newPersonPropertyClass.Person).HourlyWage);
  2109. }
  2110. public class ExistingValueClass
  2111. {
  2112. public Dictionary<string, string> Dictionary { get; set; }
  2113. public List<string> List { get; set; }
  2114. public ExistingValueClass()
  2115. {
  2116. Dictionary = new Dictionary<string, string>
  2117. {
  2118. {"existing", "yup"}
  2119. };
  2120. List = new List<string>
  2121. {
  2122. "existing"
  2123. };
  2124. }
  2125. }
  2126. [Test]
  2127. public void DeserializePopulateDictionaryAndList()
  2128. {
  2129. ExistingValueClass d = JsonConvert.DeserializeObject<ExistingValueClass>(@"{'Dictionary':{appended:'appended',existing:'new'}}");
  2130. Assert.IsNotNull(d);
  2131. Assert.IsNotNull(d.Dictionary);
  2132. Assert.AreEqual(typeof(Dictionary<string, string>), d.Dictionary.GetType());
  2133. Assert.AreEqual(typeof(List<string>), d.List.GetType());
  2134. Assert.AreEqual(2, d.Dictionary.Count);
  2135. Assert.AreEqual("new", d.Dictionary["existing"]);
  2136. Assert.AreEqual("appended", d.Dictionary["appended"]);
  2137. Assert.AreEqual(1, d.List.Count);
  2138. Assert.AreEqual("existing", d.List[0]);
  2139. }
  2140. public interface IKeyValueId
  2141. {
  2142. int Id { get; set; }
  2143. string Key { get; set; }
  2144. string Value { get; set; }
  2145. }
  2146. public class KeyValueId : IKeyValueId
  2147. {
  2148. public int Id { get; set; }
  2149. public string Key { get; set; }
  2150. public string Value { get; set; }
  2151. }
  2152. public class ThisGenericTest<T> where T : IKeyValueId
  2153. {
  2154. private Dictionary<string, T> _dict1 = new Dictionary<string, T>();
  2155. public string MyProperty { get; set; }
  2156. public void Add(T item)
  2157. {
  2158. this._dict1.Add(item.Key, item);
  2159. }
  2160. public T this[string key]
  2161. {
  2162. get { return this._dict1[key]; }
  2163. set { this._dict1[key] = value; }
  2164. }
  2165. public T this[int id]
  2166. {
  2167. get { return this._dict1.Values.FirstOrDefault(x => x.Id == id); }
  2168. set
  2169. {
  2170. var item = this[id];
  2171. if (item == null)
  2172. this.Add(value);
  2173. else
  2174. this._dict1[item.Key] = value;
  2175. }
  2176. }
  2177. public string ToJson()
  2178. {
  2179. return JsonConvert.SerializeObject(this, Formatting.Indented);
  2180. }
  2181. public T[] TheItems
  2182. {
  2183. get { return this._dict1.Values.ToArray<T>(); }
  2184. set
  2185. {
  2186. foreach (var item in value)
  2187. this.Add(item);
  2188. }
  2189. }
  2190. }
  2191. [Test]
  2192. public void IgnoreIndexedProperties()
  2193. {
  2194. ThisGenericTest<KeyValueId> g = new ThisGenericTest<KeyValueId>();
  2195. g.Add(new KeyValueId { Id = 1, Key = "key1", Value = "value1" });
  2196. g.Add(new KeyValueId { Id = 2, Key = "key2", Value = "value2" });
  2197. g.MyProperty = "some value";
  2198. string json = g.ToJson();
  2199. Assert.AreEqual(@"{
  2200. ""MyProperty"": ""some value"",
  2201. ""TheItems"": [
  2202. {
  2203. ""Id"": 1,
  2204. ""Key"": ""key1"",
  2205. ""Value"": ""value1""
  2206. },
  2207. {
  2208. ""Id"": 2,
  2209. ""Key"": ""key2"",
  2210. ""Value"": ""value2""
  2211. }
  2212. ]
  2213. }", json);
  2214. ThisGenericTest<KeyValueId> gen = JsonConvert.DeserializeObject<ThisGenericTest<KeyValueId>>(json);
  2215. Assert.AreEqual("some value", gen.MyProperty);
  2216. }
  2217. public class JRawValueTestObject
  2218. {
  2219. public JRaw Value { get; set; }
  2220. }
  2221. [Test]
  2222. public void JRawValue()
  2223. {
  2224. JRawValueTestObject deserialized = JsonConvert.DeserializeObject<JRawValueTestObject>("{value:3}");
  2225. Assert.AreEqual("3", deserialized.Value.ToString());
  2226. deserialized = JsonConvert.DeserializeObject<JRawValueTestObject>("{value:'3'}");
  2227. Assert.AreEqual(@"""3""", deserialized.Value.ToString());
  2228. }
  2229. [Test]
  2230. public void DeserializeDictionaryWithNoDefaultConstructor()
  2231. {
  2232. string json = "{key1:'value',key2:'value',key3:'value'}";
  2233. ExceptionAssert.Throws<JsonSerializationException>(
  2234. "Unable to find a default constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Path 'key1', line 1, position 6.",
  2235. () =>
  2236. {
  2237. JsonConvert.DeserializeObject<DictionaryWithNoDefaultConstructor>(json);
  2238. });
  2239. }
  2240. public class DictionaryWithNoDefaultConstructor : Dictionary<string, string>
  2241. {
  2242. public DictionaryWithNoDefaultConstructor(IEnumerable<KeyValuePair<string, string>> initial)
  2243. {
  2244. foreach (KeyValuePair<string, string> pair in initial)
  2245. {
  2246. Add(pair.Key, pair.Value);
  2247. }
  2248. }
  2249. }
  2250. [JsonObject(MemberSerialization.OptIn)]
  2251. public class A
  2252. {
  2253. [JsonProperty("A1")]
  2254. private string _A1;
  2255. public string A1
  2256. {
  2257. get { return _A1; }
  2258. set { _A1 = value; }
  2259. }
  2260. [JsonProperty("A2")]
  2261. private string A2 { get; set; }
  2262. }
  2263. [JsonObject(MemberSerialization.OptIn)]
  2264. public class B : A
  2265. {
  2266. public string B1 { get; set; }
  2267. [JsonProperty("B2")]
  2268. private string _B2;
  2269. public string B2
  2270. {
  2271. get { return _B2; }
  2272. set { _B2 = value; }
  2273. }
  2274. [JsonProperty("B3")]
  2275. private string B3 { get; set; }
  2276. }
  2277. [Test]
  2278. public void SerializeNonPublicBaseJsonProperties()
  2279. {
  2280. B value = new B();
  2281. string json = JsonConvert.SerializeObject(value, Formatting.Indented);
  2282. Assert.AreEqual(@"{
  2283. ""B2"": null,
  2284. ""A1"": null,
  2285. ""B3"": null,
  2286. ""A2"": null
  2287. }", json);
  2288. }
  2289. public class TestClass
  2290. {
  2291. public string Key { get; set; }
  2292. public object Value { get; set; }
  2293. }
  2294. [Test]
  2295. public void DeserializeToObjectProperty()
  2296. {
  2297. var json = "{ Key: 'abc', Value: 123 }";
  2298. var item = JsonConvert.DeserializeObject<TestClass>(json);
  2299. Assert.AreEqual(123L, item.Value);
  2300. }
  2301. public abstract class Animal
  2302. {
  2303. public abstract string Name { get; }
  2304. }
  2305. public class Human : Animal
  2306. {
  2307. public override string Name
  2308. {
  2309. get { return typeof(Human).Name; }
  2310. }
  2311. public string Ethnicity { get; set; }
  2312. }
  2313. #if !NET20 && !WINDOWS_PHONE
  2314. public class DataContractJsonSerializerTestClass
  2315. {
  2316. public TimeSpan TimeSpanProperty { get; set; }
  2317. public Guid GuidProperty { get; set; }
  2318. public Animal AnimalProperty { get; set; }
  2319. public Exception ExceptionProperty { get; set; }
  2320. }
  2321. [Test]
  2322. public void DataContractJsonSerializerTest()
  2323. {
  2324. Exception ex = new Exception("Blah blah blah");
  2325. DataContractJsonSerializerTestClass c = new DataContractJsonSerializerTestClass();
  2326. c.TimeSpanProperty = new TimeSpan(200, 20, 59, 30, 900);
  2327. c.GuidProperty = new Guid("66143115-BE2A-4a59-AF0A-348E1EA15B1E");
  2328. c.AnimalProperty = new Human() { Ethnicity = "European" };
  2329. c.ExceptionProperty = ex;
  2330. MemoryStream ms = new MemoryStream();
  2331. DataContractJsonSerializer serializer = new DataContractJsonSerializer(
  2332. typeof(DataContractJsonSerializerTestClass),
  2333. new Type[] { typeof(Human) });
  2334. serializer.WriteObject(ms, c);
  2335. byte[] jsonBytes = ms.ToArray();
  2336. string json = Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length);
  2337. //Console.WriteLine(JObject.Parse(json).ToString());
  2338. //Console.WriteLine();
  2339. //Console.WriteLine(JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings
  2340. // {
  2341. // // TypeNameHandling = TypeNameHandling.Objects
  2342. // }));
  2343. }
  2344. #endif
  2345. public class ModelStateDictionary<T> : IDictionary<string, T>
  2346. {
  2347. private readonly Dictionary<string, T> _innerDictionary = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
  2348. public ModelStateDictionary()
  2349. {
  2350. }
  2351. public ModelStateDictionary(ModelStateDictionary<T> dictionary)
  2352. {
  2353. if (dictionary == null)
  2354. {
  2355. throw new ArgumentNullException("dictionary");
  2356. }
  2357. foreach (var entry in dictionary)
  2358. {
  2359. _innerDictionary.Add(entry.Key, entry.Value);
  2360. }
  2361. }
  2362. public int Count
  2363. {
  2364. get { return _innerDictionary.Count; }
  2365. }
  2366. public bool IsReadOnly
  2367. {
  2368. get { return ((IDictionary<string, T>)_innerDictionary).IsReadOnly; }
  2369. }
  2370. public ICollection<string> Keys
  2371. {
  2372. get { return _innerDictionary.Keys; }
  2373. }
  2374. public T this[string key]
  2375. {
  2376. get
  2377. {
  2378. T value;
  2379. _innerDictionary.TryGetValue(key, out value);
  2380. return value;
  2381. }
  2382. set { _innerDictionary[key] = value; }
  2383. }
  2384. public ICollection<T> Values
  2385. {
  2386. get { return _innerDictionary.Values; }
  2387. }
  2388. public void Add(KeyValuePair<string, T> item)
  2389. {
  2390. ((IDictionary<string, T>)_innerDictionary).Add(item);
  2391. }
  2392. public void Add(string key, T value)
  2393. {
  2394. _innerDictionary.Add(key, value);
  2395. }
  2396. public void Clear()
  2397. {
  2398. _innerDictionary.Clear();
  2399. }
  2400. public bool Contains(KeyValuePair<string, T> item)
  2401. {
  2402. return ((IDictionary<string, T>)_innerDictionary).Contains(item);
  2403. }
  2404. public bool ContainsKey(string key)
  2405. {
  2406. return _innerDictionary.ContainsKey(key);
  2407. }
  2408. public void CopyTo(KeyValuePair<string, T>[] array, int arrayIndex)
  2409. {
  2410. ((IDictionary<string, T>)_innerDictionary).CopyTo(array, arrayIndex);
  2411. }
  2412. public IEnumerator<KeyValuePair<string, T>> GetEnumerator()
  2413. {
  2414. return _innerDictionary.GetEnumerator();
  2415. }
  2416. public void Merge(ModelStateDictionary<T> dictionary)
  2417. {
  2418. if (dictionary == null)
  2419. {
  2420. return;
  2421. }
  2422. foreach (var entry in dictionary)
  2423. {
  2424. this[entry.Key] = entry.Value;
  2425. }
  2426. }
  2427. public bool Remove(KeyValuePair<string, T> item)
  2428. {
  2429. return ((IDictionary<string, T>)_innerDictionary).Remove(item);
  2430. }
  2431. public bool Remove(string key)
  2432. {
  2433. return _innerDictionary.Remove(key);
  2434. }
  2435. public bool TryGetValue(string key, out T value)
  2436. {
  2437. return _innerDictionary.TryGetValue(key, out value);
  2438. }
  2439. IEnumerator IEnumerable.GetEnumerator()
  2440. {
  2441. return ((IEnumerable)_innerDictionary).GetEnumerator();
  2442. }
  2443. }
  2444. [Test]
  2445. public void SerializeNonIDictionary()
  2446. {
  2447. ModelStateDictionary<string> modelStateDictionary = new ModelStateDictionary<string>();
  2448. modelStateDictionary.Add("key", "value");
  2449. string json = JsonConvert.SerializeObject(modelStateDictionary);
  2450. Assert.AreEqual(@"{""key"":""value""}", json);
  2451. ModelStateDictionary<string> newModelStateDictionary = JsonConvert.DeserializeObject<ModelStateDictionary<string>>(json);
  2452. Assert.AreEqual(1, newModelStateDictionary.Count);
  2453. Assert.AreEqual("value", newModelStateDictionary["key"]);
  2454. }
  2455. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  2456. public class ISerializableTestObject : ISerializable
  2457. {
  2458. internal string _stringValue;
  2459. internal int _intValue;
  2460. internal DateTimeOffset _dateTimeOffsetValue;
  2461. internal Person _personValue;
  2462. internal Person _nullPersonValue;
  2463. internal int? _nullableInt;
  2464. internal bool _booleanValue;
  2465. internal byte _byteValue;
  2466. internal char _charValue;
  2467. internal DateTime _dateTimeValue;
  2468. internal decimal _decimalValue;
  2469. internal short _shortValue;
  2470. internal long _longValue;
  2471. internal sbyte _sbyteValue;
  2472. internal float _floatValue;
  2473. internal ushort _ushortValue;
  2474. internal uint _uintValue;
  2475. internal ulong _ulongValue;
  2476. public ISerializableTestObject(string stringValue, int intValue, DateTimeOffset dateTimeOffset, Person personValue)
  2477. {
  2478. _stringValue = stringValue;
  2479. _intValue = intValue;
  2480. _dateTimeOffsetValue = dateTimeOffset;
  2481. _personValue = personValue;
  2482. _dateTimeValue = new DateTime(0, DateTimeKind.Utc);
  2483. }
  2484. protected ISerializableTestObject(SerializationInfo info, StreamingContext context)
  2485. {
  2486. _stringValue = info.GetString("stringValue");
  2487. _intValue = info.GetInt32("intValue");
  2488. _dateTimeOffsetValue = (DateTimeOffset)info.GetValue("dateTimeOffsetValue", typeof(DateTimeOffset));
  2489. _personValue = (Person)info.GetValue("personValue", typeof(Person));
  2490. _nullPersonValue = (Person)info.GetValue("nullPersonValue", typeof(Person));
  2491. _nullableInt = (int?)info.GetValue("nullableInt", typeof(int?));
  2492. _booleanValue = info.GetBoolean("booleanValue");
  2493. _byteValue = info.GetByte("byteValue");
  2494. _charValue = info.GetChar("charValue");
  2495. _dateTimeValue = info.GetDateTime("dateTimeValue");
  2496. _decimalValue = info.GetDecimal("decimalValue");
  2497. _shortValue = info.GetInt16("shortValue");
  2498. _longValue = info.GetInt64("longValue");
  2499. _sbyteValue = info.GetSByte("sbyteValue");
  2500. _floatValue = info.GetSingle("floatValue");
  2501. _ushortValue = info.GetUInt16("ushortValue");
  2502. _uintValue = info.GetUInt32("uintValue");
  2503. _ulongValue = info.GetUInt64("ulongValue");
  2504. }
  2505. public void GetObjectData(SerializationInfo info, StreamingContext context)
  2506. {
  2507. info.AddValue("stringValue", _stringValue);
  2508. info.AddValue("intValue", _intValue);
  2509. info.AddValue("dateTimeOffsetValue", _dateTimeOffsetValue);
  2510. info.AddValue("personValue", _personValue);
  2511. info.AddValue("nullPersonValue", _nullPersonValue);
  2512. info.AddValue("nullableInt", null);
  2513. info.AddValue("booleanValue", _booleanValue);
  2514. info.AddValue("byteValue", _byteValue);
  2515. info.AddValue("charValue", _charValue);
  2516. info.AddValue("dateTimeValue", _dateTimeValue);
  2517. info.AddValue("decimalValue", _decimalValue);
  2518. info.AddValue("shortValue", _shortValue);
  2519. info.AddValue("longValue", _longValue);
  2520. info.AddValue("sbyteValue", _sbyteValue);
  2521. info.AddValue("floatValue", _floatValue);
  2522. info.AddValue("ushortValue", _ushortValue);
  2523. info.AddValue("uintValue", _uintValue);
  2524. info.AddValue("ulongValue", _ulongValue);
  2525. }
  2526. }
  2527. #if DEBUG
  2528. [Test]
  2529. public void SerializeISerializableInPartialTrustWithIgnoreInterface()
  2530. {
  2531. try
  2532. {
  2533. JsonTypeReflector.SetFullyTrusted(false);
  2534. ISerializableTestObject value = new ISerializableTestObject("string!", 0, default(DateTimeOffset), null);
  2535. string json = JsonConvert.SerializeObject(value, new JsonSerializerSettings
  2536. {
  2537. ContractResolver = new DefaultContractResolver(false)
  2538. {
  2539. IgnoreSerializableInterface = true
  2540. }
  2541. });
  2542. Assert.AreEqual("{}", json);
  2543. value = JsonConvert.DeserializeObject<ISerializableTestObject>("{booleanValue:true}", new JsonSerializerSettings
  2544. {
  2545. ContractResolver = new DefaultContractResolver(false)
  2546. {
  2547. IgnoreSerializableInterface = true
  2548. }
  2549. });
  2550. Assert.IsNotNull(value);
  2551. Assert.AreEqual(false, value._booleanValue);
  2552. }
  2553. finally
  2554. {
  2555. JsonTypeReflector.SetFullyTrusted(true);
  2556. }
  2557. }
  2558. [Test]
  2559. public void SerializeISerializableInPartialTrust()
  2560. {
  2561. try
  2562. {
  2563. ExceptionAssert.Throws<JsonSerializationException>(
  2564. @"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.
  2565. To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.
  2566. Path 'booleanValue', line 1, position 14.",
  2567. () =>
  2568. {
  2569. JsonTypeReflector.SetFullyTrusted(false);
  2570. JsonConvert.DeserializeObject<ISerializableTestObject>("{booleanValue:true}");
  2571. });
  2572. }
  2573. finally
  2574. {
  2575. JsonTypeReflector.SetFullyTrusted(true);
  2576. }
  2577. }
  2578. [Test]
  2579. public void DeserializeISerializableInPartialTrust()
  2580. {
  2581. try
  2582. {
  2583. ExceptionAssert.Throws<JsonSerializationException>(
  2584. @"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.
  2585. To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true. Path ''.",
  2586. () =>
  2587. {
  2588. JsonTypeReflector.SetFullyTrusted(false);
  2589. ISerializableTestObject value = new ISerializableTestObject("string!", 0, default(DateTimeOffset), null);
  2590. JsonConvert.SerializeObject(value);
  2591. });
  2592. }
  2593. finally
  2594. {
  2595. JsonTypeReflector.SetFullyTrusted(true);
  2596. }
  2597. }
  2598. #endif
  2599. [Test]
  2600. public void SerializeISerializableTestObject_IsoDate()
  2601. {
  2602. Person person = new Person();
  2603. person.BirthDate = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
  2604. person.LastModified = person.BirthDate;
  2605. person.Department = "Department!";
  2606. person.Name = "Name!";
  2607. DateTimeOffset dateTimeOffset = new DateTimeOffset(2000, 12, 20, 22, 59, 59, TimeSpan.FromHours(2));
  2608. string dateTimeOffsetText;
  2609. #if !NET20
  2610. dateTimeOffsetText = @"2000-12-20T22:59:59+02:00";
  2611. #else
  2612. dateTimeOffsetText = @"12/20/2000 22:59:59 +02:00";
  2613. #endif
  2614. ISerializableTestObject o = new ISerializableTestObject("String!", int.MinValue, dateTimeOffset, person);
  2615. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  2616. Assert.AreEqual(@"{
  2617. ""stringValue"": ""String!"",
  2618. ""intValue"": -2147483648,
  2619. ""dateTimeOffsetValue"": """ + dateTimeOffsetText + @""",
  2620. ""personValue"": {
  2621. ""Name"": ""Name!"",
  2622. ""BirthDate"": ""2000-01-01T01:01:01Z"",
  2623. ""LastModified"": ""2000-01-01T01:01:01Z""
  2624. },
  2625. ""nullPersonValue"": null,
  2626. ""nullableInt"": null,
  2627. ""booleanValue"": false,
  2628. ""byteValue"": 0,
  2629. ""charValue"": ""\u0000"",
  2630. ""dateTimeValue"": ""0001-01-01T00:00:00Z"",
  2631. ""decimalValue"": 0.0,
  2632. ""shortValue"": 0,
  2633. ""longValue"": 0,
  2634. ""sbyteValue"": 0,
  2635. ""floatValue"": 0.0,
  2636. ""ushortValue"": 0,
  2637. ""uintValue"": 0,
  2638. ""ulongValue"": 0
  2639. }", json);
  2640. ISerializableTestObject o2 = JsonConvert.DeserializeObject<ISerializableTestObject>(json);
  2641. Assert.AreEqual("String!", o2._stringValue);
  2642. Assert.AreEqual(int.MinValue, o2._intValue);
  2643. Assert.AreEqual(dateTimeOffset, o2._dateTimeOffsetValue);
  2644. Assert.AreEqual("Name!", o2._personValue.Name);
  2645. Assert.AreEqual(null, o2._nullPersonValue);
  2646. Assert.AreEqual(null, o2._nullableInt);
  2647. }
  2648. [Test]
  2649. public void SerializeISerializableTestObject_MsAjax()
  2650. {
  2651. Person person = new Person();
  2652. person.BirthDate = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
  2653. person.LastModified = person.BirthDate;
  2654. person.Department = "Department!";
  2655. person.Name = "Name!";
  2656. DateTimeOffset dateTimeOffset = new DateTimeOffset(2000, 12, 20, 22, 59, 59, TimeSpan.FromHours(2));
  2657. string dateTimeOffsetText;
  2658. #if !NET20
  2659. dateTimeOffsetText = @"\/Date(977345999000+0200)\/";
  2660. #else
  2661. dateTimeOffsetText = @"12/20/2000 22:59:59 +02:00";
  2662. #endif
  2663. ISerializableTestObject o = new ISerializableTestObject("String!", int.MinValue, dateTimeOffset, person);
  2664. string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
  2665. {
  2666. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  2667. });
  2668. Assert.AreEqual(@"{
  2669. ""stringValue"": ""String!"",
  2670. ""intValue"": -2147483648,
  2671. ""dateTimeOffsetValue"": """ + dateTimeOffsetText + @""",
  2672. ""personValue"": {
  2673. ""Name"": ""Name!"",
  2674. ""BirthDate"": ""\/Date(946688461000)\/"",
  2675. ""LastModified"": ""\/Date(946688461000)\/""
  2676. },
  2677. ""nullPersonValue"": null,
  2678. ""nullableInt"": null,
  2679. ""booleanValue"": false,
  2680. ""byteValue"": 0,
  2681. ""charValue"": ""\u0000"",
  2682. ""dateTimeValue"": ""\/Date(-62135596800000)\/"",
  2683. ""decimalValue"": 0.0,
  2684. ""shortValue"": 0,
  2685. ""longValue"": 0,
  2686. ""sbyteValue"": 0,
  2687. ""floatValue"": 0.0,
  2688. ""ushortValue"": 0,
  2689. ""uintValue"": 0,
  2690. ""ulongValue"": 0
  2691. }", json);
  2692. ISerializableTestObject o2 = JsonConvert.DeserializeObject<ISerializableTestObject>(json);
  2693. Assert.AreEqual("String!", o2._stringValue);
  2694. Assert.AreEqual(int.MinValue, o2._intValue);
  2695. Assert.AreEqual(dateTimeOffset, o2._dateTimeOffsetValue);
  2696. Assert.AreEqual("Name!", o2._personValue.Name);
  2697. Assert.AreEqual(null, o2._nullPersonValue);
  2698. Assert.AreEqual(null, o2._nullableInt);
  2699. }
  2700. #endif
  2701. public class KVPair<TKey, TValue>
  2702. {
  2703. public TKey Key { get; set; }
  2704. public TValue Value { get; set; }
  2705. public KVPair(TKey k, TValue v)
  2706. {
  2707. Key = k;
  2708. Value = v;
  2709. }
  2710. }
  2711. [Test]
  2712. public void DeserializeUsingNonDefaultConstructorWithLeftOverValues()
  2713. {
  2714. List<KVPair<string, string>> kvPairs =
  2715. JsonConvert.DeserializeObject<List<KVPair<string, string>>>(
  2716. "[{\"Key\":\"Two\",\"Value\":\"2\"},{\"Key\":\"One\",\"Value\":\"1\"}]");
  2717. Assert.AreEqual(2, kvPairs.Count);
  2718. Assert.AreEqual("Two", kvPairs[0].Key);
  2719. Assert.AreEqual("2", kvPairs[0].Value);
  2720. Assert.AreEqual("One", kvPairs[1].Key);
  2721. Assert.AreEqual("1", kvPairs[1].Value);
  2722. }
  2723. [Test]
  2724. public void SerializeClassWithInheritedProtectedMember()
  2725. {
  2726. AA myA = new AA(2);
  2727. string json = JsonConvert.SerializeObject(myA, Formatting.Indented);
  2728. Assert.AreEqual(@"{
  2729. ""AA_field1"": 2,
  2730. ""AA_property1"": 2,
  2731. ""AA_property2"": 2,
  2732. ""AA_property3"": 2,
  2733. ""AA_property4"": 2
  2734. }", json);
  2735. BB myB = new BB(3, 4);
  2736. json = JsonConvert.SerializeObject(myB, Formatting.Indented);
  2737. Assert.AreEqual(@"{
  2738. ""BB_field1"": 4,
  2739. ""BB_field2"": 4,
  2740. ""AA_field1"": 3,
  2741. ""BB_property1"": 4,
  2742. ""BB_property2"": 4,
  2743. ""BB_property3"": 4,
  2744. ""BB_property4"": 4,
  2745. ""BB_property5"": 4,
  2746. ""BB_property7"": 4,
  2747. ""AA_property1"": 3,
  2748. ""AA_property2"": 3,
  2749. ""AA_property3"": 3,
  2750. ""AA_property4"": 3
  2751. }", json);
  2752. }
  2753. [Test]
  2754. public void DeserializeClassWithInheritedProtectedMember()
  2755. {
  2756. AA myA = JsonConvert.DeserializeObject<AA>(
  2757. @"{
  2758. ""AA_field1"": 2,
  2759. ""AA_field2"": 2,
  2760. ""AA_property1"": 2,
  2761. ""AA_property2"": 2,
  2762. ""AA_property3"": 2,
  2763. ""AA_property4"": 2,
  2764. ""AA_property5"": 2,
  2765. ""AA_property6"": 2
  2766. }");
  2767. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field1", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2768. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field2", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2769. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property1", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2770. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property2", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2771. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property3", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2772. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property4", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2773. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property5", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2774. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property6", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  2775. BB myB = JsonConvert.DeserializeObject<BB>(
  2776. @"{
  2777. ""BB_field1"": 4,
  2778. ""BB_field2"": 4,
  2779. ""AA_field1"": 3,
  2780. ""AA_field2"": 3,
  2781. ""AA_property1"": 2,
  2782. ""AA_property2"": 2,
  2783. ""AA_property3"": 2,
  2784. ""AA_property4"": 2,
  2785. ""AA_property5"": 2,
  2786. ""AA_property6"": 2,
  2787. ""BB_property1"": 3,
  2788. ""BB_property2"": 3,
  2789. ""BB_property3"": 3,
  2790. ""BB_property4"": 3,
  2791. ""BB_property5"": 3,
  2792. ""BB_property6"": 3,
  2793. ""BB_property7"": 3,
  2794. ""BB_property8"": 3
  2795. }");
  2796. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field1", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2797. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field2", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2798. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property1", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2799. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property2", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2800. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property3", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2801. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property4", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2802. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property5", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2803. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property6", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2804. Assert.AreEqual(4, myB.BB_field1);
  2805. Assert.AreEqual(4, myB.BB_field2);
  2806. Assert.AreEqual(3, myB.BB_property1);
  2807. Assert.AreEqual(3, myB.BB_property2);
  2808. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property3", BindingFlags.Instance | BindingFlags.Public), myB));
  2809. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property4", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  2810. Assert.AreEqual(0, myB.BB_property5);
  2811. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property6", BindingFlags.Instance | BindingFlags.Public), myB));
  2812. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property7", BindingFlags.Instance | BindingFlags.Public), myB));
  2813. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property8", BindingFlags.Instance | BindingFlags.Public), myB));
  2814. }
  2815. public class AA
  2816. {
  2817. [JsonProperty]
  2818. protected int AA_field1;
  2819. protected int AA_field2;
  2820. [JsonProperty]
  2821. protected int AA_property1 { get; set; }
  2822. [JsonProperty]
  2823. protected int AA_property2 { get; private set; }
  2824. [JsonProperty]
  2825. protected int AA_property3 { private get; set; }
  2826. [JsonProperty]
  2827. private int AA_property4 { get; set; }
  2828. protected int AA_property5 { get; private set; }
  2829. protected int AA_property6 { private get; set; }
  2830. public AA()
  2831. {
  2832. }
  2833. public AA(int f)
  2834. {
  2835. AA_field1 = f;
  2836. AA_field2 = f;
  2837. AA_property1 = f;
  2838. AA_property2 = f;
  2839. AA_property3 = f;
  2840. AA_property4 = f;
  2841. AA_property5 = f;
  2842. AA_property6 = f;
  2843. }
  2844. }
  2845. public class BB : AA
  2846. {
  2847. [JsonProperty]
  2848. public int BB_field1;
  2849. public int BB_field2;
  2850. [JsonProperty]
  2851. public int BB_property1 { get; set; }
  2852. [JsonProperty]
  2853. public int BB_property2 { get; private set; }
  2854. [JsonProperty]
  2855. public int BB_property3 { private get; set; }
  2856. [JsonProperty]
  2857. private int BB_property4 { get; set; }
  2858. public int BB_property5 { get; private set; }
  2859. public int BB_property6 { private get; set; }
  2860. [JsonProperty]
  2861. public int BB_property7 { protected get; set; }
  2862. public int BB_property8 { protected get; set; }
  2863. public BB()
  2864. {
  2865. }
  2866. public BB(int f, int g)
  2867. : base(f)
  2868. {
  2869. BB_field1 = g;
  2870. BB_field2 = g;
  2871. BB_property1 = g;
  2872. BB_property2 = g;
  2873. BB_property3 = g;
  2874. BB_property4 = g;
  2875. BB_property5 = g;
  2876. BB_property6 = g;
  2877. BB_property7 = g;
  2878. BB_property8 = g;
  2879. }
  2880. }
  2881. #if !NET20 && !SILVERLIGHT
  2882. public class XNodeTestObject
  2883. {
  2884. public XDocument Document { get; set; }
  2885. public XElement Element { get; set; }
  2886. }
  2887. #endif
  2888. #if !SILVERLIGHT && !NETFX_CORE
  2889. public class XmlNodeTestObject
  2890. {
  2891. public XmlDocument Document { get; set; }
  2892. }
  2893. #endif
  2894. #if !(NET20 || SILVERLIGHT || PORTABLE)
  2895. [Test]
  2896. public void SerializeDeserializeXNodeProperties()
  2897. {
  2898. XNodeTestObject testObject = new XNodeTestObject();
  2899. testObject.Document = XDocument.Parse("<root>hehe, root</root>");
  2900. testObject.Element = XElement.Parse(@"<fifth xmlns:json=""http://json.org"" json:Awesome=""true"">element</fifth>");
  2901. string json = JsonConvert.SerializeObject(testObject, Formatting.Indented);
  2902. string expected = @"{
  2903. ""Document"": {
  2904. ""root"": ""hehe, root""
  2905. },
  2906. ""Element"": {
  2907. ""fifth"": {
  2908. ""@xmlns:json"": ""http://json.org"",
  2909. ""@json:Awesome"": ""true"",
  2910. ""#text"": ""element""
  2911. }
  2912. }
  2913. }";
  2914. Assert.AreEqual(expected, json);
  2915. XNodeTestObject newTestObject = JsonConvert.DeserializeObject<XNodeTestObject>(json);
  2916. Assert.AreEqual(testObject.Document.ToString(), newTestObject.Document.ToString());
  2917. Assert.AreEqual(testObject.Element.ToString(), newTestObject.Element.ToString());
  2918. Assert.IsNull(newTestObject.Element.Parent);
  2919. }
  2920. #endif
  2921. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  2922. [Test]
  2923. public void SerializeDeserializeXmlNodeProperties()
  2924. {
  2925. XmlNodeTestObject testObject = new XmlNodeTestObject();
  2926. XmlDocument document = new XmlDocument();
  2927. document.LoadXml("<root>hehe, root</root>");
  2928. testObject.Document = document;
  2929. string json = JsonConvert.SerializeObject(testObject, Formatting.Indented);
  2930. string expected = @"{
  2931. ""Document"": {
  2932. ""root"": ""hehe, root""
  2933. }
  2934. }";
  2935. Assert.AreEqual(expected, json);
  2936. XmlNodeTestObject newTestObject = JsonConvert.DeserializeObject<XmlNodeTestObject>(json);
  2937. Assert.AreEqual(testObject.Document.InnerXml, newTestObject.Document.InnerXml);
  2938. }
  2939. #endif
  2940. [Test]
  2941. public void FullClientMapSerialization()
  2942. {
  2943. ClientMap source = new ClientMap()
  2944. {
  2945. position = new Pos() { X = 100, Y = 200 },
  2946. center = new PosDouble() { X = 251.6, Y = 361.3 }
  2947. };
  2948. string json = JsonConvert.SerializeObject(source, new PosConverter(), new PosDoubleConverter());
  2949. Assert.AreEqual("{\"position\":new Pos(100,200),\"center\":new PosD(251.6,361.3)}", json);
  2950. }
  2951. public class ClientMap
  2952. {
  2953. public Pos position { get; set; }
  2954. public PosDouble center { get; set; }
  2955. }
  2956. public class Pos
  2957. {
  2958. public int X { get; set; }
  2959. public int Y { get; set; }
  2960. }
  2961. public class PosDouble
  2962. {
  2963. public double X { get; set; }
  2964. public double Y { get; set; }
  2965. }
  2966. public class PosConverter : JsonConverter
  2967. {
  2968. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  2969. {
  2970. Pos p = (Pos)value;
  2971. if (p != null)
  2972. writer.WriteRawValue(String.Format("new Pos({0},{1})", p.X, p.Y));
  2973. else
  2974. writer.WriteNull();
  2975. }
  2976. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  2977. {
  2978. throw new NotImplementedException();
  2979. }
  2980. public override bool CanConvert(Type objectType)
  2981. {
  2982. return objectType.IsAssignableFrom(typeof(Pos));
  2983. }
  2984. }
  2985. public class PosDoubleConverter : JsonConverter
  2986. {
  2987. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  2988. {
  2989. PosDouble p = (PosDouble)value;
  2990. if (p != null)
  2991. writer.WriteRawValue(String.Format(CultureInfo.InvariantCulture, "new PosD({0},{1})", p.X, p.Y));
  2992. else
  2993. writer.WriteNull();
  2994. }
  2995. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  2996. {
  2997. throw new NotImplementedException();
  2998. }
  2999. public override bool CanConvert(Type objectType)
  3000. {
  3001. return objectType.IsAssignableFrom(typeof(PosDouble));
  3002. }
  3003. }
  3004. [Test]
  3005. public void TestEscapeDictionaryStrings()
  3006. {
  3007. const string s = @"host\user";
  3008. string serialized = JsonConvert.SerializeObject(s);
  3009. Assert.AreEqual(@"""host\\user""", serialized);
  3010. Dictionary<int, object> d1 = new Dictionary<int, object>();
  3011. d1.Add(5, s);
  3012. Assert.AreEqual(@"{""5"":""host\\user""}", JsonConvert.SerializeObject(d1));
  3013. Dictionary<string, object> d2 = new Dictionary<string, object>();
  3014. d2.Add(s, 5);
  3015. Assert.AreEqual(@"{""host\\user"":5}", JsonConvert.SerializeObject(d2));
  3016. }
  3017. public class GenericListTestClass
  3018. {
  3019. public List<string> GenericList { get; set; }
  3020. public GenericListTestClass()
  3021. {
  3022. GenericList = new List<string>();
  3023. }
  3024. }
  3025. [Test]
  3026. public void DeserializeExistingGenericList()
  3027. {
  3028. GenericListTestClass c = new GenericListTestClass();
  3029. c.GenericList.Add("1");
  3030. c.GenericList.Add("2");
  3031. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3032. GenericListTestClass newValue = JsonConvert.DeserializeObject<GenericListTestClass>(json);
  3033. Assert.AreEqual(2, newValue.GenericList.Count);
  3034. Assert.AreEqual(typeof(List<string>), newValue.GenericList.GetType());
  3035. }
  3036. [Test]
  3037. public void DeserializeSimpleKeyValuePair()
  3038. {
  3039. List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
  3040. list.Add(new KeyValuePair<string, string>("key1", "value1"));
  3041. list.Add(new KeyValuePair<string, string>("key2", "value2"));
  3042. string json = JsonConvert.SerializeObject(list);
  3043. Assert.AreEqual(@"[{""Key"":""key1"",""Value"":""value1""},{""Key"":""key2"",""Value"":""value2""}]", json);
  3044. List<KeyValuePair<string, string>> result = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(json);
  3045. Assert.AreEqual(2, result.Count);
  3046. Assert.AreEqual("key1", result[0].Key);
  3047. Assert.AreEqual("value1", result[0].Value);
  3048. Assert.AreEqual("key2", result[1].Key);
  3049. Assert.AreEqual("value2", result[1].Value);
  3050. }
  3051. [Test]
  3052. public void DeserializeComplexKeyValuePair()
  3053. {
  3054. DateTime dateTime = new DateTime(2000, 12, 1, 23, 1, 1, DateTimeKind.Utc);
  3055. List<KeyValuePair<string, WagePerson>> list = new List<KeyValuePair<string, WagePerson>>();
  3056. list.Add(new KeyValuePair<string, WagePerson>("key1", new WagePerson
  3057. {
  3058. BirthDate = dateTime,
  3059. Department = "Department1",
  3060. LastModified = dateTime,
  3061. HourlyWage = 1
  3062. }));
  3063. list.Add(new KeyValuePair<string, WagePerson>("key2", new WagePerson
  3064. {
  3065. BirthDate = dateTime,
  3066. Department = "Department2",
  3067. LastModified = dateTime,
  3068. HourlyWage = 2
  3069. }));
  3070. string json = JsonConvert.SerializeObject(list, Formatting.Indented);
  3071. Assert.AreEqual(@"[
  3072. {
  3073. ""Key"": ""key1"",
  3074. ""Value"": {
  3075. ""HourlyWage"": 1.0,
  3076. ""Name"": null,
  3077. ""BirthDate"": ""2000-12-01T23:01:01Z"",
  3078. ""LastModified"": ""2000-12-01T23:01:01Z""
  3079. }
  3080. },
  3081. {
  3082. ""Key"": ""key2"",
  3083. ""Value"": {
  3084. ""HourlyWage"": 2.0,
  3085. ""Name"": null,
  3086. ""BirthDate"": ""2000-12-01T23:01:01Z"",
  3087. ""LastModified"": ""2000-12-01T23:01:01Z""
  3088. }
  3089. }
  3090. ]", json);
  3091. List<KeyValuePair<string, WagePerson>> result = JsonConvert.DeserializeObject<List<KeyValuePair<string, WagePerson>>>(json);
  3092. Assert.AreEqual(2, result.Count);
  3093. Assert.AreEqual("key1", result[0].Key);
  3094. Assert.AreEqual(1, result[0].Value.HourlyWage);
  3095. Assert.AreEqual("key2", result[1].Key);
  3096. Assert.AreEqual(2, result[1].Value.HourlyWage);
  3097. }
  3098. public class StringListAppenderConverter : JsonConverter
  3099. {
  3100. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  3101. {
  3102. writer.WriteValue(value);
  3103. }
  3104. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  3105. {
  3106. List<string> existingStrings = (List<string>)existingValue;
  3107. List<string> newStrings = new List<string>(existingStrings);
  3108. reader.Read();
  3109. while (reader.TokenType != JsonToken.EndArray)
  3110. {
  3111. string s = (string)reader.Value;
  3112. newStrings.Add(s);
  3113. reader.Read();
  3114. }
  3115. return newStrings;
  3116. }
  3117. public override bool CanConvert(Type objectType)
  3118. {
  3119. return (objectType == typeof(List<string>));
  3120. }
  3121. }
  3122. [Test]
  3123. public void StringListAppenderConverterTest()
  3124. {
  3125. Movie p = new Movie();
  3126. p.ReleaseCountries = new List<string> { "Existing" };
  3127. JsonConvert.PopulateObject("{'ReleaseCountries':['Appended']}", p, new JsonSerializerSettings
  3128. {
  3129. Converters = new List<JsonConverter> { new StringListAppenderConverter() }
  3130. });
  3131. Assert.AreEqual(2, p.ReleaseCountries.Count);
  3132. Assert.AreEqual("Existing", p.ReleaseCountries[0]);
  3133. Assert.AreEqual("Appended", p.ReleaseCountries[1]);
  3134. }
  3135. public class StringAppenderConverter : JsonConverter
  3136. {
  3137. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  3138. {
  3139. writer.WriteValue(value);
  3140. }
  3141. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  3142. {
  3143. string existingString = (string)existingValue;
  3144. string newString = existingString + (string)reader.Value;
  3145. return newString;
  3146. }
  3147. public override bool CanConvert(Type objectType)
  3148. {
  3149. return (objectType == typeof(string));
  3150. }
  3151. }
  3152. [Test]
  3153. public void StringAppenderConverterTest()
  3154. {
  3155. Movie p = new Movie();
  3156. p.Name = "Existing,";
  3157. JsonConvert.PopulateObject("{'Name':'Appended'}", p, new JsonSerializerSettings
  3158. {
  3159. Converters = new List<JsonConverter> { new StringAppenderConverter() }
  3160. });
  3161. Assert.AreEqual("Existing,Appended", p.Name);
  3162. }
  3163. [Test]
  3164. public void SerializeRefAdditionalContent()
  3165. {
  3166. //Additional text found in JSON string after finishing deserializing object.
  3167. //Test 1
  3168. var reference = new Dictionary<string, object>();
  3169. reference.Add("$ref", "Persons");
  3170. reference.Add("$id", 1);
  3171. var child = new Dictionary<string, object>();
  3172. child.Add("_id", 2);
  3173. child.Add("Name", "Isabell");
  3174. child.Add("Father", reference);
  3175. var json = JsonConvert.SerializeObject(child, Formatting.Indented);
  3176. ExceptionAssert.Throws<JsonSerializationException>(
  3177. "Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Path 'Father.$id', line 6, position 11.",
  3178. () =>
  3179. {
  3180. JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  3181. });
  3182. }
  3183. [Test]
  3184. public void SerializeRefBadType()
  3185. {
  3186. ExceptionAssert.Throws<JsonSerializationException>(
  3187. "JSON reference $ref property must have a string or null value. Path 'Father.$ref', line 5, position 14.",
  3188. () =>
  3189. {
  3190. //Additional text found in JSON string after finishing deserializing object.
  3191. //Test 1
  3192. var reference = new Dictionary<string, object>();
  3193. reference.Add("$ref", 1);
  3194. reference.Add("$id", 1);
  3195. var child = new Dictionary<string, object>();
  3196. child.Add("_id", 2);
  3197. child.Add("Name", "Isabell");
  3198. child.Add("Father", reference);
  3199. var json = JsonConvert.SerializeObject(child, Formatting.Indented);
  3200. JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  3201. });
  3202. }
  3203. [Test]
  3204. public void SerializeRefNull()
  3205. {
  3206. var reference = new Dictionary<string, object>();
  3207. reference.Add("$ref", null);
  3208. reference.Add("$id", null);
  3209. reference.Add("blah", "blah!");
  3210. var child = new Dictionary<string, object>();
  3211. child.Add("_id", 2);
  3212. child.Add("Name", "Isabell");
  3213. child.Add("Father", reference);
  3214. var json = JsonConvert.SerializeObject(child);
  3215. Dictionary<string, object> result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  3216. Assert.AreEqual(3, result.Count);
  3217. Assert.AreEqual(1, ((JObject)result["Father"]).Count);
  3218. Assert.AreEqual("blah!", (string)((JObject)result["Father"])["blah"]);
  3219. }
  3220. public class ConstructorCompexIgnoredProperty
  3221. {
  3222. [JsonIgnore]
  3223. public Product Ignored { get; set; }
  3224. public string First { get; set; }
  3225. public int Second { get; set; }
  3226. public ConstructorCompexIgnoredProperty(string first, int second)
  3227. {
  3228. First = first;
  3229. Second = second;
  3230. }
  3231. }
  3232. [Test]
  3233. public void DeserializeIgnoredPropertyInConstructor()
  3234. {
  3235. string json = @"{""First"":""First"",""Second"":2,""Ignored"":{""Name"":""James""},""AdditionalContent"":{""LOL"":true}}";
  3236. ConstructorCompexIgnoredProperty cc = JsonConvert.DeserializeObject<ConstructorCompexIgnoredProperty>(json);
  3237. Assert.AreEqual("First", cc.First);
  3238. Assert.AreEqual(2, cc.Second);
  3239. Assert.AreEqual(null, cc.Ignored);
  3240. }
  3241. [Test]
  3242. public void ShouldSerializeTest()
  3243. {
  3244. ShouldSerializeTestClass c = new ShouldSerializeTestClass();
  3245. c.Name = "James";
  3246. c.Age = 27;
  3247. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3248. Assert.AreEqual(@"{
  3249. ""Age"": 27
  3250. }", json);
  3251. c._shouldSerializeName = true;
  3252. json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3253. Assert.AreEqual(@"{
  3254. ""Name"": ""James"",
  3255. ""Age"": 27
  3256. }", json);
  3257. ShouldSerializeTestClass deserialized = JsonConvert.DeserializeObject<ShouldSerializeTestClass>(json);
  3258. Assert.AreEqual("James", deserialized.Name);
  3259. Assert.AreEqual(27, deserialized.Age);
  3260. }
  3261. public class Employee
  3262. {
  3263. public string Name { get; set; }
  3264. public Employee Manager { get; set; }
  3265. public bool ShouldSerializeManager()
  3266. {
  3267. return (Manager != this);
  3268. }
  3269. }
  3270. [Test]
  3271. public void ShouldSerializeExample()
  3272. {
  3273. Employee joe = new Employee();
  3274. joe.Name = "Joe Employee";
  3275. Employee mike = new Employee();
  3276. mike.Name = "Mike Manager";
  3277. joe.Manager = mike;
  3278. mike.Manager = mike;
  3279. string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented);
  3280. // [
  3281. // {
  3282. // "Name": "Joe Employee",
  3283. // "Manager": {
  3284. // "Name": "Mike Manager"
  3285. // }
  3286. // },
  3287. // {
  3288. // "Name": "Mike Manager"
  3289. // }
  3290. // ]
  3291. Console.WriteLine(json);
  3292. }
  3293. [Test]
  3294. public void SpecifiedTest()
  3295. {
  3296. SpecifiedTestClass c = new SpecifiedTestClass();
  3297. c.Name = "James";
  3298. c.Age = 27;
  3299. c.NameSpecified = false;
  3300. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3301. Assert.AreEqual(@"{
  3302. ""Age"": 27
  3303. }", json);
  3304. SpecifiedTestClass deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json);
  3305. Assert.IsNull(deserialized.Name);
  3306. Assert.IsFalse(deserialized.NameSpecified);
  3307. Assert.IsFalse(deserialized.WeightSpecified);
  3308. Assert.IsFalse(deserialized.HeightSpecified);
  3309. Assert.IsFalse(deserialized.FavoriteNumberSpecified);
  3310. Assert.AreEqual(27, deserialized.Age);
  3311. c.NameSpecified = true;
  3312. c.WeightSpecified = true;
  3313. c.HeightSpecified = true;
  3314. c.FavoriteNumber = 23;
  3315. json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3316. Assert.AreEqual(@"{
  3317. ""Name"": ""James"",
  3318. ""Age"": 27,
  3319. ""Weight"": 0,
  3320. ""Height"": 0,
  3321. ""FavoriteNumber"": 23
  3322. }", json);
  3323. deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json);
  3324. Assert.AreEqual("James", deserialized.Name);
  3325. Assert.IsTrue(deserialized.NameSpecified);
  3326. Assert.IsTrue(deserialized.WeightSpecified);
  3327. Assert.IsTrue(deserialized.HeightSpecified);
  3328. Assert.IsTrue(deserialized.FavoriteNumberSpecified);
  3329. Assert.AreEqual(27, deserialized.Age);
  3330. Assert.AreEqual(23, deserialized.FavoriteNumber);
  3331. }
  3332. // [Test]
  3333. // public void XmlSerializerSpecifiedTrueTest()
  3334. // {
  3335. // XmlSerializer s = new XmlSerializer(typeof(OptionalOrder));
  3336. // StringWriter sw = new StringWriter();
  3337. // s.Serialize(sw, new OptionalOrder() { FirstOrder = "First", FirstOrderSpecified = true });
  3338. // Console.WriteLine(sw.ToString());
  3339. // string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
  3340. //<OptionalOrder xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  3341. // <FirstOrder>First</FirstOrder>
  3342. //</OptionalOrder>";
  3343. // OptionalOrder o = (OptionalOrder)s.Deserialize(new StringReader(xml));
  3344. // Console.WriteLine(o.FirstOrder);
  3345. // Console.WriteLine(o.FirstOrderSpecified);
  3346. // }
  3347. // [Test]
  3348. // public void XmlSerializerSpecifiedFalseTest()
  3349. // {
  3350. // XmlSerializer s = new XmlSerializer(typeof(OptionalOrder));
  3351. // StringWriter sw = new StringWriter();
  3352. // s.Serialize(sw, new OptionalOrder() { FirstOrder = "First", FirstOrderSpecified = false });
  3353. // Console.WriteLine(sw.ToString());
  3354. // // string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
  3355. // //<OptionalOrder xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  3356. // // <FirstOrder>First</FirstOrder>
  3357. // //</OptionalOrder>";
  3358. // // OptionalOrder o = (OptionalOrder)s.Deserialize(new StringReader(xml));
  3359. // // Console.WriteLine(o.FirstOrder);
  3360. // // Console.WriteLine(o.FirstOrderSpecified);
  3361. // }
  3362. public class OptionalOrder
  3363. {
  3364. // This field shouldn't be serialized
  3365. // if it is uninitialized.
  3366. public string FirstOrder;
  3367. // Use the XmlIgnoreAttribute to ignore the
  3368. // special field named "FirstOrderSpecified".
  3369. [System.Xml.Serialization.XmlIgnoreAttribute]
  3370. public bool FirstOrderSpecified;
  3371. }
  3372. public class FamilyDetails
  3373. {
  3374. public string Name { get; set; }
  3375. public int NumberOfChildren { get; set; }
  3376. [JsonIgnore]
  3377. public bool NumberOfChildrenSpecified { get; set; }
  3378. }
  3379. [Test]
  3380. public void SpecifiedExample()
  3381. {
  3382. FamilyDetails joe = new FamilyDetails();
  3383. joe.Name = "Joe Family Details";
  3384. joe.NumberOfChildren = 4;
  3385. joe.NumberOfChildrenSpecified = true;
  3386. FamilyDetails martha = new FamilyDetails();
  3387. martha.Name = "Martha Family Details";
  3388. martha.NumberOfChildren = 3;
  3389. martha.NumberOfChildrenSpecified = false;
  3390. string json = JsonConvert.SerializeObject(new[] { joe, martha }, Formatting.Indented);
  3391. //[
  3392. // {
  3393. // "Name": "Joe Family Details",
  3394. // "NumberOfChildren": 4
  3395. // },
  3396. // {
  3397. // "Name": "Martha Family Details"
  3398. // }
  3399. //]
  3400. Console.WriteLine(json);
  3401. string mikeString = "{\"Name\": \"Mike Person\"}";
  3402. FamilyDetails mike = JsonConvert.DeserializeObject<FamilyDetails>(mikeString);
  3403. Console.WriteLine("mikeString specifies number of children: {0}", mike.NumberOfChildrenSpecified);
  3404. string mikeFullDisclosureString = "{\"Name\": \"Mike Person\", \"NumberOfChildren\": \"0\"}";
  3405. mike = JsonConvert.DeserializeObject<FamilyDetails>(mikeFullDisclosureString);
  3406. Console.WriteLine("mikeString specifies number of children: {0}", mike.NumberOfChildrenSpecified);
  3407. }
  3408. public class DictionaryKey
  3409. {
  3410. public string Value { get; set; }
  3411. public override string ToString()
  3412. {
  3413. return Value;
  3414. }
  3415. public static implicit operator DictionaryKey(string value)
  3416. {
  3417. return new DictionaryKey() { Value = value };
  3418. }
  3419. }
  3420. [Test]
  3421. public void SerializeDeserializeDictionaryKey()
  3422. {
  3423. Dictionary<DictionaryKey, string> dictionary = new Dictionary<DictionaryKey, string>();
  3424. dictionary.Add(new DictionaryKey() { Value = "First!" }, "First");
  3425. dictionary.Add(new DictionaryKey() { Value = "Second!" }, "Second");
  3426. string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
  3427. Assert.AreEqual(@"{
  3428. ""First!"": ""First"",
  3429. ""Second!"": ""Second""
  3430. }", json);
  3431. Dictionary<DictionaryKey, string> newDictionary =
  3432. JsonConvert.DeserializeObject<Dictionary<DictionaryKey, string>>(json);
  3433. Assert.AreEqual(2, newDictionary.Count);
  3434. }
  3435. [Test]
  3436. public void SerializeNullableArray()
  3437. {
  3438. string jsonText = JsonConvert.SerializeObject(new double?[] { 2.4, 4.3, null }, Formatting.Indented);
  3439. Assert.AreEqual(@"[
  3440. 2.4,
  3441. 4.3,
  3442. null
  3443. ]", jsonText);
  3444. double?[] d = (double?[])JsonConvert.DeserializeObject(jsonText, typeof(double?[]));
  3445. Assert.AreEqual(3, d.Length);
  3446. Assert.AreEqual(2.4, d[0]);
  3447. Assert.AreEqual(4.3, d[1]);
  3448. Assert.AreEqual(null, d[2]);
  3449. }
  3450. #if !SILVERLIGHT && !NET20
  3451. [Test]
  3452. public void SerializeHashSet()
  3453. {
  3454. string jsonText = JsonConvert.SerializeObject(new HashSet<string>()
  3455. {
  3456. "One",
  3457. "2",
  3458. "III"
  3459. }, Formatting.Indented);
  3460. Assert.AreEqual(@"[
  3461. ""One"",
  3462. ""2"",
  3463. ""III""
  3464. ]", jsonText);
  3465. HashSet<string> d = JsonConvert.DeserializeObject<HashSet<string>>(jsonText);
  3466. Assert.AreEqual(3, d.Count);
  3467. Assert.IsTrue(d.Contains("One"));
  3468. Assert.IsTrue(d.Contains("2"));
  3469. Assert.IsTrue(d.Contains("III"));
  3470. }
  3471. #endif
  3472. private class MyClass
  3473. {
  3474. public byte[] Prop1 { get; set; }
  3475. public MyClass()
  3476. {
  3477. Prop1 = new byte[0];
  3478. }
  3479. }
  3480. [Test]
  3481. public void DeserializeByteArray()
  3482. {
  3483. JsonSerializer serializer1 = new JsonSerializer();
  3484. serializer1.Converters.Add(new IsoDateTimeConverter());
  3485. serializer1.NullValueHandling = NullValueHandling.Ignore;
  3486. string json = @"[{""Prop1"":""""},{""Prop1"":""""}]";
  3487. JsonTextReader reader = new JsonTextReader(new StringReader(json));
  3488. MyClass[] z = (MyClass[])serializer1.Deserialize(reader, typeof(MyClass[]));
  3489. Assert.AreEqual(2, z.Length);
  3490. Assert.AreEqual(0, z[0].Prop1.Length);
  3491. Assert.AreEqual(0, z[1].Prop1.Length);
  3492. }
  3493. #if !NET20 && !SILVERLIGHT && !NETFX_CORE
  3494. public class StringDictionaryTestClass
  3495. {
  3496. public StringDictionary StringDictionaryProperty { get; set; }
  3497. }
  3498. [Test]
  3499. public void StringDictionaryTest()
  3500. {
  3501. string classRef = typeof(StringDictionary).FullName;
  3502. StringDictionaryTestClass s1 = new StringDictionaryTestClass()
  3503. {
  3504. StringDictionaryProperty = new StringDictionary()
  3505. {
  3506. {"1", "One"},
  3507. {"2", "II"},
  3508. {"3", "3"}
  3509. }
  3510. };
  3511. string json = JsonConvert.SerializeObject(s1, Formatting.Indented);
  3512. ExceptionAssert.Throws<InvalidOperationException>(
  3513. "Cannot create and populate list type " + classRef + ".",
  3514. () =>
  3515. {
  3516. JsonConvert.DeserializeObject<StringDictionaryTestClass>(json);
  3517. });
  3518. }
  3519. #endif
  3520. [JsonObject(MemberSerialization.OptIn)]
  3521. public struct StructWithAttribute
  3522. {
  3523. public string MyString { get; set; }
  3524. [JsonProperty]
  3525. public int MyInt { get; set; }
  3526. }
  3527. [Test]
  3528. public void SerializeStructWithJsonObjectAttribute()
  3529. {
  3530. StructWithAttribute testStruct = new StructWithAttribute
  3531. {
  3532. MyInt = int.MaxValue
  3533. };
  3534. string json = JsonConvert.SerializeObject(testStruct, Formatting.Indented);
  3535. Assert.AreEqual(@"{
  3536. ""MyInt"": 2147483647
  3537. }", json);
  3538. StructWithAttribute newStruct = JsonConvert.DeserializeObject<StructWithAttribute>(json);
  3539. Assert.AreEqual(int.MaxValue, newStruct.MyInt);
  3540. }
  3541. public class TimeZoneOffsetObject
  3542. {
  3543. public DateTimeOffset Offset { get; set; }
  3544. }
  3545. #if !NET20
  3546. [Test]
  3547. public void ReadWriteTimeZoneOffsetIso()
  3548. {
  3549. var serializeObject = JsonConvert.SerializeObject(new TimeZoneOffsetObject
  3550. {
  3551. Offset = new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6))
  3552. });
  3553. Assert.AreEqual("{\"Offset\":\"2000-01-01T00:00:00+06:00\"}", serializeObject);
  3554. var deserializeObject = JsonConvert.DeserializeObject<TimeZoneOffsetObject>(serializeObject);
  3555. Assert.AreEqual(TimeSpan.FromHours(6), deserializeObject.Offset.Offset);
  3556. Assert.AreEqual(new DateTime(2000, 1, 1), deserializeObject.Offset.Date);
  3557. }
  3558. [Test]
  3559. public void DeserializePropertyNullableDateTimeOffsetExactIso()
  3560. {
  3561. NullableDateTimeTestClass d = JsonConvert.DeserializeObject<NullableDateTimeTestClass>("{\"DateTimeOffsetField\":\"2000-01-01T00:00:00+06:00\"}");
  3562. Assert.AreEqual(new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6)), d.DateTimeOffsetField);
  3563. }
  3564. [Test]
  3565. public void ReadWriteTimeZoneOffsetMsAjax()
  3566. {
  3567. var serializeObject = JsonConvert.SerializeObject(new TimeZoneOffsetObject
  3568. {
  3569. Offset = new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6))
  3570. }, Formatting.None, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
  3571. Assert.AreEqual("{\"Offset\":\"\\/Date(946663200000+0600)\\/\"}", serializeObject);
  3572. var deserializeObject = JsonConvert.DeserializeObject<TimeZoneOffsetObject>(serializeObject);
  3573. Assert.AreEqual(TimeSpan.FromHours(6), deserializeObject.Offset.Offset);
  3574. Assert.AreEqual(new DateTime(2000, 1, 1), deserializeObject.Offset.Date);
  3575. }
  3576. [Test]
  3577. public void DeserializePropertyNullableDateTimeOffsetExactMsAjax()
  3578. {
  3579. NullableDateTimeTestClass d = JsonConvert.DeserializeObject<NullableDateTimeTestClass>("{\"DateTimeOffsetField\":\"\\/Date(946663200000+0600)\\/\"}");
  3580. Assert.AreEqual(new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6)), d.DateTimeOffsetField);
  3581. }
  3582. #endif
  3583. public abstract class LogEvent
  3584. {
  3585. [JsonProperty("event")]
  3586. public abstract string EventName { get; }
  3587. }
  3588. public class DerivedEvent : LogEvent
  3589. {
  3590. public override string EventName
  3591. {
  3592. get { return "derived"; }
  3593. }
  3594. }
  3595. [Test]
  3596. public void OverridenPropertyMembers()
  3597. {
  3598. string json = JsonConvert.SerializeObject(new DerivedEvent(), Formatting.Indented);
  3599. Assert.AreEqual(@"{
  3600. ""event"": ""derived""
  3601. }", json);
  3602. }
  3603. #if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
  3604. [Test]
  3605. public void SerializeExpandoObject()
  3606. {
  3607. dynamic expando = new ExpandoObject();
  3608. expando.Int = 1;
  3609. expando.Decimal = 99.9d;
  3610. expando.Complex = new ExpandoObject();
  3611. expando.Complex.String = "I am a string";
  3612. expando.Complex.DateTime = new DateTime(2000, 12, 20, 18, 55, 0, DateTimeKind.Utc);
  3613. string json = JsonConvert.SerializeObject(expando, Formatting.Indented);
  3614. Assert.AreEqual(@"{
  3615. ""Int"": 1,
  3616. ""Decimal"": 99.9,
  3617. ""Complex"": {
  3618. ""String"": ""I am a string"",
  3619. ""DateTime"": ""2000-12-20T18:55:00Z""
  3620. }
  3621. }", json);
  3622. IDictionary<string, object> newExpando = JsonConvert.DeserializeObject<ExpandoObject>(json);
  3623. CustomAssert.IsInstanceOfType(typeof(long), newExpando["Int"]);
  3624. Assert.AreEqual((long)expando.Int, newExpando["Int"]);
  3625. CustomAssert.IsInstanceOfType(typeof(double), newExpando["Decimal"]);
  3626. Assert.AreEqual(expando.Decimal, newExpando["Decimal"]);
  3627. CustomAssert.IsInstanceOfType(typeof(ExpandoObject), newExpando["Complex"]);
  3628. IDictionary<string, object> o = (ExpandoObject)newExpando["Complex"];
  3629. CustomAssert.IsInstanceOfType(typeof(string), o["String"]);
  3630. Assert.AreEqual(expando.Complex.String, o["String"]);
  3631. CustomAssert.IsInstanceOfType(typeof(DateTime), o["DateTime"]);
  3632. Assert.AreEqual(expando.Complex.DateTime, o["DateTime"]);
  3633. }
  3634. #endif
  3635. [Test]
  3636. public void DeserializeDecimalExact()
  3637. {
  3638. decimal d = JsonConvert.DeserializeObject<decimal>("123456789876543.21");
  3639. Assert.AreEqual(123456789876543.21m, d);
  3640. }
  3641. [Test]
  3642. public void DeserializeNullableDecimalExact()
  3643. {
  3644. decimal? d = JsonConvert.DeserializeObject<decimal?>("123456789876543.21");
  3645. Assert.AreEqual(123456789876543.21m, d);
  3646. }
  3647. [Test]
  3648. public void DeserializeDecimalPropertyExact()
  3649. {
  3650. string json = "{Amount:123456789876543.21}";
  3651. Invoice i = JsonConvert.DeserializeObject<Invoice>(json);
  3652. Assert.AreEqual(123456789876543.21m, i.Amount);
  3653. }
  3654. [Test]
  3655. public void DeserializeDecimalArrayExact()
  3656. {
  3657. string json = "[123456789876543.21]";
  3658. IList<decimal> a = JsonConvert.DeserializeObject<IList<decimal>>(json);
  3659. Assert.AreEqual(123456789876543.21m, a[0]);
  3660. }
  3661. [Test]
  3662. public void DeserializeDecimalDictionaryExact()
  3663. {
  3664. string json = "{'Value':123456789876543.21}";
  3665. IDictionary<string, decimal> d = JsonConvert.DeserializeObject<IDictionary<string, decimal>>(json);
  3666. Assert.AreEqual(123456789876543.21m, d["Value"]);
  3667. }
  3668. public struct Vector
  3669. {
  3670. public float X;
  3671. public float Y;
  3672. public float Z;
  3673. public override string ToString()
  3674. {
  3675. return string.Format("({0},{1},{2})", X, Y, Z);
  3676. }
  3677. }
  3678. public class VectorParent
  3679. {
  3680. public Vector Position;
  3681. }
  3682. [Test]
  3683. public void DeserializeStructProperty()
  3684. {
  3685. VectorParent obj = new VectorParent();
  3686. obj.Position = new Vector { X = 1, Y = 2, Z = 3 };
  3687. string str = JsonConvert.SerializeObject(obj);
  3688. obj = JsonConvert.DeserializeObject<VectorParent>(str);
  3689. Assert.AreEqual(1, obj.Position.X);
  3690. Assert.AreEqual(2, obj.Position.Y);
  3691. Assert.AreEqual(3, obj.Position.Z);
  3692. }
  3693. [JsonObject(MemberSerialization.OptIn)]
  3694. public class Derived : Base
  3695. {
  3696. [JsonProperty]
  3697. public string IDoWork { get; private set; }
  3698. private Derived()
  3699. {
  3700. }
  3701. internal Derived(string dontWork, string doWork)
  3702. : base(dontWork)
  3703. {
  3704. IDoWork = doWork;
  3705. }
  3706. }
  3707. [JsonObject(MemberSerialization.OptIn)]
  3708. public class Base
  3709. {
  3710. [JsonProperty]
  3711. public string IDontWork { get; private set; }
  3712. protected Base()
  3713. {
  3714. }
  3715. internal Base(string dontWork)
  3716. {
  3717. IDontWork = dontWork;
  3718. }
  3719. }
  3720. [Test]
  3721. public void PrivateSetterOnBaseClassProperty()
  3722. {
  3723. var derived = new Derived("meh", "woo");
  3724. var settings = new JsonSerializerSettings
  3725. {
  3726. TypeNameHandling = TypeNameHandling.Objects,
  3727. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
  3728. };
  3729. string json = JsonConvert.SerializeObject(derived, Formatting.Indented, settings);
  3730. var meh = JsonConvert.DeserializeObject<Base>(json, settings);
  3731. Assert.AreEqual(((Derived)meh).IDoWork, "woo");
  3732. Assert.AreEqual(meh.IDontWork, "meh");
  3733. }
  3734. #if !(SILVERLIGHT || NET20 || NETFX_CORE)
  3735. [DataContract]
  3736. public struct StructISerializable : ISerializable
  3737. {
  3738. private string _name;
  3739. public StructISerializable(SerializationInfo info, StreamingContext context)
  3740. {
  3741. _name = info.GetString("Name");
  3742. }
  3743. [DataMember]
  3744. public string Name
  3745. {
  3746. get { return _name; }
  3747. set { _name = value; }
  3748. }
  3749. public void GetObjectData(SerializationInfo info, StreamingContext context)
  3750. {
  3751. info.AddValue("Name", _name);
  3752. }
  3753. }
  3754. [DataContract]
  3755. public class NullableStructPropertyClass
  3756. {
  3757. private StructISerializable _foo1;
  3758. private StructISerializable? _foo2;
  3759. [DataMember]
  3760. public StructISerializable Foo1
  3761. {
  3762. get { return _foo1; }
  3763. set { _foo1 = value; }
  3764. }
  3765. [DataMember]
  3766. public StructISerializable? Foo2
  3767. {
  3768. get { return _foo2; }
  3769. set { _foo2 = value; }
  3770. }
  3771. }
  3772. [Test]
  3773. public void DeserializeNullableStruct()
  3774. {
  3775. NullableStructPropertyClass nullableStructPropertyClass = new NullableStructPropertyClass();
  3776. nullableStructPropertyClass.Foo1 = new StructISerializable() { Name = "foo 1" };
  3777. nullableStructPropertyClass.Foo2 = new StructISerializable() { Name = "foo 2" };
  3778. NullableStructPropertyClass barWithNull = new NullableStructPropertyClass();
  3779. barWithNull.Foo1 = new StructISerializable() { Name = "foo 1" };
  3780. barWithNull.Foo2 = null;
  3781. //throws error on deserialization because bar1.Foo2 is of type Foo?
  3782. string s = JsonConvert.SerializeObject(nullableStructPropertyClass);
  3783. NullableStructPropertyClass deserialized = deserialize(s);
  3784. Assert.AreEqual(deserialized.Foo1.Name, "foo 1");
  3785. Assert.AreEqual(deserialized.Foo2.Value.Name, "foo 2");
  3786. //no error Foo2 is null
  3787. s = JsonConvert.SerializeObject(barWithNull);
  3788. deserialized = deserialize(s);
  3789. Assert.AreEqual(deserialized.Foo1.Name, "foo 1");
  3790. Assert.AreEqual(deserialized.Foo2, null);
  3791. }
  3792. private static NullableStructPropertyClass deserialize(string serStr)
  3793. {
  3794. return JsonConvert.DeserializeObject<NullableStructPropertyClass>(
  3795. serStr,
  3796. new JsonSerializerSettings
  3797. {
  3798. NullValueHandling = NullValueHandling.Ignore,
  3799. MissingMemberHandling = MissingMemberHandling.Ignore
  3800. });
  3801. }
  3802. #endif
  3803. public class Response
  3804. {
  3805. public string Name { get; set; }
  3806. public JToken Data { get; set; }
  3807. }
  3808. [Test]
  3809. public void DeserializeJToken()
  3810. {
  3811. Response response = new Response
  3812. {
  3813. Name = "Success",
  3814. Data = new JObject(new JProperty("First", "Value1"), new JProperty("Second", "Value2"))
  3815. };
  3816. string json = JsonConvert.SerializeObject(response, Formatting.Indented);
  3817. Response deserializedResponse = JsonConvert.DeserializeObject<Response>(json);
  3818. Assert.AreEqual("Success", deserializedResponse.Name);
  3819. Assert.IsTrue(deserializedResponse.Data.DeepEquals(response.Data));
  3820. }
  3821. public abstract class Test<T>
  3822. {
  3823. public abstract T Value { get; set; }
  3824. }
  3825. [JsonObject(MemberSerialization.OptIn)]
  3826. public class DecimalTest : Test<decimal>
  3827. {
  3828. protected DecimalTest()
  3829. {
  3830. }
  3831. public DecimalTest(decimal val)
  3832. {
  3833. Value = val;
  3834. }
  3835. [JsonProperty]
  3836. public override decimal Value { get; set; }
  3837. }
  3838. [Test]
  3839. public void OnError()
  3840. {
  3841. var data = new DecimalTest(decimal.MinValue);
  3842. var json = JsonConvert.SerializeObject(data);
  3843. var obj = JsonConvert.DeserializeObject<DecimalTest>(json);
  3844. Assert.AreEqual(decimal.MinValue, obj.Value);
  3845. }
  3846. public class NonPublicConstructorWithJsonConstructor
  3847. {
  3848. public string Value { get; private set; }
  3849. public string Constructor { get; private set; }
  3850. [JsonConstructor]
  3851. private NonPublicConstructorWithJsonConstructor()
  3852. {
  3853. Constructor = "NonPublic";
  3854. }
  3855. public NonPublicConstructorWithJsonConstructor(string value)
  3856. {
  3857. Value = value;
  3858. Constructor = "Public Paramatized";
  3859. }
  3860. }
  3861. [Test]
  3862. public void NonPublicConstructorWithJsonConstructorTest()
  3863. {
  3864. NonPublicConstructorWithJsonConstructor c = JsonConvert.DeserializeObject<NonPublicConstructorWithJsonConstructor>("{}");
  3865. Assert.AreEqual("NonPublic", c.Constructor);
  3866. }
  3867. public class PublicConstructorOverridenByJsonConstructor
  3868. {
  3869. public string Value { get; private set; }
  3870. public string Constructor { get; private set; }
  3871. public PublicConstructorOverridenByJsonConstructor()
  3872. {
  3873. Constructor = "NonPublic";
  3874. }
  3875. [JsonConstructor]
  3876. public PublicConstructorOverridenByJsonConstructor(string value)
  3877. {
  3878. Value = value;
  3879. Constructor = "Public Paramatized";
  3880. }
  3881. }
  3882. [Test]
  3883. public void PublicConstructorOverridenByJsonConstructorTest()
  3884. {
  3885. PublicConstructorOverridenByJsonConstructor c = JsonConvert.DeserializeObject<PublicConstructorOverridenByJsonConstructor>("{Value:'value!'}");
  3886. Assert.AreEqual("Public Paramatized", c.Constructor);
  3887. Assert.AreEqual("value!", c.Value);
  3888. }
  3889. public class MultipleParamatrizedConstructorsJsonConstructor
  3890. {
  3891. public string Value { get; private set; }
  3892. public int Age { get; private set; }
  3893. public string Constructor { get; private set; }
  3894. public MultipleParamatrizedConstructorsJsonConstructor(string value)
  3895. {
  3896. Value = value;
  3897. Constructor = "Public Paramatized 1";
  3898. }
  3899. [JsonConstructor]
  3900. public MultipleParamatrizedConstructorsJsonConstructor(string value, int age)
  3901. {
  3902. Value = value;
  3903. Age = age;
  3904. Constructor = "Public Paramatized 2";
  3905. }
  3906. }
  3907. [Test]
  3908. public void MultipleParamatrizedConstructorsJsonConstructorTest()
  3909. {
  3910. MultipleParamatrizedConstructorsJsonConstructor c = JsonConvert.DeserializeObject<MultipleParamatrizedConstructorsJsonConstructor>("{Value:'value!', Age:1}");
  3911. Assert.AreEqual("Public Paramatized 2", c.Constructor);
  3912. Assert.AreEqual("value!", c.Value);
  3913. Assert.AreEqual(1, c.Age);
  3914. }
  3915. public class EnumerableClass
  3916. {
  3917. public IEnumerable<string> Enumerable { get; set; }
  3918. }
  3919. [Test]
  3920. public void DeserializeEnumerable()
  3921. {
  3922. EnumerableClass c = new EnumerableClass
  3923. {
  3924. Enumerable = new List<string> { "One", "Two", "Three" }
  3925. };
  3926. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3927. Assert.AreEqual(@"{
  3928. ""Enumerable"": [
  3929. ""One"",
  3930. ""Two"",
  3931. ""Three""
  3932. ]
  3933. }", json);
  3934. EnumerableClass c2 = JsonConvert.DeserializeObject<EnumerableClass>(json);
  3935. Assert.AreEqual("One", c2.Enumerable.ElementAt(0));
  3936. Assert.AreEqual("Two", c2.Enumerable.ElementAt(1));
  3937. Assert.AreEqual("Three", c2.Enumerable.ElementAt(2));
  3938. }
  3939. [JsonObject(MemberSerialization.OptIn)]
  3940. public class ItemBase
  3941. {
  3942. [JsonProperty]
  3943. public string Name { get; set; }
  3944. }
  3945. public class ComplexItem : ItemBase
  3946. {
  3947. public Stream Source { get; set; }
  3948. }
  3949. [Test]
  3950. public void SerializeAttributesOnBase()
  3951. {
  3952. ComplexItem i = new ComplexItem();
  3953. string json = JsonConvert.SerializeObject(i, Formatting.Indented);
  3954. Assert.AreEqual(@"{
  3955. ""Name"": null
  3956. }", json);
  3957. }
  3958. public class DeserializeStringConvert
  3959. {
  3960. public string Name { get; set; }
  3961. public int Age { get; set; }
  3962. public double Height { get; set; }
  3963. public decimal Price { get; set; }
  3964. }
  3965. [Test]
  3966. public void DeserializeStringEnglish()
  3967. {
  3968. string json = @"{
  3969. 'Name': 'James Hughes',
  3970. 'Age': '40',
  3971. 'Height': '44.4',
  3972. 'Price': '4'
  3973. }";
  3974. DeserializeStringConvert p = JsonConvert.DeserializeObject<DeserializeStringConvert>(json);
  3975. Assert.AreEqual(40, p.Age);
  3976. Assert.AreEqual(44.4, p.Height);
  3977. Assert.AreEqual(4m, p.Price);
  3978. }
  3979. [Test]
  3980. public void DeserializeNullDateTimeValueTest()
  3981. {
  3982. ExceptionAssert.Throws<JsonSerializationException>(
  3983. "Error converting value {null} to type 'System.DateTime'. Path '', line 1, position 4.",
  3984. () =>
  3985. {
  3986. JsonConvert.DeserializeObject("null", typeof(DateTime));
  3987. });
  3988. }
  3989. [Test]
  3990. public void DeserializeNullNullableDateTimeValueTest()
  3991. {
  3992. object dateTime = JsonConvert.DeserializeObject("null", typeof(DateTime?));
  3993. Assert.IsNull(dateTime);
  3994. }
  3995. [Test]
  3996. public void MultiIndexSuperTest()
  3997. {
  3998. MultiIndexSuper e = new MultiIndexSuper();
  3999. string json = JsonConvert.SerializeObject(e, Formatting.Indented);
  4000. Assert.AreEqual(@"{}", json);
  4001. }
  4002. public class MultiIndexSuper : MultiIndexBase
  4003. {
  4004. }
  4005. public abstract class MultiIndexBase
  4006. {
  4007. protected internal object this[string propertyName]
  4008. {
  4009. get { return null; }
  4010. set { }
  4011. }
  4012. protected internal object this[object property]
  4013. {
  4014. get { return null; }
  4015. set { }
  4016. }
  4017. }
  4018. public class CommentTestClass
  4019. {
  4020. public bool Indexed { get; set; }
  4021. public int StartYear { get; set; }
  4022. public IList<decimal> Values { get; set; }
  4023. }
  4024. [Test]
  4025. public void CommentTestClassTest()
  4026. {
  4027. string json = @"{""indexed"":true, ""startYear"":1939, ""values"":
  4028. [ 3000, /* 1940-1949 */
  4029. 3000, 3600, 3600, 3600, 3600, 4200, 4200, 4200, 4200, 4800, /* 1950-1959 */
  4030. 4800, 4800, 4800, 4800, 4800, 4800, 6600, 6600, 7800, 7800, /* 1960-1969 */
  4031. 7800, 7800, 9000, 10800, 13200, 14100, 15300, 16500, 17700, 22900, /* 1970-1979 */
  4032. 25900, 29700, 32400, 35700, 37800, 39600, 42000, 43800, 45000, 48000, /* 1980-1989 */
  4033. 51300, 53400, 55500, 57600, 60600, 61200, 62700, 65400, 68400, 72600, /* 1990-1999 */
  4034. 76200, 80400, 84900, 87000, 87900, 90000, 94200, 97500, 102000, 106800, /* 2000-2009 */
  4035. 106800, 106800] /* 2010-2011 */
  4036. }";
  4037. CommentTestClass commentTestClass = JsonConvert.DeserializeObject<CommentTestClass>(json);
  4038. Assert.AreEqual(true, commentTestClass.Indexed);
  4039. Assert.AreEqual(1939, commentTestClass.StartYear);
  4040. Assert.AreEqual(63, commentTestClass.Values.Count);
  4041. }
  4042. private class DTOWithParameterisedConstructor
  4043. {
  4044. public DTOWithParameterisedConstructor(string A)
  4045. {
  4046. this.A = A;
  4047. B = 2;
  4048. }
  4049. public string A { get; set; }
  4050. public int? B { get; set; }
  4051. }
  4052. private class DTOWithoutParameterisedConstructor
  4053. {
  4054. public DTOWithoutParameterisedConstructor()
  4055. {
  4056. B = 2;
  4057. }
  4058. public string A { get; set; }
  4059. public int? B { get; set; }
  4060. }
  4061. [Test]
  4062. public void PopulationBehaviourForOmittedPropertiesIsTheSameForParameterisedConstructorAsForDefaultConstructor()
  4063. {
  4064. string json = @"{A:""Test""}";
  4065. var withoutParameterisedConstructor = JsonConvert.DeserializeObject<DTOWithoutParameterisedConstructor>(json);
  4066. var withParameterisedConstructor = JsonConvert.DeserializeObject<DTOWithParameterisedConstructor>(json);
  4067. Assert.AreEqual(withoutParameterisedConstructor.B, withParameterisedConstructor.B);
  4068. }
  4069. public class EnumerableArrayPropertyClass
  4070. {
  4071. public IEnumerable<int> Numbers
  4072. {
  4073. get
  4074. {
  4075. return new[] { 1, 2, 3 }; //fails
  4076. //return new List<int>(new[] { 1, 2, 3 }); //works
  4077. }
  4078. }
  4079. }
  4080. [Test]
  4081. public void SkipPopulatingArrayPropertyClass()
  4082. {
  4083. string json = JsonConvert.SerializeObject(new EnumerableArrayPropertyClass());
  4084. JsonConvert.DeserializeObject<EnumerableArrayPropertyClass>(json);
  4085. }
  4086. #if !NET20
  4087. [DataContract]
  4088. public class BaseDataContract
  4089. {
  4090. [DataMember(Name = "virtualMember")]
  4091. public virtual string VirtualMember { get; set; }
  4092. [DataMember(Name = "nonVirtualMember")]
  4093. public string NonVirtualMember { get; set; }
  4094. }
  4095. public class ChildDataContract : BaseDataContract
  4096. {
  4097. public override string VirtualMember { get; set; }
  4098. public string NewMember { get; set; }
  4099. }
  4100. [Test]
  4101. public void ChildDataContractTest()
  4102. {
  4103. ChildDataContract cc = new ChildDataContract
  4104. {
  4105. VirtualMember = "VirtualMember!",
  4106. NonVirtualMember = "NonVirtualMember!"
  4107. };
  4108. string result = JsonConvert.SerializeObject(cc);
  4109. Assert.AreEqual(@"{""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  4110. }
  4111. #endif
  4112. [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
  4113. public class BaseObject
  4114. {
  4115. [JsonProperty(PropertyName = "virtualMember")]
  4116. public virtual string VirtualMember { get; set; }
  4117. [JsonProperty(PropertyName = "nonVirtualMember")]
  4118. public string NonVirtualMember { get; set; }
  4119. }
  4120. public class ChildObject : BaseObject
  4121. {
  4122. public override string VirtualMember { get; set; }
  4123. public string NewMember { get; set; }
  4124. }
  4125. public class ChildWithDifferentOverrideObject : BaseObject
  4126. {
  4127. [JsonProperty(PropertyName = "differentVirtualMember")]
  4128. public override string VirtualMember { get; set; }
  4129. }
  4130. [Test]
  4131. public void ChildObjectTest()
  4132. {
  4133. ChildObject cc = new ChildObject
  4134. {
  4135. VirtualMember = "VirtualMember!",
  4136. NonVirtualMember = "NonVirtualMember!"
  4137. };
  4138. string result = JsonConvert.SerializeObject(cc);
  4139. Assert.AreEqual(@"{""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  4140. }
  4141. [Test]
  4142. public void ChildWithDifferentOverrideObjectTest()
  4143. {
  4144. ChildWithDifferentOverrideObject cc = new ChildWithDifferentOverrideObject
  4145. {
  4146. VirtualMember = "VirtualMember!",
  4147. NonVirtualMember = "NonVirtualMember!"
  4148. };
  4149. string result = JsonConvert.SerializeObject(cc);
  4150. Assert.AreEqual(@"{""differentVirtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  4151. }
  4152. [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
  4153. public interface IInterfaceObject
  4154. {
  4155. [JsonProperty(PropertyName = "virtualMember")]
  4156. [JsonConverter(typeof(IsoDateTimeConverter))]
  4157. DateTime InterfaceMember { get; set; }
  4158. }
  4159. public class ImplementInterfaceObject : IInterfaceObject
  4160. {
  4161. public DateTime InterfaceMember { get; set; }
  4162. public string NewMember { get; set; }
  4163. [JsonProperty(PropertyName = "newMemberWithProperty")]
  4164. public string NewMemberWithProperty { get; set; }
  4165. }
  4166. [Test]
  4167. public void ImplementInterfaceObjectTest()
  4168. {
  4169. ImplementInterfaceObject cc = new ImplementInterfaceObject
  4170. {
  4171. InterfaceMember = new DateTime(2010, 12, 31, 0, 0, 0, DateTimeKind.Utc),
  4172. NewMember = "NewMember!"
  4173. };
  4174. string result = JsonConvert.SerializeObject(cc, Formatting.Indented);
  4175. Assert.AreEqual(@"{
  4176. ""virtualMember"": ""2010-12-31T00:00:00Z"",
  4177. ""newMemberWithProperty"": null
  4178. }", result);
  4179. }
  4180. public class NonDefaultConstructorWithReadOnlyCollectionProperty
  4181. {
  4182. public string Title { get; set; }
  4183. public IList<string> Categories { get; private set; }
  4184. public NonDefaultConstructorWithReadOnlyCollectionProperty(string title)
  4185. {
  4186. Title = title;
  4187. Categories = new List<string>();
  4188. }
  4189. }
  4190. [Test]
  4191. public void NonDefaultConstructorWithReadOnlyCollectionPropertyTest()
  4192. {
  4193. NonDefaultConstructorWithReadOnlyCollectionProperty c1 = new NonDefaultConstructorWithReadOnlyCollectionProperty("blah");
  4194. c1.Categories.Add("one");
  4195. c1.Categories.Add("two");
  4196. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4197. Assert.AreEqual(@"{
  4198. ""Title"": ""blah"",
  4199. ""Categories"": [
  4200. ""one"",
  4201. ""two""
  4202. ]
  4203. }", json);
  4204. NonDefaultConstructorWithReadOnlyCollectionProperty c2 = JsonConvert.DeserializeObject<NonDefaultConstructorWithReadOnlyCollectionProperty>(json);
  4205. Assert.AreEqual(c1.Title, c2.Title);
  4206. Assert.AreEqual(c1.Categories.Count, c2.Categories.Count);
  4207. Assert.AreEqual("one", c2.Categories[0]);
  4208. Assert.AreEqual("two", c2.Categories[1]);
  4209. }
  4210. public class NonDefaultConstructorWithReadOnlyDictionaryProperty
  4211. {
  4212. public string Title { get; set; }
  4213. public IDictionary<string, int> Categories { get; private set; }
  4214. public NonDefaultConstructorWithReadOnlyDictionaryProperty(string title)
  4215. {
  4216. Title = title;
  4217. Categories = new Dictionary<string, int>();
  4218. }
  4219. }
  4220. [Test]
  4221. public void NonDefaultConstructorWithReadOnlyDictionaryPropertyTest()
  4222. {
  4223. NonDefaultConstructorWithReadOnlyDictionaryProperty c1 = new NonDefaultConstructorWithReadOnlyDictionaryProperty("blah");
  4224. c1.Categories.Add("one", 1);
  4225. c1.Categories.Add("two", 2);
  4226. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4227. Assert.AreEqual(@"{
  4228. ""Title"": ""blah"",
  4229. ""Categories"": {
  4230. ""one"": 1,
  4231. ""two"": 2
  4232. }
  4233. }", json);
  4234. NonDefaultConstructorWithReadOnlyDictionaryProperty c2 = JsonConvert.DeserializeObject<NonDefaultConstructorWithReadOnlyDictionaryProperty>(json);
  4235. Assert.AreEqual(c1.Title, c2.Title);
  4236. Assert.AreEqual(c1.Categories.Count, c2.Categories.Count);
  4237. Assert.AreEqual(1, c2.Categories["one"]);
  4238. Assert.AreEqual(2, c2.Categories["two"]);
  4239. }
  4240. [JsonObject(MemberSerialization.OptIn)]
  4241. public class ClassAttributeBase
  4242. {
  4243. [JsonProperty]
  4244. public string BaseClassValue { get; set; }
  4245. }
  4246. public class ClassAttributeDerived : ClassAttributeBase
  4247. {
  4248. [JsonProperty]
  4249. public string DerivedClassValue { get; set; }
  4250. public string NonSerialized { get; set; }
  4251. }
  4252. public class CollectionClassAttributeDerived : ClassAttributeBase, ICollection<object>
  4253. {
  4254. [JsonProperty]
  4255. public string CollectionDerivedClassValue { get; set; }
  4256. public void Add(object item)
  4257. {
  4258. throw new NotImplementedException();
  4259. }
  4260. public void Clear()
  4261. {
  4262. throw new NotImplementedException();
  4263. }
  4264. public bool Contains(object item)
  4265. {
  4266. throw new NotImplementedException();
  4267. }
  4268. public void CopyTo(object[] array, int arrayIndex)
  4269. {
  4270. throw new NotImplementedException();
  4271. }
  4272. public int Count
  4273. {
  4274. get { throw new NotImplementedException(); }
  4275. }
  4276. public bool IsReadOnly
  4277. {
  4278. get { throw new NotImplementedException(); }
  4279. }
  4280. public bool Remove(object item)
  4281. {
  4282. throw new NotImplementedException();
  4283. }
  4284. public IEnumerator<object> GetEnumerator()
  4285. {
  4286. throw new NotImplementedException();
  4287. }
  4288. IEnumerator IEnumerable.GetEnumerator()
  4289. {
  4290. throw new NotImplementedException();
  4291. }
  4292. }
  4293. [Test]
  4294. public void ClassAttributesInheritance()
  4295. {
  4296. string json = JsonConvert.SerializeObject(new ClassAttributeDerived
  4297. {
  4298. BaseClassValue = "BaseClassValue!",
  4299. DerivedClassValue = "DerivedClassValue!",
  4300. NonSerialized = "NonSerialized!"
  4301. }, Formatting.Indented);
  4302. Assert.AreEqual(@"{
  4303. ""DerivedClassValue"": ""DerivedClassValue!"",
  4304. ""BaseClassValue"": ""BaseClassValue!""
  4305. }", json);
  4306. json = JsonConvert.SerializeObject(new CollectionClassAttributeDerived
  4307. {
  4308. BaseClassValue = "BaseClassValue!",
  4309. CollectionDerivedClassValue = "CollectionDerivedClassValue!"
  4310. }, Formatting.Indented);
  4311. Assert.AreEqual(@"{
  4312. ""CollectionDerivedClassValue"": ""CollectionDerivedClassValue!"",
  4313. ""BaseClassValue"": ""BaseClassValue!""
  4314. }", json);
  4315. }
  4316. public class PrivateMembersClassWithAttributes
  4317. {
  4318. public PrivateMembersClassWithAttributes(string privateString, string internalString, string readonlyString)
  4319. {
  4320. _privateString = privateString;
  4321. _readonlyString = readonlyString;
  4322. _internalString = internalString;
  4323. }
  4324. public PrivateMembersClassWithAttributes()
  4325. {
  4326. _readonlyString = "default!";
  4327. }
  4328. [JsonProperty]
  4329. private string _privateString;
  4330. [JsonProperty]
  4331. private readonly string _readonlyString;
  4332. [JsonProperty]
  4333. internal string _internalString;
  4334. public string UseValue()
  4335. {
  4336. return _readonlyString;
  4337. }
  4338. }
  4339. [Test]
  4340. public void PrivateMembersClassWithAttributesTest()
  4341. {
  4342. PrivateMembersClassWithAttributes c1 = new PrivateMembersClassWithAttributes("privateString!", "internalString!", "readonlyString!");
  4343. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4344. Assert.AreEqual(@"{
  4345. ""_privateString"": ""privateString!"",
  4346. ""_readonlyString"": ""readonlyString!"",
  4347. ""_internalString"": ""internalString!""
  4348. }", json);
  4349. PrivateMembersClassWithAttributes c2 = JsonConvert.DeserializeObject<PrivateMembersClassWithAttributes>(json);
  4350. Assert.AreEqual("readonlyString!", c2.UseValue());
  4351. }
  4352. public partial class BusRun
  4353. {
  4354. public IEnumerable<Nullable<DateTime>> Departures { get; set; }
  4355. public Boolean WheelchairAccessible { get; set; }
  4356. }
  4357. [Test]
  4358. public void DeserializeGenericEnumerableProperty()
  4359. {
  4360. BusRun r = JsonConvert.DeserializeObject<BusRun>("{\"Departures\":[\"\\/Date(1309874148734-0400)\\/\",\"\\/Date(1309874148739-0400)\\/\",null],\"WheelchairAccessible\":true}");
  4361. Assert.AreEqual(3, r.Departures.Count());
  4362. Assert.IsNotNull(r.Departures.ElementAt(0));
  4363. Assert.IsNotNull(r.Departures.ElementAt(1));
  4364. Assert.IsNull(r.Departures.ElementAt(2));
  4365. }
  4366. #if !(NET20)
  4367. [DataContract]
  4368. public class BaseType
  4369. {
  4370. [DataMember]
  4371. public string zebra;
  4372. }
  4373. [DataContract]
  4374. public class DerivedType : BaseType
  4375. {
  4376. [DataMember(Order = 0)]
  4377. public string bird;
  4378. [DataMember(Order = 1)]
  4379. public string parrot;
  4380. [DataMember]
  4381. public string dog;
  4382. [DataMember(Order = 3)]
  4383. public string antelope;
  4384. [DataMember]
  4385. public string cat;
  4386. [JsonProperty(Order = 1)]
  4387. public string albatross;
  4388. [JsonProperty(Order = -2)]
  4389. public string dinosaur;
  4390. }
  4391. [Test]
  4392. public void JsonPropertyDataMemberOrder()
  4393. {
  4394. DerivedType d = new DerivedType();
  4395. string json = JsonConvert.SerializeObject(d, Formatting.Indented);
  4396. Assert.AreEqual(@"{
  4397. ""dinosaur"": null,
  4398. ""dog"": null,
  4399. ""cat"": null,
  4400. ""zebra"": null,
  4401. ""bird"": null,
  4402. ""parrot"": null,
  4403. ""albatross"": null,
  4404. ""antelope"": null
  4405. }", json);
  4406. }
  4407. #endif
  4408. public class ClassWithException
  4409. {
  4410. public IList<Exception> Exceptions { get; set; }
  4411. public ClassWithException()
  4412. {
  4413. Exceptions = new List<Exception>();
  4414. }
  4415. }
  4416. #if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE)
  4417. [Test]
  4418. public void SerializeException1()
  4419. {
  4420. ClassWithException classWithException = new ClassWithException();
  4421. try
  4422. {
  4423. throw new Exception("Test Exception");
  4424. }
  4425. catch (Exception ex)
  4426. {
  4427. classWithException.Exceptions.Add(ex);
  4428. }
  4429. string sex = JsonConvert.SerializeObject(classWithException);
  4430. ClassWithException dex = JsonConvert.DeserializeObject<ClassWithException>(sex);
  4431. Assert.AreEqual(dex.Exceptions[0].ToString(), dex.Exceptions[0].ToString());
  4432. sex = JsonConvert.SerializeObject(classWithException, Formatting.Indented);
  4433. dex = JsonConvert.DeserializeObject<ClassWithException>(sex); // this fails!
  4434. Assert.AreEqual(dex.Exceptions[0].ToString(), dex.Exceptions[0].ToString());
  4435. }
  4436. #endif
  4437. public void DeserializeIDictionary()
  4438. {
  4439. IDictionary dictionary = JsonConvert.DeserializeObject<IDictionary>("{'name':'value!'}");
  4440. Assert.AreEqual(1, dictionary.Count);
  4441. Assert.AreEqual("value!", dictionary["name"]);
  4442. }
  4443. public void DeserializeIList()
  4444. {
  4445. IList list = JsonConvert.DeserializeObject<IList>("['1', 'two', 'III']");
  4446. Assert.AreEqual(3, list.Count);
  4447. }
  4448. public void UriGuidTimeSpanTestClassEmptyTest()
  4449. {
  4450. UriGuidTimeSpanTestClass c1 = new UriGuidTimeSpanTestClass();
  4451. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4452. Assert.AreEqual(@"{
  4453. ""Guid"": ""00000000-0000-0000-0000-000000000000"",
  4454. ""NullableGuid"": null,
  4455. ""TimeSpan"": ""00:00:00"",
  4456. ""NullableTimeSpan"": null,
  4457. ""Uri"": null
  4458. }", json);
  4459. UriGuidTimeSpanTestClass c2 = JsonConvert.DeserializeObject<UriGuidTimeSpanTestClass>(json);
  4460. Assert.AreEqual(c1.Guid, c2.Guid);
  4461. Assert.AreEqual(c1.NullableGuid, c2.NullableGuid);
  4462. Assert.AreEqual(c1.TimeSpan, c2.TimeSpan);
  4463. Assert.AreEqual(c1.NullableTimeSpan, c2.NullableTimeSpan);
  4464. Assert.AreEqual(c1.Uri, c2.Uri);
  4465. }
  4466. public void UriGuidTimeSpanTestClassValuesTest()
  4467. {
  4468. UriGuidTimeSpanTestClass c1 = new UriGuidTimeSpanTestClass
  4469. {
  4470. Guid = new Guid("1924129C-F7E0-40F3-9607-9939C531395A"),
  4471. NullableGuid = new Guid("9E9F3ADF-E017-4F72-91E0-617EBE85967D"),
  4472. TimeSpan = TimeSpan.FromDays(1),
  4473. NullableTimeSpan = TimeSpan.FromHours(1),
  4474. Uri = new Uri("http://testuri.com")
  4475. };
  4476. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4477. Assert.AreEqual(@"{
  4478. ""Guid"": ""1924129c-f7e0-40f3-9607-9939c531395a"",
  4479. ""NullableGuid"": ""9e9f3adf-e017-4f72-91e0-617ebe85967d"",
  4480. ""TimeSpan"": ""1.00:00:00"",
  4481. ""NullableTimeSpan"": ""01:00:00"",
  4482. ""Uri"": ""http://testuri.com/""
  4483. }", json);
  4484. UriGuidTimeSpanTestClass c2 = JsonConvert.DeserializeObject<UriGuidTimeSpanTestClass>(json);
  4485. Assert.AreEqual(c1.Guid, c2.Guid);
  4486. Assert.AreEqual(c1.NullableGuid, c2.NullableGuid);
  4487. Assert.AreEqual(c1.TimeSpan, c2.TimeSpan);
  4488. Assert.AreEqual(c1.NullableTimeSpan, c2.NullableTimeSpan);
  4489. Assert.AreEqual(c1.Uri, c2.Uri);
  4490. }
  4491. [Test]
  4492. public void NullableValueGenericDictionary()
  4493. {
  4494. IDictionary<string, int?> v1 = new Dictionary<string, int?>
  4495. {
  4496. {"First", 1},
  4497. {"Second", null},
  4498. {"Third", 3}
  4499. };
  4500. string json = JsonConvert.SerializeObject(v1, Formatting.Indented);
  4501. Assert.AreEqual(@"{
  4502. ""First"": 1,
  4503. ""Second"": null,
  4504. ""Third"": 3
  4505. }", json);
  4506. IDictionary<string, int?> v2 = JsonConvert.DeserializeObject<IDictionary<string, int?>>(json);
  4507. Assert.AreEqual(3, v2.Count);
  4508. Assert.AreEqual(1, v2["First"]);
  4509. Assert.AreEqual(null, v2["Second"]);
  4510. Assert.AreEqual(3, v2["Third"]);
  4511. }
  4512. [Test]
  4513. public void UsingJsonTextWriter()
  4514. {
  4515. // The property of the object has to be a number for the cast exception to occure
  4516. object o = new { p = 1 };
  4517. var json = JObject.FromObject(o);
  4518. using (var sw = new StringWriter())
  4519. using (var jw = new JsonTextWriter(sw))
  4520. {
  4521. jw.WriteToken(json.CreateReader());
  4522. jw.Flush();
  4523. string result = sw.ToString();
  4524. Assert.AreEqual(@"{""p"":1}", result);
  4525. }
  4526. }
  4527. #if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE)
  4528. [Test]
  4529. public void DeserializeConcurrentDictionary()
  4530. {
  4531. IDictionary<string, Component> components = new Dictionary<string, Component>
  4532. {
  4533. {"Key!", new Component()}
  4534. };
  4535. GameObject go = new GameObject
  4536. {
  4537. Components = new ConcurrentDictionary<string, Component>(components),
  4538. Id = "Id!",
  4539. Name = "Name!"
  4540. };
  4541. string originalJson = JsonConvert.SerializeObject(go, Formatting.Indented);
  4542. Assert.AreEqual(@"{
  4543. ""Components"": {
  4544. ""Key!"": {}
  4545. },
  4546. ""Id"": ""Id!"",
  4547. ""Name"": ""Name!""
  4548. }", originalJson);
  4549. GameObject newObject = JsonConvert.DeserializeObject<GameObject>(originalJson);
  4550. Assert.AreEqual(1, newObject.Components.Count);
  4551. Assert.AreEqual("Id!", newObject.Id);
  4552. Assert.AreEqual("Name!", newObject.Name);
  4553. }
  4554. #endif
  4555. [Test]
  4556. public void DeserializeKeyValuePairArray()
  4557. {
  4558. string json = @"[ { ""Value"": [ ""1"", ""2"" ], ""Key"": ""aaa"", ""BadContent"": [ 0 ] }, { ""Value"": [ ""3"", ""4"" ], ""Key"": ""bbb"" } ]";
  4559. IList<KeyValuePair<string, IList<string>>> values = JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json);
  4560. Assert.AreEqual(2, values.Count);
  4561. Assert.AreEqual("aaa", values[0].Key);
  4562. Assert.AreEqual(2, values[0].Value.Count);
  4563. Assert.AreEqual("1", values[0].Value[0]);
  4564. Assert.AreEqual("2", values[0].Value[1]);
  4565. Assert.AreEqual("bbb", values[1].Key);
  4566. Assert.AreEqual(2, values[1].Value.Count);
  4567. Assert.AreEqual("3", values[1].Value[0]);
  4568. Assert.AreEqual("4", values[1].Value[1]);
  4569. }
  4570. [Test]
  4571. public void DeserializeNullableKeyValuePairArray()
  4572. {
  4573. string json = @"[ { ""Value"": [ ""1"", ""2"" ], ""Key"": ""aaa"", ""BadContent"": [ 0 ] }, null, { ""Value"": [ ""3"", ""4"" ], ""Key"": ""bbb"" } ]";
  4574. IList<KeyValuePair<string, IList<string>>?> values = JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>?>>(json);
  4575. Assert.AreEqual(3, values.Count);
  4576. Assert.AreEqual("aaa", values[0].Value.Key);
  4577. Assert.AreEqual(2, values[0].Value.Value.Count);
  4578. Assert.AreEqual("1", values[0].Value.Value[0]);
  4579. Assert.AreEqual("2", values[0].Value.Value[1]);
  4580. Assert.AreEqual(null, values[1]);
  4581. Assert.AreEqual("bbb", values[2].Value.Key);
  4582. Assert.AreEqual(2, values[2].Value.Value.Count);
  4583. Assert.AreEqual("3", values[2].Value.Value[0]);
  4584. Assert.AreEqual("4", values[2].Value.Value[1]);
  4585. }
  4586. [Test]
  4587. public void DeserializeNullToNonNullableKeyValuePairArray()
  4588. {
  4589. string json = @"[ null ]";
  4590. ExceptionAssert.Throws<JsonSerializationException>(
  4591. "Cannot convert null value to KeyValuePair. Path '[0]', line 1, position 6.",
  4592. () =>
  4593. {
  4594. JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json);
  4595. });
  4596. }
  4597. [Test]
  4598. public void SerializeUriWithQuotes()
  4599. {
  4600. string input = "http://test.com/%22foo+bar%22";
  4601. Uri uri = new Uri(input);
  4602. string json = JsonConvert.SerializeObject(uri);
  4603. Uri output = JsonConvert.DeserializeObject<Uri>(json);
  4604. Assert.AreEqual(uri, output);
  4605. }
  4606. [Test]
  4607. public void SerializeUriWithSlashes()
  4608. {
  4609. string input = @"http://tes/?a=b\\c&d=e\";
  4610. Uri uri = new Uri(input);
  4611. string json = JsonConvert.SerializeObject(uri);
  4612. Uri output = JsonConvert.DeserializeObject<Uri>(json);
  4613. Assert.AreEqual(uri, output);
  4614. }
  4615. [Test]
  4616. public void DeserializeByteArrayWithTypeNameHandling()
  4617. {
  4618. TestObject test = new TestObject("Test", new byte[] { 72, 63, 62, 71, 92, 55 });
  4619. JsonSerializer serializer = new JsonSerializer();
  4620. serializer.TypeNameHandling = TypeNameHandling.All;
  4621. byte[] objectBytes;
  4622. using (MemoryStream bsonStream = new MemoryStream())
  4623. using (JsonWriter bsonWriter = new JsonTextWriter(new StreamWriter(bsonStream)))
  4624. {
  4625. serializer.Serialize(bsonWriter, test);
  4626. bsonWriter.Flush();
  4627. objectBytes = bsonStream.ToArray();
  4628. }
  4629. using (MemoryStream bsonStream = new MemoryStream(objectBytes))
  4630. using (JsonReader bsonReader = new JsonTextReader(new StreamReader(bsonStream)))
  4631. {
  4632. // Get exception here
  4633. TestObject newObject = (TestObject)serializer.Deserialize(bsonReader);
  4634. Assert.AreEqual("Test", newObject.Name);
  4635. CollectionAssert.AreEquivalent(new byte[] { 72, 63, 62, 71, 92, 55 }, newObject.Data);
  4636. }
  4637. }
  4638. #if !(SILVERLIGHT || WINDOWS_PHONE || NET20 || NETFX_CORE)
  4639. [Test]
  4640. public void DeserializeDecimalsWithCulture()
  4641. {
  4642. CultureInfo initialCulture = Thread.CurrentThread.CurrentCulture;
  4643. try
  4644. {
  4645. CultureInfo testCulture = CultureInfo.CreateSpecificCulture("nb-NO");
  4646. Thread.CurrentThread.CurrentCulture = testCulture;
  4647. Thread.CurrentThread.CurrentUICulture = testCulture;
  4648. string json = @"{ 'Quantity': '1.5', 'OptionalQuantity': '2.2' }";
  4649. DecimalTestClass c = JsonConvert.DeserializeObject<DecimalTestClass>(json);
  4650. Assert.AreEqual(1.5m, c.Quantity);
  4651. Assert.AreEqual(2.2d, c.OptionalQuantity);
  4652. }
  4653. finally
  4654. {
  4655. Thread.CurrentThread.CurrentCulture = initialCulture;
  4656. Thread.CurrentThread.CurrentUICulture = initialCulture;
  4657. }
  4658. }
  4659. #endif
  4660. [Test]
  4661. public void ReadForTypeHackFixDecimal()
  4662. {
  4663. IList<decimal> d1 = new List<decimal> { 1.1m };
  4664. string json = JsonConvert.SerializeObject(d1);
  4665. IList<decimal> d2 = JsonConvert.DeserializeObject<IList<decimal>>(json);
  4666. Assert.AreEqual(d1.Count, d2.Count);
  4667. Assert.AreEqual(d1[0], d2[0]);
  4668. }
  4669. [Test]
  4670. public void ReadForTypeHackFixDateTimeOffset()
  4671. {
  4672. IList<DateTimeOffset?> d1 = new List<DateTimeOffset?> { null };
  4673. string json = JsonConvert.SerializeObject(d1);
  4674. IList<DateTimeOffset?> d2 = JsonConvert.DeserializeObject<IList<DateTimeOffset?>>(json);
  4675. Assert.AreEqual(d1.Count, d2.Count);
  4676. Assert.AreEqual(d1[0], d2[0]);
  4677. }
  4678. [Test]
  4679. public void ReadForTypeHackFixByteArray()
  4680. {
  4681. IList<byte[]> d1 = new List<byte[]> { null };
  4682. string json = JsonConvert.SerializeObject(d1);
  4683. IList<byte[]> d2 = JsonConvert.DeserializeObject<IList<byte[]>>(json);
  4684. Assert.AreEqual(d1.Count, d2.Count);
  4685. Assert.AreEqual(d1[0], d2[0]);
  4686. }
  4687. [Test]
  4688. public void SerializeInheritanceHierarchyWithDuplicateProperty()
  4689. {
  4690. Bb b = new Bb();
  4691. b.no = true;
  4692. Aa a = b;
  4693. a.no = int.MaxValue;
  4694. string json = JsonConvert.SerializeObject(b);
  4695. Assert.AreEqual(@"{""no"":true}", json);
  4696. Bb b2 = JsonConvert.DeserializeObject<Bb>(json);
  4697. Assert.AreEqual(true, b2.no);
  4698. }
  4699. [Test]
  4700. public void DeserializeNullInt()
  4701. {
  4702. string json = @"[
  4703. 1,
  4704. 2,
  4705. 3,
  4706. null
  4707. ]";
  4708. ExceptionAssert.Throws<JsonSerializationException>(
  4709. "Error converting value {null} to type 'System.Int32'. Path '[3]', line 5, position 7.",
  4710. () =>
  4711. {
  4712. List<int> numbers = JsonConvert.DeserializeObject<List<int>>(json);
  4713. });
  4714. }
  4715. [Test]
  4716. public void SerializeNullableWidgetStruct()
  4717. {
  4718. Widget widget = new Widget { Id = new WidgetId { Value = "id" } };
  4719. string json = JsonConvert.SerializeObject(widget);
  4720. Assert.AreEqual(@"{""Id"":{""Value"":""id""}}", json);
  4721. }
  4722. [Test]
  4723. public void DeserializeNullableWidgetStruct()
  4724. {
  4725. string json = @"{""Id"":{""Value"":""id""}}";
  4726. Widget w = JsonConvert.DeserializeObject<Widget>(json);
  4727. Assert.AreEqual(new WidgetId { Value = "id" }, w.Id);
  4728. Assert.AreEqual(new WidgetId { Value = "id" }, w.Id.Value);
  4729. Assert.AreEqual("id", w.Id.Value.Value);
  4730. }
  4731. [Test]
  4732. public void DeserializeBoolInt()
  4733. {
  4734. ExceptionAssert.Throws<JsonReaderException>(
  4735. "Error reading integer. Unexpected token: Boolean. Path 'PreProperty', line 2, position 22.",
  4736. () =>
  4737. {
  4738. string json = @"{
  4739. ""PreProperty"": true,
  4740. ""PostProperty"": ""-1""
  4741. }";
  4742. JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
  4743. });
  4744. }
  4745. [Test]
  4746. public void DeserializeUnexpectedEndInt()
  4747. {
  4748. ExceptionAssert.Throws<JsonSerializationException>(
  4749. "Unexpected end when setting PreProperty's value. Path 'PreProperty', line 2, position 18.",
  4750. () =>
  4751. {
  4752. string json = @"{
  4753. ""PreProperty"": ";
  4754. JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
  4755. });
  4756. }
  4757. [Test]
  4758. public void DeserializeNullableGuid()
  4759. {
  4760. string json = @"{""Id"":null}";
  4761. var c = JsonConvert.DeserializeObject<NullableGuid>(json);
  4762. Assert.AreEqual(null, c.Id);
  4763. json = @"{""Id"":""d8220a4b-75b1-4b7a-8112-b7bdae956a45""}";
  4764. c = JsonConvert.DeserializeObject<NullableGuid>(json);
  4765. Assert.AreEqual(new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"), c.Id);
  4766. }
  4767. [Test]
  4768. public void DeserializeGuid()
  4769. {
  4770. Item expected = new Item()
  4771. {
  4772. SourceTypeID = new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"),
  4773. BrokerID = new Guid("951663c4-924e-4c86-a57a-7ed737501dbd"),
  4774. Latitude = 33.657145,
  4775. Longitude = -117.766684,
  4776. TimeStamp = new DateTime(2000, 3, 1, 23, 59, 59, DateTimeKind.Utc),
  4777. Payload = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
  4778. };
  4779. string jsonString = JsonConvert.SerializeObject(expected, Formatting.Indented);
  4780. Assert.AreEqual(@"{
  4781. ""SourceTypeID"": ""d8220a4b-75b1-4b7a-8112-b7bdae956a45"",
  4782. ""BrokerID"": ""951663c4-924e-4c86-a57a-7ed737501dbd"",
  4783. ""Latitude"": 33.657145,
  4784. ""Longitude"": -117.766684,
  4785. ""TimeStamp"": ""2000-03-01T23:59:59Z"",
  4786. ""Payload"": {
  4787. ""$type"": ""System.Byte[], mscorlib"",
  4788. ""$value"": ""AAECAwQFBgcICQ==""
  4789. }
  4790. }", jsonString);
  4791. Item actual = JsonConvert.DeserializeObject<Item>(jsonString);
  4792. Assert.AreEqual(new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"), actual.SourceTypeID);
  4793. Assert.AreEqual(new Guid("951663c4-924e-4c86-a57a-7ed737501dbd"), actual.BrokerID);
  4794. byte[] bytes = (byte[])actual.Payload;
  4795. CollectionAssert.AreEquivalent((new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }).ToList(), bytes.ToList());
  4796. }
  4797. [Test]
  4798. public void DeserializeObjectDictionary()
  4799. {
  4800. var serializer = JsonSerializer.Create(new JsonSerializerSettings());
  4801. var dict = serializer.Deserialize<Dictionary<string, string>>(new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}")));
  4802. Assert.AreEqual("", dict["k1"]);
  4803. Assert.AreEqual("v2", dict["k2"]);
  4804. }
  4805. [Test]
  4806. public void DeserializeNullableEnum()
  4807. {
  4808. string json = JsonConvert.SerializeObject(new WithEnums
  4809. {
  4810. Id = 7,
  4811. NullableEnum = null
  4812. });
  4813. Assert.AreEqual(@"{""Id"":7,""NullableEnum"":null}", json);
  4814. WithEnums e = JsonConvert.DeserializeObject<WithEnums>(json);
  4815. Assert.AreEqual(null, e.NullableEnum);
  4816. json = JsonConvert.SerializeObject(new WithEnums
  4817. {
  4818. Id = 7,
  4819. NullableEnum = MyEnum.Value2
  4820. });
  4821. Assert.AreEqual(@"{""Id"":7,""NullableEnum"":1}", json);
  4822. e = JsonConvert.DeserializeObject<WithEnums>(json);
  4823. Assert.AreEqual(MyEnum.Value2, e.NullableEnum);
  4824. }
  4825. [Test]
  4826. public void NullableStructWithConverter()
  4827. {
  4828. string json = JsonConvert.SerializeObject(new Widget1 { Id = new WidgetId1 { Value = 1234 } });
  4829. Assert.AreEqual(@"{""Id"":""1234""}", json);
  4830. Widget1 w = JsonConvert.DeserializeObject<Widget1>(@"{""Id"":""1234""}");
  4831. Assert.AreEqual(new WidgetId1 { Value = 1234 }, w.Id);
  4832. }
  4833. [Test]
  4834. public void SerializeDictionaryStringStringAndStringObject()
  4835. {
  4836. var serializer = JsonSerializer.Create(new JsonSerializerSettings());
  4837. var dict = serializer.Deserialize<Dictionary<string, string>>(new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}")));
  4838. var reader = new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}"));
  4839. var dict2 = serializer.Deserialize<Dictionary<string, object>>(reader);
  4840. Assert.AreEqual(dict["k1"], dict2["k1"]);
  4841. }
  4842. [Test]
  4843. public void DeserializeEmptyStrings()
  4844. {
  4845. object v = JsonConvert.DeserializeObject<double?>("");
  4846. Assert.IsNull(v);
  4847. v = JsonConvert.DeserializeObject<char?>("");
  4848. Assert.IsNull(v);
  4849. v = JsonConvert.DeserializeObject<int?>("");
  4850. Assert.IsNull(v);
  4851. v = JsonConvert.DeserializeObject<decimal?>("");
  4852. Assert.IsNull(v);
  4853. v = JsonConvert.DeserializeObject<DateTime?>("");
  4854. Assert.IsNull(v);
  4855. v = JsonConvert.DeserializeObject<DateTimeOffset?>("");
  4856. Assert.IsNull(v);
  4857. v = JsonConvert.DeserializeObject<byte[]>("");
  4858. Assert.IsNull(v);
  4859. }
  4860. public class Sdfsdf
  4861. {
  4862. public double Id { get; set; }
  4863. }
  4864. [Test]
  4865. public void DeserializeDoubleFromEmptyString()
  4866. {
  4867. ExceptionAssert.Throws<JsonSerializationException>(
  4868. "No JSON content found and type 'System.Double' is not nullable. Path '', line 0, position 0.",
  4869. () =>
  4870. {
  4871. JsonConvert.DeserializeObject<double>("");
  4872. });
  4873. }
  4874. [Test]
  4875. public void DeserializeEnumFromEmptyString()
  4876. {
  4877. ExceptionAssert.Throws<JsonSerializationException>(
  4878. "No JSON content found and type 'System.StringComparison' is not nullable. Path '', line 0, position 0.",
  4879. () =>
  4880. {
  4881. JsonConvert.DeserializeObject<StringComparison>("");
  4882. });
  4883. }
  4884. [Test]
  4885. public void DeserializeInt32FromEmptyString()
  4886. {
  4887. ExceptionAssert.Throws<JsonSerializationException>(
  4888. "No JSON content found and type 'System.Int32' is not nullable. Path '', line 0, position 0.",
  4889. () =>
  4890. {
  4891. JsonConvert.DeserializeObject<int>("");
  4892. });
  4893. }
  4894. [Test]
  4895. public void DeserializeByteArrayFromEmptyString()
  4896. {
  4897. byte[] b = JsonConvert.DeserializeObject<byte[]>("");
  4898. Assert.IsNull(b);
  4899. }
  4900. [Test]
  4901. public void DeserializeDoubleFromNullString()
  4902. {
  4903. ExceptionAssert.Throws<ArgumentNullException>(
  4904. @"Value cannot be null.
  4905. Parameter name: value",
  4906. () =>
  4907. {
  4908. JsonConvert.DeserializeObject<double>(null);
  4909. });
  4910. }
  4911. [Test]
  4912. public void DeserializeFromNullString()
  4913. {
  4914. ExceptionAssert.Throws<ArgumentNullException>(
  4915. @"Value cannot be null.
  4916. Parameter name: value",
  4917. () =>
  4918. {
  4919. JsonConvert.DeserializeObject(null);
  4920. });
  4921. }
  4922. [Test]
  4923. public void DeserializeIsoDatesWithIsoConverter()
  4924. {
  4925. string jsonIsoText =
  4926. @"{""Value"":""2012-02-25T19:55:50.6095676+13:00""}";
  4927. DateTimeWrapper c = JsonConvert.DeserializeObject<DateTimeWrapper>(jsonIsoText, new IsoDateTimeConverter());
  4928. Assert.AreEqual(DateTimeKind.Local, c.Value.Kind);
  4929. }
  4930. #if !NET20
  4931. [Test]
  4932. public void DeserializeUTC()
  4933. {
  4934. DateTimeTestClass c =
  4935. JsonConvert.DeserializeObject<DateTimeTestClass>(
  4936. @"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12Z"",""PostField"":""Post""}",
  4937. new JsonSerializerSettings
  4938. {
  4939. DateTimeZoneHandling = DateTimeZoneHandling.Local
  4940. });
  4941. Assert.AreEqual(new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime(), c.DateTimeField);
  4942. Assert.AreEqual(new DateTimeOffset(2008, 12, 12, 12, 12, 12, 0, TimeSpan.Zero), c.DateTimeOffsetField);
  4943. Assert.AreEqual("Pre", c.PreField);
  4944. Assert.AreEqual("Post", c.PostField);
  4945. DateTimeTestClass c2 =
  4946. JsonConvert.DeserializeObject<DateTimeTestClass>(
  4947. @"{""PreField"":""Pre"",""DateTimeField"":""2008-01-01T01:01:01Z"",""DateTimeOffsetField"":""2008-01-01T01:01:01Z"",""PostField"":""Post""}",
  4948. new JsonSerializerSettings
  4949. {
  4950. DateTimeZoneHandling = DateTimeZoneHandling.Local
  4951. });
  4952. Assert.AreEqual(new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc).ToLocalTime(), c2.DateTimeField);
  4953. Assert.AreEqual(new DateTimeOffset(2008, 1, 1, 1, 1, 1, 0, TimeSpan.Zero), c2.DateTimeOffsetField);
  4954. Assert.AreEqual("Pre", c2.PreField);
  4955. Assert.AreEqual("Post", c2.PostField);
  4956. }
  4957. [Test]
  4958. public void NullableDeserializeUTC()
  4959. {
  4960. NullableDateTimeTestClass c =
  4961. JsonConvert.DeserializeObject<NullableDateTimeTestClass>(
  4962. @"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12Z"",""PostField"":""Post""}",
  4963. new JsonSerializerSettings
  4964. {
  4965. DateTimeZoneHandling = DateTimeZoneHandling.Local
  4966. });
  4967. Assert.AreEqual(new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime(), c.DateTimeField);
  4968. Assert.AreEqual(new DateTimeOffset(2008, 12, 12, 12, 12, 12, 0, TimeSpan.Zero), c.DateTimeOffsetField);
  4969. Assert.AreEqual("Pre", c.PreField);
  4970. Assert.AreEqual("Post", c.PostField);
  4971. NullableDateTimeTestClass c2 =
  4972. JsonConvert.DeserializeObject<NullableDateTimeTestClass>(
  4973. @"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}");
  4974. Assert.AreEqual(null, c2.DateTimeField);
  4975. Assert.AreEqual(null, c2.DateTimeOffsetField);
  4976. Assert.AreEqual("Pre", c2.PreField);
  4977. Assert.AreEqual("Post", c2.PostField);
  4978. }
  4979. [Test]
  4980. public void PrivateConstructor()
  4981. {
  4982. var person = PersonWithPrivateConstructor.CreatePerson();
  4983. person.Name = "John Doe";
  4984. person.Age = 25;
  4985. var serializedPerson = JsonConvert.SerializeObject(person);
  4986. var roundtrippedPerson = JsonConvert.DeserializeObject<PersonWithPrivateConstructor>(serializedPerson);
  4987. Assert.AreEqual(person.Name, roundtrippedPerson.Name);
  4988. }
  4989. #endif
  4990. #if !(SILVERLIGHT || NETFX_CORE)
  4991. [Test]
  4992. public void MetroBlogPost()
  4993. {
  4994. Product product = new Product();
  4995. product.Name = "Apple";
  4996. product.ExpiryDate = new DateTime(2012, 4, 1);
  4997. product.Price = 3.99M;
  4998. product.Sizes = new[] { "Small", "Medium", "Large" };
  4999. string json = JsonConvert.SerializeObject(product);
  5000. //{
  5001. // "Name": "Apple",
  5002. // "ExpiryDate": "2012-04-01T00:00:00",
  5003. // "Price": 3.99,
  5004. // "Sizes": [ "Small", "Medium", "Large" ]
  5005. //}
  5006. string metroJson = JsonConvert.SerializeObject(product, new JsonSerializerSettings
  5007. {
  5008. ContractResolver = new MetroPropertyNameResolver(),
  5009. Converters = { new MetroStringConverter() },
  5010. Formatting = Formatting.Indented
  5011. });
  5012. Assert.AreEqual(@"{
  5013. "":::NAME:::"": "":::APPLE:::"",
  5014. "":::EXPIRYDATE:::"": ""2012-04-01T00:00:00"",
  5015. "":::PRICE:::"": 3.99,
  5016. "":::SIZES:::"": [
  5017. "":::SMALL:::"",
  5018. "":::MEDIUM:::"",
  5019. "":::LARGE:::""
  5020. ]
  5021. }", metroJson);
  5022. //{
  5023. // ":::NAME:::": ":::APPLE:::",
  5024. // ":::EXPIRYDATE:::": "2012-04-01T00:00:00",
  5025. // ":::PRICE:::": 3.99,
  5026. // ":::SIZES:::": [ ":::SMALL:::", ":::MEDIUM:::", ":::LARGE:::" ]
  5027. //}
  5028. Color[] colors = new[] { Color.Blue, Color.Red, Color.Yellow, Color.Green, Color.Black, Color.Brown };
  5029. string json2 = JsonConvert.SerializeObject(colors, new JsonSerializerSettings
  5030. {
  5031. ContractResolver = new MetroPropertyNameResolver(),
  5032. Converters = { new MetroStringConverter(), new MetroColorConverter() },
  5033. Formatting = Formatting.Indented
  5034. });
  5035. Assert.AreEqual(@"[
  5036. "":::GRAY:::"",
  5037. "":::GRAY:::"",
  5038. "":::GRAY:::"",
  5039. "":::GRAY:::"",
  5040. "":::BLACK:::"",
  5041. "":::GRAY:::""
  5042. ]", json2);
  5043. }
  5044. public class MetroColorConverter : JsonConverter
  5045. {
  5046. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  5047. {
  5048. Color color = (Color)value;
  5049. Color fixedColor = (color == Color.White || color == Color.Black) ? color : Color.Gray;
  5050. writer.WriteValue(":::" + fixedColor.ToKnownColor().ToString().ToUpper() + ":::");
  5051. }
  5052. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  5053. {
  5054. return Enum.Parse(typeof(Color), reader.Value.ToString());
  5055. }
  5056. public override bool CanConvert(Type objectType)
  5057. {
  5058. return objectType == typeof(Color);
  5059. }
  5060. }
  5061. #endif
  5062. private class FooBar
  5063. {
  5064. public DateTimeOffset Foo { get; set; }
  5065. }
  5066. [Test]
  5067. public void TokenFromBson()
  5068. {
  5069. MemoryStream ms = new MemoryStream();
  5070. BsonWriter writer = new BsonWriter(ms);
  5071. writer.WriteStartArray();
  5072. writer.WriteValue("2000-01-02T03:04:05+06:00");
  5073. writer.WriteEndArray();
  5074. byte[] data = ms.ToArray();
  5075. BsonReader reader = new BsonReader(new MemoryStream(data))
  5076. {
  5077. ReadRootValueAsArray = true
  5078. };
  5079. JArray a = (JArray)JArray.ReadFrom(reader);
  5080. JValue v = (JValue)a[0];
  5081. Console.WriteLine(v.Value.GetType());
  5082. Console.WriteLine(a.ToString());
  5083. }
  5084. [Test]
  5085. public void ObjectRequiredDeserializeMissing()
  5086. {
  5087. string json = "{}";
  5088. IList<string> errors = new List<string>();
  5089. EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
  5090. {
  5091. errors.Add(e.ErrorContext.Error.Message);
  5092. e.ErrorContext.Handled = true;
  5093. };
  5094. var o = JsonConvert.DeserializeObject<RequiredObject>(json, new JsonSerializerSettings
  5095. {
  5096. Error = error
  5097. });
  5098. Assert.IsNotNull(o);
  5099. Assert.AreEqual(4, errors.Count);
  5100. Assert.AreEqual("Required property 'NonAttributeProperty' not found in JSON. Path '', line 1, position 2.", errors[0]);
  5101. Assert.AreEqual("Required property 'UnsetProperty' not found in JSON. Path '', line 1, position 2.", errors[1]);
  5102. Assert.AreEqual("Required property 'AllowNullProperty' not found in JSON. Path '', line 1, position 2.", errors[2]);
  5103. Assert.AreEqual("Required property 'AlwaysProperty' not found in JSON. Path '', line 1, position 2.", errors[3]);
  5104. }
  5105. [Test]
  5106. public void ObjectRequiredDeserializeNull()
  5107. {
  5108. string json = "{'NonAttributeProperty':null,'UnsetProperty':null,'AllowNullProperty':null,'AlwaysProperty':null}";
  5109. IList<string> errors = new List<string>();
  5110. EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
  5111. {
  5112. errors.Add(e.ErrorContext.Error.Message);
  5113. e.ErrorContext.Handled = true;
  5114. };
  5115. var o = JsonConvert.DeserializeObject<RequiredObject>(json, new JsonSerializerSettings
  5116. {
  5117. Error = error
  5118. });
  5119. Assert.IsNotNull(o);
  5120. Assert.AreEqual(3, errors.Count);
  5121. Assert.AreEqual("Required property 'NonAttributeProperty' expects a value but got null. Path '', line 1, position 97.", errors[0]);
  5122. Assert.AreEqual("Required property 'UnsetProperty' expects a value but got null. Path '', line 1, position 97.", errors[1]);
  5123. Assert.AreEqual("Required property 'AlwaysProperty' expects a value but got null. Path '', line 1, position 97.", errors[2]);
  5124. }
  5125. [Test]
  5126. public void ObjectRequiredSerialize()
  5127. {
  5128. IList<string> errors = new List<string>();
  5129. EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
  5130. {
  5131. errors.Add(e.ErrorContext.Error.Message);
  5132. e.ErrorContext.Handled = true;
  5133. };
  5134. string json = JsonConvert.SerializeObject(new RequiredObject(), new JsonSerializerSettings
  5135. {
  5136. Error = error,
  5137. Formatting = Formatting.Indented
  5138. });
  5139. Assert.AreEqual(@"{
  5140. ""DefaultProperty"": null,
  5141. ""AllowNullProperty"": null
  5142. }", json);
  5143. Assert.AreEqual(3, errors.Count);
  5144. Assert.AreEqual("Cannot write a null value for property 'NonAttributeProperty'. Property requires a value. Path ''.", errors[0]);
  5145. Assert.AreEqual("Cannot write a null value for property 'UnsetProperty'. Property requires a value. Path ''.", errors[1]);
  5146. Assert.AreEqual("Cannot write a null value for property 'AlwaysProperty'. Property requires a value. Path ''.", errors[2]);
  5147. }
  5148. [Test]
  5149. public void DeserializeCollectionItemConverter()
  5150. {
  5151. PropertyItemConverter c = new PropertyItemConverter
  5152. {
  5153. Data =
  5154. new[]{
  5155. "one",
  5156. "two",
  5157. "three"
  5158. }
  5159. };
  5160. var c2 = JsonConvert.DeserializeObject<PropertyItemConverter>("{'Data':['::ONE::','::TWO::']}");
  5161. Assert.IsNotNull(c2);
  5162. Assert.AreEqual(2, c2.Data.Count);
  5163. Assert.AreEqual("one", c2.Data[0]);
  5164. Assert.AreEqual("two", c2.Data[1]);
  5165. }
  5166. [Test]
  5167. public void SerializeCollectionItemConverter()
  5168. {
  5169. PropertyItemConverter c = new PropertyItemConverter
  5170. {
  5171. Data = new[]
  5172. {
  5173. "one",
  5174. "two",
  5175. "three"
  5176. }
  5177. };
  5178. string json = JsonConvert.SerializeObject(c);
  5179. Assert.AreEqual(@"{""Data"":["":::ONE:::"","":::TWO:::"","":::THREE:::""]}", json);
  5180. }
  5181. [Test]
  5182. public void DeserializeEmptyJsonString()
  5183. {
  5184. string s = (string) new JsonSerializer().Deserialize(new JsonTextReader(new StringReader("''")));
  5185. Assert.AreEqual("", s);
  5186. }
  5187. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  5188. [Test]
  5189. public void SerializeAndDeserializeWithAttributes()
  5190. {
  5191. var testObj = new PersonSerializable() { Name = "John Doe", Age = 28 };
  5192. var objDeserialized = this.SerializeAndDeserialize<PersonSerializable>(testObj);
  5193. Assert.AreEqual(testObj.Name, objDeserialized.Name);
  5194. Assert.AreEqual(0, objDeserialized.Age);
  5195. }
  5196. private T SerializeAndDeserialize<T>(T obj)
  5197. where T : class
  5198. {
  5199. var json = Serialize(obj);
  5200. return Deserialize<T>(json);
  5201. }
  5202. private string Serialize<T>(T obj)
  5203. where T : class
  5204. {
  5205. var stringWriter = new StringWriter();
  5206. var serializer = new Newtonsoft.Json.JsonSerializer();
  5207. serializer.ContractResolver = new DefaultContractResolver(false)
  5208. {
  5209. IgnoreSerializableAttribute = false
  5210. };
  5211. serializer.Serialize(stringWriter, obj);
  5212. return stringWriter.ToString();
  5213. }
  5214. private T Deserialize<T>(string json)
  5215. where T : class
  5216. {
  5217. var jsonReader = new Newtonsoft.Json.JsonTextReader(new StringReader(json));
  5218. var serializer = new Newtonsoft.Json.JsonSerializer();
  5219. serializer.ContractResolver = new DefaultContractResolver(false)
  5220. {
  5221. IgnoreSerializableAttribute = false
  5222. };
  5223. return serializer.Deserialize(jsonReader, typeof(T)) as T;
  5224. }
  5225. #endif
  5226. [Test]
  5227. public void PropertyItemConverter()
  5228. {
  5229. Event e = new Event
  5230. {
  5231. EventName = "Blackadder III",
  5232. Venue = "Gryphon Theatre",
  5233. Performances = new List<DateTime>
  5234. {
  5235. JsonConvert.ConvertJavaScriptTicksToDateTime(1336458600000),
  5236. JsonConvert.ConvertJavaScriptTicksToDateTime(1336545000000),
  5237. JsonConvert.ConvertJavaScriptTicksToDateTime(1336636800000)
  5238. }
  5239. };
  5240. string json = JsonConvert.SerializeObject(e, Formatting.Indented);
  5241. //{
  5242. // "EventName": "Blackadder III",
  5243. // "Venue": "Gryphon Theatre",
  5244. // "Performances": [
  5245. // new Date(1336458600000),
  5246. // new Date(1336545000000),
  5247. // new Date(1336636800000)
  5248. // ]
  5249. //}
  5250. Assert.AreEqual(@"{
  5251. ""EventName"": ""Blackadder III"",
  5252. ""Venue"": ""Gryphon Theatre"",
  5253. ""Performances"": [
  5254. new Date(
  5255. 1336458600000
  5256. ),
  5257. new Date(
  5258. 1336545000000
  5259. ),
  5260. new Date(
  5261. 1336636800000
  5262. )
  5263. ]
  5264. }", json);
  5265. }
  5266. #if !(NET20 || NET35)
  5267. [Test]
  5268. public void SerializeDataContractSerializationAttributes()
  5269. {
  5270. DataContractSerializationAttributesClass dataContract = new DataContractSerializationAttributesClass
  5271. {
  5272. NoAttribute = "Value!",
  5273. IgnoreDataMemberAttribute = "Value!",
  5274. DataMemberAttribute = "Value!",
  5275. IgnoreDataMemberAndDataMemberAttribute = "Value!"
  5276. };
  5277. string json = JsonConvert.SerializeObject(dataContract, Formatting.Indented);
  5278. Assert.AreEqual(@"{
  5279. ""DataMemberAttribute"": ""Value!"",
  5280. ""IgnoreDataMemberAndDataMemberAttribute"": ""Value!""
  5281. }", json);
  5282. PocoDataContractSerializationAttributesClass poco = new PocoDataContractSerializationAttributesClass
  5283. {
  5284. NoAttribute = "Value!",
  5285. IgnoreDataMemberAttribute = "Value!",
  5286. DataMemberAttribute = "Value!",
  5287. IgnoreDataMemberAndDataMemberAttribute = "Value!"
  5288. };
  5289. json = JsonConvert.SerializeObject(poco, Formatting.Indented);
  5290. Assert.AreEqual(@"{
  5291. ""NoAttribute"": ""Value!"",
  5292. ""DataMemberAttribute"": ""Value!""
  5293. }", json);
  5294. }
  5295. #endif
  5296. [Test]
  5297. public void CheckAdditionalContent()
  5298. {
  5299. string json = "{one:1}{}";
  5300. JsonSerializerSettings settings = new JsonSerializerSettings();
  5301. JsonSerializer s = JsonSerializer.Create(settings);
  5302. IDictionary<string, int> o = s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json)));
  5303. Assert.IsNotNull(o);
  5304. Assert.AreEqual(1, o["one"]);
  5305. settings.CheckAdditionalContent = true;
  5306. s = JsonSerializer.Create(settings);
  5307. ExceptionAssert.Throws<JsonReaderException>(
  5308. "Additional text encountered after finished reading JSON content: {. Path '', line 1, position 7.",
  5309. () =>
  5310. {
  5311. s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json)));
  5312. });
  5313. }
  5314. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  5315. [Test]
  5316. public void DeserializeException()
  5317. {
  5318. string json = @"{ ""ClassName"" : ""System.InvalidOperationException"",
  5319. ""Data"" : null,
  5320. ""ExceptionMethod"" : ""8\nLogin\nAppBiz, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null\nMyApp.LoginBiz\nMyApp.User Login()"",
  5321. ""HResult"" : -2146233079,
  5322. ""HelpURL"" : null,
  5323. ""InnerException"" : { ""ClassName"" : ""System.Exception"",
  5324. ""Data"" : null,
  5325. ""ExceptionMethod"" : null,
  5326. ""HResult"" : -2146233088,
  5327. ""HelpURL"" : null,
  5328. ""InnerException"" : null,
  5329. ""Message"" : ""Inner exception..."",
  5330. ""RemoteStackIndex"" : 0,
  5331. ""RemoteStackTraceString"" : null,
  5332. ""Source"" : null,
  5333. ""StackTraceString"" : null,
  5334. ""WatsonBuckets"" : null
  5335. },
  5336. ""Message"" : ""Outter exception..."",
  5337. ""RemoteStackIndex"" : 0,
  5338. ""RemoteStackTraceString"" : null,
  5339. ""Source"" : ""AppBiz"",
  5340. ""StackTraceString"" : "" at MyApp.LoginBiz.Login() in C:\\MyApp\\LoginBiz.cs:line 44\r\n at MyApp.LoginSvc.Login() in C:\\MyApp\\LoginSvc.cs:line 71\r\n at SyncInvokeLogin(Object , Object[] , Object[] )\r\n at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)\r\n at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\r\n at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)"",
  5341. ""WatsonBuckets"" : null
  5342. }";
  5343. InvalidOperationException exception = JsonConvert.DeserializeObject<InvalidOperationException>(json);
  5344. Assert.IsNotNull(exception);
  5345. CustomAssert.IsInstanceOfType(typeof(InvalidOperationException), exception);
  5346. Assert.AreEqual("Outter exception...", exception.Message);
  5347. }
  5348. #endif
  5349. [Test]
  5350. public void AdditionalContentAfterFinish()
  5351. {
  5352. ExceptionAssert.Throws<JsonException>(
  5353. "Additional text found in JSON string after finishing deserializing object.",
  5354. () =>
  5355. {
  5356. string json = "[{},1]";
  5357. JsonSerializer serializer = new JsonSerializer();
  5358. serializer.CheckAdditionalContent = true;
  5359. var reader = new JsonTextReader(new StringReader(json));
  5360. reader.Read();
  5361. reader.Read();
  5362. serializer.Deserialize(reader, typeof (MyType));
  5363. });
  5364. }
  5365. [Test]
  5366. public void DeserializeRelativeUri()
  5367. {
  5368. IList<Uri> uris = JsonConvert.DeserializeObject<IList<Uri>>(@"[""http://localhost/path?query#hash""]");
  5369. Assert.AreEqual(1, uris.Count);
  5370. Assert.AreEqual(new Uri("http://localhost/path?query#hash"), uris[0]);
  5371. Uri uri = JsonConvert.DeserializeObject<Uri>(@"""http://localhost/path?query#hash""");
  5372. Assert.IsNotNull(uri);
  5373. Uri i1 = new Uri("http://localhost/path?query#hash", UriKind.RelativeOrAbsolute);
  5374. Uri i2 = new Uri("http://localhost/path?query#hash");
  5375. Assert.AreEqual(i1, i2);
  5376. uri = JsonConvert.DeserializeObject<Uri>(@"""/path?query#hash""");
  5377. Assert.IsNotNull(uri);
  5378. Assert.AreEqual(new Uri("/path?query#hash", UriKind.RelativeOrAbsolute), uri);
  5379. }
  5380. public class MyConverter : JsonConverter
  5381. {
  5382. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  5383. {
  5384. writer.WriteValue("X");
  5385. }
  5386. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  5387. {
  5388. return "X";
  5389. }
  5390. public override bool CanConvert(Type objectType)
  5391. {
  5392. return true;
  5393. }
  5394. }
  5395. public class MyType
  5396. {
  5397. [JsonProperty(ItemConverterType = typeof(MyConverter))]
  5398. public Dictionary<string, object> MyProperty { get; set; }
  5399. }
  5400. [Test]
  5401. public void DeserializeDictionaryItemConverter()
  5402. {
  5403. var actual = JsonConvert.DeserializeObject<MyType>(@"{ ""MyProperty"":{""Key"":""Y""}}");
  5404. Assert.AreEqual("X", actual.MyProperty["Key"]);
  5405. }
  5406. [Test]
  5407. public void DeserializeCaseInsensitiveKeyValuePairConverter()
  5408. {
  5409. KeyValuePair<int, string> result =
  5410. JsonConvert.DeserializeObject<KeyValuePair<int, string>>(
  5411. "{key: 123, \"VALUE\": \"test value\"}"
  5412. );
  5413. Assert.AreEqual(123, result.Key);
  5414. Assert.AreEqual("test value", result.Value);
  5415. }
  5416. [Test]
  5417. public void SerializeKeyValuePairConverterWithCamelCase()
  5418. {
  5419. string json =
  5420. JsonConvert.SerializeObject(new KeyValuePair<int, string>(123, "test value"), Formatting.Indented, new JsonSerializerSettings
  5421. {
  5422. ContractResolver = new CamelCasePropertyNamesContractResolver()
  5423. });
  5424. Assert.AreEqual(@"{
  5425. ""key"": 123,
  5426. ""value"": ""test value""
  5427. }", json);
  5428. }
  5429. [JsonObject(MemberSerialization.Fields)]
  5430. public class MyTuple<T1>
  5431. {
  5432. private readonly T1 m_Item1;
  5433. public MyTuple(T1 item1)
  5434. {
  5435. m_Item1 = item1;
  5436. }
  5437. public T1 Item1
  5438. {
  5439. get { return m_Item1; }
  5440. }
  5441. }
  5442. [JsonObject(MemberSerialization.Fields)]
  5443. public class MyTuplePartial<T1>
  5444. {
  5445. private readonly T1 m_Item1;
  5446. public MyTuplePartial(T1 item1)
  5447. {
  5448. m_Item1 = item1;
  5449. }
  5450. public T1 Item1
  5451. {
  5452. get { return m_Item1; }
  5453. }
  5454. }
  5455. [Test]
  5456. public void SerializeCustomTupleWithSerializableAttribute()
  5457. {
  5458. var tuple = new MyTuple<int>(500);
  5459. var json = JsonConvert.SerializeObject(tuple);
  5460. Assert.AreEqual(@"{""m_Item1"":500}", json);
  5461. MyTuple<int> obj = null;
  5462. Action doStuff = () =>
  5463. {
  5464. obj = JsonConvert.DeserializeObject<MyTuple<int>>(json);
  5465. };
  5466. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  5467. doStuff();
  5468. Assert.AreEqual(500, obj.Item1);
  5469. #else
  5470. ExceptionAssert.Throws<JsonSerializationException>(
  5471. "Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+MyTuple`1[System.Int32]. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'm_Item1', line 1, position 11.",
  5472. doStuff);
  5473. #endif
  5474. }
  5475. #if DEBUG
  5476. [Test]
  5477. public void SerializeCustomTupleWithSerializableAttributeInPartialTrust()
  5478. {
  5479. try
  5480. {
  5481. JsonTypeReflector.SetFullyTrusted(false);
  5482. var tuple = new MyTuplePartial<int>(500);
  5483. var json = JsonConvert.SerializeObject(tuple);
  5484. Assert.AreEqual(@"{""m_Item1"":500}", json);
  5485. ExceptionAssert.Throws<JsonSerializationException>(
  5486. "Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+MyTuplePartial`1[System.Int32]. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'm_Item1', line 1, position 11.",
  5487. () => JsonConvert.DeserializeObject<MyTuplePartial<int>>(json));
  5488. }
  5489. finally
  5490. {
  5491. JsonTypeReflector.SetFullyTrusted(true);
  5492. }
  5493. }
  5494. #endif
  5495. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || NET35 || NET20)
  5496. [Test]
  5497. public void SerializeTupleWithSerializableAttribute()
  5498. {
  5499. var tuple = Tuple.Create(500);
  5500. var json = JsonConvert.SerializeObject(tuple, new JsonSerializerSettings
  5501. {
  5502. ContractResolver = new SerializableContractResolver()
  5503. });
  5504. Assert.AreEqual(@"{""m_Item1"":500}", json);
  5505. var obj = JsonConvert.DeserializeObject<Tuple<int>>(json, new JsonSerializerSettings
  5506. {
  5507. ContractResolver = new SerializableContractResolver()
  5508. });
  5509. Assert.AreEqual(500, obj.Item1);
  5510. }
  5511. public class SerializableContractResolver : DefaultContractResolver
  5512. {
  5513. public SerializableContractResolver()
  5514. {
  5515. IgnoreSerializableAttribute = false;
  5516. }
  5517. }
  5518. #endif
  5519. [Test]
  5520. public void SerializeArray2D()
  5521. {
  5522. Array2D aa = new Array2D();
  5523. aa.Before = "Before!";
  5524. aa.After = "After!";
  5525. aa.Coordinates = new[,] { { 1, 1 }, { 1, 2 }, { 2, 1 }, { 2, 2 } };
  5526. string json = JsonConvert.SerializeObject(aa);
  5527. Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}", json);
  5528. }
  5529. [Test]
  5530. public void SerializeArray3D()
  5531. {
  5532. Array3D aa = new Array3D();
  5533. aa.Before = "Before!";
  5534. aa.After = "After!";
  5535. aa.Coordinates = new[, ,] { { { 1, 1, 1 }, { 1, 1, 2 } }, { { 1, 2, 1 }, { 1, 2, 2 } }, { { 2, 1, 1 }, { 2, 1, 2 } }, { { 2, 2, 1 }, { 2, 2, 2 } } };
  5536. string json = JsonConvert.SerializeObject(aa);
  5537. Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1,2]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],[2,2,2]]],""After"":""After!""}", json);
  5538. }
  5539. [Test]
  5540. public void SerializeArray3DWithConverter()
  5541. {
  5542. Array3DWithConverter aa = new Array3DWithConverter();
  5543. aa.Before = "Before!";
  5544. aa.After = "After!";
  5545. aa.Coordinates = new[, ,] { { { 1, 1, 1 }, { 1, 1, 2 } }, { { 1, 2, 1 }, { 1, 2, 2 } }, { { 2, 1, 1 }, { 2, 1, 2 } }, { { 2, 2, 1 }, { 2, 2, 2 } } };
  5546. string json = JsonConvert.SerializeObject(aa, Formatting.Indented);
  5547. Assert.AreEqual(@"{
  5548. ""Before"": ""Before!"",
  5549. ""Coordinates"": [
  5550. [
  5551. [
  5552. 1.0,
  5553. 1.0,
  5554. 1.0
  5555. ],
  5556. [
  5557. 1.0,
  5558. 1.0,
  5559. 2.0
  5560. ]
  5561. ],
  5562. [
  5563. [
  5564. 1.0,
  5565. 2.0,
  5566. 1.0
  5567. ],
  5568. [
  5569. 1.0,
  5570. 2.0,
  5571. 2.0
  5572. ]
  5573. ],
  5574. [
  5575. [
  5576. 2.0,
  5577. 1.0,
  5578. 1.0
  5579. ],
  5580. [
  5581. 2.0,
  5582. 1.0,
  5583. 2.0
  5584. ]
  5585. ],
  5586. [
  5587. [
  5588. 2.0,
  5589. 2.0,
  5590. 1.0
  5591. ],
  5592. [
  5593. 2.0,
  5594. 2.0,
  5595. 2.0
  5596. ]
  5597. ]
  5598. ],
  5599. ""After"": ""After!""
  5600. }", json);
  5601. }
  5602. [Test]
  5603. public void DeserializeArray3DWithConverter()
  5604. {
  5605. string json = @"{
  5606. ""Before"": ""Before!"",
  5607. ""Coordinates"": [
  5608. [
  5609. [
  5610. 1.0,
  5611. 1.0,
  5612. 1.0
  5613. ],
  5614. [
  5615. 1.0,
  5616. 1.0,
  5617. 2.0
  5618. ]
  5619. ],
  5620. [
  5621. [
  5622. 1.0,
  5623. 2.0,
  5624. 1.0
  5625. ],
  5626. [
  5627. 1.0,
  5628. 2.0,
  5629. 2.0
  5630. ]
  5631. ],
  5632. [
  5633. [
  5634. 2.0,
  5635. 1.0,
  5636. 1.0
  5637. ],
  5638. [
  5639. 2.0,
  5640. 1.0,
  5641. 2.0
  5642. ]
  5643. ],
  5644. [
  5645. [
  5646. 2.0,
  5647. 2.0,
  5648. 1.0
  5649. ],
  5650. [
  5651. 2.0,
  5652. 2.0,
  5653. 2.0
  5654. ]
  5655. ]
  5656. ],
  5657. ""After"": ""After!""
  5658. }";
  5659. Array3DWithConverter aa = JsonConvert.DeserializeObject<Array3DWithConverter>(json);
  5660. Assert.AreEqual("Before!", aa.Before);
  5661. Assert.AreEqual("After!", aa.After);
  5662. Assert.AreEqual(4, aa.Coordinates.GetLength(0));
  5663. Assert.AreEqual(2, aa.Coordinates.GetLength(1));
  5664. Assert.AreEqual(3, aa.Coordinates.GetLength(2));
  5665. Assert.AreEqual(1, aa.Coordinates[0, 0, 0]);
  5666. Assert.AreEqual(2, aa.Coordinates[1, 1, 1]);
  5667. }
  5668. [Test]
  5669. public void DeserializeArray2D()
  5670. {
  5671. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}";
  5672. Array2D aa = JsonConvert.DeserializeObject<Array2D>(json);
  5673. Assert.AreEqual("Before!", aa.Before);
  5674. Assert.AreEqual("After!", aa.After);
  5675. Assert.AreEqual(4, aa.Coordinates.GetLength(0));
  5676. Assert.AreEqual(2, aa.Coordinates.GetLength(1));
  5677. Assert.AreEqual(1, aa.Coordinates[0, 0]);
  5678. Assert.AreEqual(2, aa.Coordinates[1, 1]);
  5679. string after = JsonConvert.SerializeObject(aa);
  5680. Assert.AreEqual(json, after);
  5681. }
  5682. [Test]
  5683. public void DeserializeArray2D_WithTooManyItems()
  5684. {
  5685. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2,3],[2,1],[2,2]],""After"":""After!""}";
  5686. ExceptionAssert.Throws<Exception>(
  5687. "Cannot deserialize non-cubical array as multidimensional array.",
  5688. () => JsonConvert.DeserializeObject<Array2D>(json));
  5689. }
  5690. [Test]
  5691. public void DeserializeArray2D_WithTooFewItems()
  5692. {
  5693. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1],[2,1],[2,2]],""After"":""After!""}";
  5694. ExceptionAssert.Throws<Exception>(
  5695. "Cannot deserialize non-cubical array as multidimensional array.",
  5696. () => JsonConvert.DeserializeObject<Array2D>(json));
  5697. }
  5698. [Test]
  5699. public void DeserializeArray3D()
  5700. {
  5701. string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1,2]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],[2,2,2]]],""After"":""After!""}";
  5702. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  5703. Assert.AreEqual("Before!", aa.Before);
  5704. Assert.AreEqual("After!", aa.After);
  5705. Assert.AreEqual(4, aa.Coordinates.GetLength(0));
  5706. Assert.AreEqual(2, aa.Coordinates.GetLength(1));
  5707. Assert.AreEqual(3, aa.Coordinates.GetLength(2));
  5708. Assert.AreEqual(1, aa.Coordinates[0, 0, 0]);
  5709. Assert.AreEqual(2, aa.Coordinates[1, 1, 1]);
  5710. string after = JsonConvert.SerializeObject(aa);
  5711. Assert.AreEqual(json, after);
  5712. }
  5713. [Test]
  5714. public void DeserializeArray3D_WithTooManyItems()
  5715. {
  5716. string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1,2,1]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],[2,2,2]]],""After"":""After!""}";
  5717. ExceptionAssert.Throws<Exception>(
  5718. "Cannot deserialize non-cubical array as multidimensional array.",
  5719. () => JsonConvert.DeserializeObject<Array3D>(json));
  5720. }
  5721. [Test]
  5722. public void DeserializeArray3D_WithBadItems()
  5723. {
  5724. string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1,2]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],{}]],""After"":""After!""}";
  5725. ExceptionAssert.Throws<JsonSerializationException>(
  5726. "Unexpected token when deserializing multidimensional array: StartObject. Path 'Coordinates[3][1]', line 1, position 99.",
  5727. () => JsonConvert.DeserializeObject<Array3D>(json));
  5728. }
  5729. [Test]
  5730. public void DeserializeArray3D_WithTooFewItems()
  5731. {
  5732. string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],[2,2,2]]],""After"":""After!""}";
  5733. ExceptionAssert.Throws<Exception>(
  5734. "Cannot deserialize non-cubical array as multidimensional array.",
  5735. () => JsonConvert.DeserializeObject<Array3D>(json));
  5736. }
  5737. [Test]
  5738. public void SerializeEmpty3DArray()
  5739. {
  5740. Array3D aa = new Array3D();
  5741. aa.Before = "Before!";
  5742. aa.After = "After!";
  5743. aa.Coordinates = new int[0, 0, 0];
  5744. string json = JsonConvert.SerializeObject(aa);
  5745. Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[],""After"":""After!""}", json);
  5746. }
  5747. [Test]
  5748. public void DeserializeEmpty3DArray()
  5749. {
  5750. string json = @"{""Before"":""Before!"",""Coordinates"":[],""After"":""After!""}";
  5751. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  5752. Assert.AreEqual("Before!", aa.Before);
  5753. Assert.AreEqual("After!", aa.After);
  5754. Assert.AreEqual(0, aa.Coordinates.GetLength(0));
  5755. Assert.AreEqual(0, aa.Coordinates.GetLength(1));
  5756. Assert.AreEqual(0, aa.Coordinates.GetLength(2));
  5757. string after = JsonConvert.SerializeObject(aa);
  5758. Assert.AreEqual(json, after);
  5759. }
  5760. [Test]
  5761. public void DeserializeIncomplete3DArray()
  5762. {
  5763. string json = @"{""Before"":""Before!"",""Coordinates"":[/*hi*/[/*hi*/[1/*hi*/,/*hi*/1/*hi*/,1]/*hi*/,/*hi*/[1,1";
  5764. ExceptionAssert.Throws<JsonSerializationException>(
  5765. "Unexpected end when deserializing array. Path 'Coordinates[0][1][1]', line 1, position 90.",
  5766. () => JsonConvert.DeserializeObject<Array3D>(json));
  5767. }
  5768. [Test]
  5769. public void DeserializeIncompleteNotTopLevel3DArray()
  5770. {
  5771. string json = @"{""Before"":""Before!"",""Coordinates"":[/*hi*/[/*hi*/";
  5772. ExceptionAssert.Throws<JsonSerializationException>(
  5773. "Unexpected end when deserializing array. Path 'Coordinates[0]', line 1, position 48.",
  5774. () => JsonConvert.DeserializeObject<Array3D>(json));
  5775. }
  5776. [Test]
  5777. public void DeserializeNull3DArray()
  5778. {
  5779. string json = @"{""Before"":""Before!"",""Coordinates"":null,""After"":""After!""}";
  5780. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  5781. Assert.AreEqual("Before!", aa.Before);
  5782. Assert.AreEqual("After!", aa.After);
  5783. Assert.AreEqual(null, aa.Coordinates);
  5784. string after = JsonConvert.SerializeObject(aa);
  5785. Assert.AreEqual(json, after);
  5786. }
  5787. [Test]
  5788. public void DeserializeSemiEmpty3DArray()
  5789. {
  5790. string json = @"{""Before"":""Before!"",""Coordinates"":[[]],""After"":""After!""}";
  5791. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  5792. Assert.AreEqual("Before!", aa.Before);
  5793. Assert.AreEqual("After!", aa.After);
  5794. Assert.AreEqual(1, aa.Coordinates.GetLength(0));
  5795. Assert.AreEqual(0, aa.Coordinates.GetLength(1));
  5796. Assert.AreEqual(0, aa.Coordinates.GetLength(2));
  5797. string after = JsonConvert.SerializeObject(aa);
  5798. Assert.AreEqual(json, after);
  5799. }
  5800. [Test]
  5801. public void SerializeReferenceTracked3DArray()
  5802. {
  5803. Event e1 = new Event
  5804. {
  5805. EventName = "EventName!"
  5806. };
  5807. Event[,] array1 = new [,] { { e1, e1 }, { e1, e1 } };
  5808. IList<Event[,]> values1 = new List<Event[,]>
  5809. {
  5810. array1,
  5811. array1
  5812. };
  5813. string json = JsonConvert.SerializeObject(values1, new JsonSerializerSettings
  5814. {
  5815. PreserveReferencesHandling = PreserveReferencesHandling.All,
  5816. Formatting = Formatting.Indented
  5817. });
  5818. Assert.AreEqual(@"{
  5819. ""$id"": ""1"",
  5820. ""$values"": [
  5821. {
  5822. ""$id"": ""2"",
  5823. ""$values"": [
  5824. [
  5825. {
  5826. ""$id"": ""3"",
  5827. ""EventName"": ""EventName!"",
  5828. ""Venue"": null,
  5829. ""Performances"": null
  5830. },
  5831. {
  5832. ""$ref"": ""3""
  5833. }
  5834. ],
  5835. [
  5836. {
  5837. ""$ref"": ""3""
  5838. },
  5839. {
  5840. ""$ref"": ""3""
  5841. }
  5842. ]
  5843. ]
  5844. },
  5845. {
  5846. ""$ref"": ""2""
  5847. }
  5848. ]
  5849. }", json);
  5850. }
  5851. [Test]
  5852. public void SerializeTypeName3DArray()
  5853. {
  5854. Event e1 = new Event
  5855. {
  5856. EventName = "EventName!"
  5857. };
  5858. Event[,] array1 = new[,] { { e1, e1 }, { e1, e1 } };
  5859. IList<Event[,]> values1 = new List<Event[,]>
  5860. {
  5861. array1,
  5862. array1
  5863. };
  5864. string json = JsonConvert.SerializeObject(values1, new JsonSerializerSettings
  5865. {
  5866. TypeNameHandling = TypeNameHandling.All,
  5867. Formatting = Formatting.Indented
  5868. });
  5869. Assert.AreEqual(@"{
  5870. ""$type"": ""System.Collections.Generic.List`1[[Newtonsoft.Json.Tests.Serialization.Event[,], Newtonsoft.Json.Tests]], mscorlib"",
  5871. ""$values"": [
  5872. {
  5873. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event[,], Newtonsoft.Json.Tests"",
  5874. ""$values"": [
  5875. [
  5876. {
  5877. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5878. ""EventName"": ""EventName!"",
  5879. ""Venue"": null,
  5880. ""Performances"": null
  5881. },
  5882. {
  5883. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5884. ""EventName"": ""EventName!"",
  5885. ""Venue"": null,
  5886. ""Performances"": null
  5887. }
  5888. ],
  5889. [
  5890. {
  5891. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5892. ""EventName"": ""EventName!"",
  5893. ""Venue"": null,
  5894. ""Performances"": null
  5895. },
  5896. {
  5897. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5898. ""EventName"": ""EventName!"",
  5899. ""Venue"": null,
  5900. ""Performances"": null
  5901. }
  5902. ]
  5903. ]
  5904. },
  5905. {
  5906. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event[,], Newtonsoft.Json.Tests"",
  5907. ""$values"": [
  5908. [
  5909. {
  5910. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5911. ""EventName"": ""EventName!"",
  5912. ""Venue"": null,
  5913. ""Performances"": null
  5914. },
  5915. {
  5916. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5917. ""EventName"": ""EventName!"",
  5918. ""Venue"": null,
  5919. ""Performances"": null
  5920. }
  5921. ],
  5922. [
  5923. {
  5924. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5925. ""EventName"": ""EventName!"",
  5926. ""Venue"": null,
  5927. ""Performances"": null
  5928. },
  5929. {
  5930. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5931. ""EventName"": ""EventName!"",
  5932. ""Venue"": null,
  5933. ""Performances"": null
  5934. }
  5935. ]
  5936. ]
  5937. }
  5938. ]
  5939. }", json);
  5940. IList<Event[,]> values2 = (IList<Event[,]>)JsonConvert.DeserializeObject(json, new JsonSerializerSettings
  5941. {
  5942. TypeNameHandling = TypeNameHandling.All
  5943. });
  5944. Assert.AreEqual(2, values2.Count);
  5945. Assert.AreEqual("EventName!", values2[0][0, 0].EventName);
  5946. }
  5947. #if NETFX_CORE
  5948. [Test]
  5949. public void SerializeWinRTJsonObject()
  5950. {
  5951. var o = Windows.Data.Json.JsonObject.Parse(@"{
  5952. ""CPU"": ""Intel"",
  5953. ""Drives"": [
  5954. ""DVD read/writer"",
  5955. ""500 gigabyte hard drive""
  5956. ]
  5957. }");
  5958. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  5959. Assert.AreEqual(@"{
  5960. ""Drives"": [
  5961. ""DVD read/writer"",
  5962. ""500 gigabyte hard drive""
  5963. ],
  5964. ""CPU"": ""Intel""
  5965. }", json);
  5966. }
  5967. #endif
  5968. #if !NET20
  5969. [Test]
  5970. public void RoundtripOfDateTimeOffset()
  5971. {
  5972. var content = @"{""startDateTime"":""2012-07-19T14:30:00+09:30""}";
  5973. var jsonSerializerSettings = new JsonSerializerSettings() {DateFormatHandling = DateFormatHandling.IsoDateFormat, DateParseHandling = DateParseHandling.DateTimeOffset, DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind};
  5974. var obj = (JObject)JsonConvert.DeserializeObject(content, jsonSerializerSettings);
  5975. var dateTimeOffset = (DateTimeOffset)((JValue) obj["startDateTime"]).Value;
  5976. Assert.AreEqual(TimeSpan.FromHours(9.5), dateTimeOffset.Offset);
  5977. Assert.AreEqual("07/19/2012 14:30:00 +09:30", dateTimeOffset.ToString(CultureInfo.InvariantCulture));
  5978. }
  5979. public class NullableFloats
  5980. {
  5981. public object Object { get; set; }
  5982. public float Float { get; set; }
  5983. public double Double { get; set; }
  5984. public float? NullableFloat { get; set; }
  5985. public double? NullableDouble { get; set; }
  5986. public object ObjectNull { get; set; }
  5987. }
  5988. [Test]
  5989. public void NullableFloatingPoint()
  5990. {
  5991. NullableFloats floats = new NullableFloats
  5992. {
  5993. Object = double.NaN,
  5994. ObjectNull = null,
  5995. Float = float.NaN,
  5996. NullableDouble = double.NaN,
  5997. NullableFloat = null
  5998. };
  5999. string json = JsonConvert.SerializeObject(floats, Formatting.Indented, new JsonSerializerSettings
  6000. {
  6001. FloatFormatHandling = FloatFormatHandling.DefaultValue
  6002. });
  6003. Assert.AreEqual(@"{
  6004. ""Object"": 0.0,
  6005. ""Float"": 0.0,
  6006. ""Double"": 0.0,
  6007. ""NullableFloat"": null,
  6008. ""NullableDouble"": null,
  6009. ""ObjectNull"": null
  6010. }", json);
  6011. }
  6012. [Test]
  6013. public void DateFormatString()
  6014. {
  6015. IList<object> dates = new List<object>
  6016. {
  6017. new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc),
  6018. new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1))
  6019. };
  6020. string json = JsonConvert.SerializeObject(dates, Formatting.Indented, new JsonSerializerSettings
  6021. {
  6022. DateFormatString = "yyyy tt",
  6023. Culture = new CultureInfo("en-NZ")
  6024. });
  6025. Assert.AreEqual(@"[
  6026. ""2000 p.m."",
  6027. ""2000 p.m.""
  6028. ]", json);
  6029. }
  6030. [Test]
  6031. public void DateFormatStringForInternetExplorer()
  6032. {
  6033. IList<object> dates = new List<object>
  6034. {
  6035. new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc),
  6036. new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1))
  6037. };
  6038. string json = JsonConvert.SerializeObject(dates, Formatting.Indented, new JsonSerializerSettings
  6039. {
  6040. DateFormatString = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK"
  6041. });
  6042. Assert.AreEqual(@"[
  6043. ""2000-12-12T12:12:12.000Z"",
  6044. ""2000-12-12T12:12:12.000+01:00""
  6045. ]", json);
  6046. }
  6047. [Test]
  6048. public void JsonSerializerDateFormatString()
  6049. {
  6050. IList<object> dates = new List<object>
  6051. {
  6052. new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc),
  6053. new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1))
  6054. };
  6055. StringWriter sw = new StringWriter();
  6056. JsonTextWriter jsonWriter = new JsonTextWriter(sw);
  6057. JsonSerializer serializer = JsonSerializer.Create(new JsonSerializerSettings
  6058. {
  6059. DateFormatString = "yyyy tt",
  6060. Culture = new CultureInfo("en-NZ"),
  6061. Formatting = Formatting.Indented
  6062. });
  6063. serializer.Serialize(jsonWriter, dates);
  6064. Assert.IsNull(jsonWriter.DateFormatString);
  6065. Assert.AreEqual(CultureInfo.InvariantCulture, jsonWriter.Culture);
  6066. Assert.AreEqual(Formatting.None, jsonWriter.Formatting);
  6067. string json = sw.ToString();
  6068. Assert.AreEqual(@"[
  6069. ""2000 p.m."",
  6070. ""2000 p.m.""
  6071. ]", json);
  6072. }
  6073. [Test]
  6074. public void JsonSerializerStringEscapeHandling()
  6075. {
  6076. StringWriter sw = new StringWriter();
  6077. JsonTextWriter jsonWriter = new JsonTextWriter(sw);
  6078. JsonSerializer serializer = JsonSerializer.Create(new JsonSerializerSettings
  6079. {
  6080. StringEscapeHandling = StringEscapeHandling.EscapeHtml,
  6081. Formatting = Formatting.Indented
  6082. });
  6083. serializer.Serialize(jsonWriter, new { html = "<html></html>" });
  6084. Assert.AreEqual(StringEscapeHandling.Default, jsonWriter.StringEscapeHandling);
  6085. string json = sw.ToString();
  6086. Assert.AreEqual(@"{
  6087. ""html"": ""\u003chtml\u003e\u003c/html\u003e""
  6088. }", json);
  6089. }
  6090. [Test]
  6091. public void ReadStringFloatingPointSymbols()
  6092. {
  6093. string json = @"[
  6094. 'NaN',
  6095. 'Infinity',
  6096. '-Infinity'
  6097. ]";
  6098. IList<float> floats = JsonConvert.DeserializeObject<IList<float>>(json);
  6099. Assert.AreEqual(float.NaN, floats[0]);
  6100. Assert.AreEqual(float.PositiveInfinity, floats[1]);
  6101. Assert.AreEqual(float.NegativeInfinity, floats[2]);
  6102. IList<double> doubles = JsonConvert.DeserializeObject<IList<double>>(json);
  6103. Assert.AreEqual(float.NaN, doubles[0]);
  6104. Assert.AreEqual(float.PositiveInfinity, doubles[1]);
  6105. Assert.AreEqual(float.NegativeInfinity, doubles[2]);
  6106. }
  6107. [Test]
  6108. public void DefaultDateStringFormatVsUnsetDateStringFormat()
  6109. {
  6110. IDictionary<string, object> dates = new Dictionary<string, object>
  6111. {
  6112. {"DateTime-Unspecified", new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Unspecified)},
  6113. {"DateTime-Utc", new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)},
  6114. {"DateTime-Local", new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Local)},
  6115. {"DateTimeOffset-Zero", new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero)},
  6116. {"DateTimeOffset-Plus1", new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1))},
  6117. {"DateTimeOffset-Plus15", new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1.5))}
  6118. };
  6119. string expected = JsonConvert.SerializeObject(dates, Formatting.Indented);
  6120. Console.WriteLine(expected);
  6121. string actual = JsonConvert.SerializeObject(dates, Formatting.Indented, new JsonSerializerSettings
  6122. {
  6123. DateFormatString = JsonSerializerSettings.DefaultDateFormatString
  6124. });
  6125. Console.WriteLine(expected);
  6126. Assert.AreEqual(expected, actual);
  6127. }
  6128. #endif
  6129. #if !NET20
  6130. public class NullableTestClass
  6131. {
  6132. public bool? MyNullableBool { get; set; }
  6133. public int? MyNullableInteger { get; set; }
  6134. public DateTime? MyNullableDateTime { get; set; }
  6135. public DateTimeOffset? MyNullableDateTimeOffset { get; set; }
  6136. public Decimal? MyNullableDecimal { get; set; }
  6137. }
  6138. [Test]
  6139. public void TestStringToNullableDeserialization()
  6140. {
  6141. string json = @"{
  6142. ""MyNullableBool"": """",
  6143. ""MyNullableInteger"": """",
  6144. ""MyNullableDateTime"": """",
  6145. ""MyNullableDateTimeOffset"": """",
  6146. ""MyNullableDecimal"": """"
  6147. }";
  6148. NullableTestClass c2 = JsonConvert.DeserializeObject<NullableTestClass>(json);
  6149. Assert.IsNull(c2.MyNullableBool);
  6150. Assert.IsNull(c2.MyNullableInteger);
  6151. Assert.IsNull(c2.MyNullableDateTime);
  6152. Assert.IsNull(c2.MyNullableDateTimeOffset);
  6153. Assert.IsNull(c2.MyNullableDecimal);
  6154. }
  6155. #endif
  6156. #if !(PORTABLE || NET20 || NET35 || WINDOWS_PHONE)
  6157. [Test]
  6158. public void HashSetInterface()
  6159. {
  6160. ISet<string> s1 = new HashSet<string>(new[] {"1", "two", "III"});
  6161. string json = JsonConvert.SerializeObject(s1);
  6162. ISet<string> s2 = JsonConvert.DeserializeObject<ISet<string>>(json);
  6163. Assert.AreEqual(s1.Count, s2.Count);
  6164. foreach (string s in s1)
  6165. {
  6166. Assert.IsTrue(s2.Contains(s));
  6167. }
  6168. }
  6169. #endif
  6170. public class NewEmployee : Employee
  6171. {
  6172. public int Age { get; set; }
  6173. public bool ShouldSerializeName()
  6174. {
  6175. return false;
  6176. }
  6177. }
  6178. [Test]
  6179. public void ShouldSerializeInheritedClassTest()
  6180. {
  6181. NewEmployee joe = new NewEmployee();
  6182. joe.Name = "Joe Employee";
  6183. joe.Age = 100;
  6184. Employee mike = new Employee();
  6185. mike.Name = "Mike Manager";
  6186. mike.Manager = mike;
  6187. joe.Manager = mike;
  6188. //StringWriter sw = new StringWriter();
  6189. //XmlSerializer x = new XmlSerializer(typeof(NewEmployee));
  6190. //x.Serialize(sw, joe);
  6191. //Console.WriteLine(sw);
  6192. //JavaScriptSerializer s = new JavaScriptSerializer();
  6193. //Console.WriteLine(s.Serialize(new {html = @"<script>hi</script>; & ! ^ * ( ) ! @ # $ % ^ ' "" - , . / ; : [ { } ] ; ' - _ = + ? ` ~ \ |"}));
  6194. string json = JsonConvert.SerializeObject(joe, Formatting.Indented);
  6195. Assert.AreEqual(@"{
  6196. ""Age"": 100,
  6197. ""Name"": ""Joe Employee"",
  6198. ""Manager"": {
  6199. ""Name"": ""Mike Manager""
  6200. }
  6201. }", json);
  6202. }
  6203. [Test]
  6204. public void DeserializeDecimal()
  6205. {
  6206. JsonTextReader reader = new JsonTextReader(new StringReader("1234567890.123456"));
  6207. var settings = new JsonSerializerSettings();
  6208. var serialiser = JsonSerializer.Create(settings);
  6209. decimal? d = serialiser.Deserialize<decimal?>(reader);
  6210. Assert.AreEqual(1234567890.123456m, d);
  6211. }
  6212. #if !(PORTABLE || SILVERLIGHT || NETFX_CORE || WINDOWS_PHONE)
  6213. [Test]
  6214. public void DontSerializeStaticFields()
  6215. {
  6216. string json =
  6217. JsonConvert.SerializeObject(new AnswerFilterModel(), Formatting.Indented, new JsonSerializerSettings
  6218. {
  6219. ContractResolver = new DefaultContractResolver
  6220. {
  6221. IgnoreSerializableAttribute = false
  6222. }
  6223. });
  6224. Assert.AreEqual(@"{
  6225. ""<Active>k__BackingField"": false,
  6226. ""<Ja>k__BackingField"": false,
  6227. ""<Handlungsbedarf>k__BackingField"": false,
  6228. ""<Beratungsbedarf>k__BackingField"": false,
  6229. ""<Unzutreffend>k__BackingField"": false,
  6230. ""<Unbeantwortet>k__BackingField"": false
  6231. }", json);
  6232. }
  6233. #endif
  6234. }
  6235. public enum Antworten
  6236. {
  6237. First,
  6238. Second
  6239. }
  6240. public class SelectListItem
  6241. {
  6242. public string Text { get; set; }
  6243. public string Value { get; set; }
  6244. public bool Selected { get; set; }
  6245. }
  6246. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  6247. [Serializable]
  6248. public class AnswerFilterModel
  6249. {
  6250. [NonSerialized]
  6251. private readonly IList answerValues;
  6252. /// <summary>
  6253. /// Initializes a new instance of the class.
  6254. /// </summary>
  6255. public AnswerFilterModel()
  6256. {
  6257. this.answerValues = (from answer in Enum.GetNames(typeof(Antworten))
  6258. select new SelectListItem { Text = answer, Value = answer, Selected = false })
  6259. .ToList();
  6260. }
  6261. /// <summary>
  6262. /// Gets or sets a value indicating whether active.
  6263. /// </summary>
  6264. public bool Active { get; set; }
  6265. /// <summary>
  6266. /// Gets or sets a value indicating whether ja.
  6267. /// nach bisherigen Antworten.
  6268. /// </summary>
  6269. public bool Ja { get; set; }
  6270. /// <summary>
  6271. /// Gets or sets a value indicating whether handlungsbedarf.
  6272. /// </summary>
  6273. public bool Handlungsbedarf { get; set; }
  6274. /// <summary>
  6275. /// Gets or sets a value indicating whether beratungsbedarf.
  6276. /// </summary>
  6277. public bool Beratungsbedarf { get; set; }
  6278. /// <summary>
  6279. /// Gets or sets a value indicating whether unzutreffend.
  6280. /// </summary>
  6281. public bool Unzutreffend { get; set; }
  6282. /// <summary>
  6283. /// Gets or sets a value indicating whether unbeantwortet.
  6284. /// </summary>
  6285. public bool Unbeantwortet { get; set; }
  6286. /// <summary>
  6287. /// Gets the answer values.
  6288. /// </summary>
  6289. public IEnumerable AnswerValues
  6290. {
  6291. get { return this.answerValues; }
  6292. }
  6293. }
  6294. [Serializable]
  6295. public class PersonSerializable
  6296. {
  6297. public PersonSerializable()
  6298. { }
  6299. private string _name = "";
  6300. public string Name
  6301. {
  6302. get { return _name; }
  6303. set { _name = value; }
  6304. }
  6305. [NonSerialized]
  6306. private int _age = 0;
  6307. public int Age
  6308. {
  6309. get { return _age; }
  6310. set { _age = value; }
  6311. }
  6312. }
  6313. #endif
  6314. public class Event
  6315. {
  6316. public string EventName { get; set; }
  6317. public string Venue { get; set; }
  6318. [JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
  6319. public IList<DateTime> Performances { get; set; }
  6320. }
  6321. public class PropertyItemConverter
  6322. {
  6323. [JsonProperty(ItemConverterType = typeof(MetroStringConverter))]
  6324. public IList<string> Data { get; set; }
  6325. }
  6326. public class PersonWithPrivateConstructor
  6327. {
  6328. private PersonWithPrivateConstructor()
  6329. { }
  6330. public static PersonWithPrivateConstructor CreatePerson()
  6331. {
  6332. return new PersonWithPrivateConstructor();
  6333. }
  6334. public string Name { get; set; }
  6335. public int Age { get; set; }
  6336. }
  6337. public class DateTimeWrapper
  6338. {
  6339. public DateTime Value { get; set; }
  6340. }
  6341. public class Widget1
  6342. {
  6343. public WidgetId1? Id { get; set; }
  6344. }
  6345. [JsonConverter(typeof(WidgetIdJsonConverter))]
  6346. public struct WidgetId1
  6347. {
  6348. public long Value { get; set; }
  6349. }
  6350. public class WidgetIdJsonConverter : JsonConverter
  6351. {
  6352. public override bool CanConvert(Type objectType)
  6353. {
  6354. return objectType == typeof(WidgetId1) || objectType == typeof(WidgetId1?);
  6355. }
  6356. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  6357. {
  6358. WidgetId1 id = (WidgetId1)value;
  6359. writer.WriteValue(id.Value.ToString());
  6360. }
  6361. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  6362. {
  6363. if (reader.TokenType == JsonToken.Null)
  6364. return null;
  6365. return new WidgetId1 { Value = int.Parse(reader.Value.ToString()) };
  6366. }
  6367. }
  6368. public enum MyEnum
  6369. {
  6370. Value1,
  6371. Value2,
  6372. Value3
  6373. }
  6374. public class WithEnums
  6375. {
  6376. public int Id { get; set; }
  6377. public MyEnum? NullableEnum { get; set; }
  6378. }
  6379. public class Item
  6380. {
  6381. public Guid SourceTypeID { get; set; }
  6382. public Guid BrokerID { get; set; }
  6383. public double Latitude { get; set; }
  6384. public double Longitude { get; set; }
  6385. public DateTime TimeStamp { get; set; }
  6386. [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
  6387. public object Payload { get; set; }
  6388. }
  6389. public class NullableGuid
  6390. {
  6391. public Guid? Id { get; set; }
  6392. }
  6393. public class Widget
  6394. {
  6395. public WidgetId? Id { get; set; }
  6396. }
  6397. public struct WidgetId
  6398. {
  6399. public string Value { get; set; }
  6400. }
  6401. public class DecimalTestClass
  6402. {
  6403. public decimal Quantity { get; set; }
  6404. public double OptionalQuantity { get; set; }
  6405. }
  6406. public class TestObject
  6407. {
  6408. public TestObject()
  6409. {
  6410. }
  6411. public TestObject(string name, byte[] data)
  6412. {
  6413. Name = name;
  6414. Data = data;
  6415. }
  6416. public string Name { get; set; }
  6417. public byte[] Data { get; set; }
  6418. }
  6419. public class UriGuidTimeSpanTestClass
  6420. {
  6421. public Guid Guid { get; set; }
  6422. public Guid? NullableGuid { get; set; }
  6423. public TimeSpan TimeSpan { get; set; }
  6424. public TimeSpan? NullableTimeSpan { get; set; }
  6425. public Uri Uri { get; set; }
  6426. }
  6427. internal class Aa
  6428. {
  6429. public int no;
  6430. }
  6431. internal class Bb : Aa
  6432. {
  6433. public new bool no;
  6434. }
  6435. #if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE)
  6436. [JsonObject(MemberSerialization.OptIn)]
  6437. public class GameObject
  6438. {
  6439. [JsonProperty]
  6440. public string Id { get; set; }
  6441. [JsonProperty]
  6442. public string Name { get; set; }
  6443. [JsonProperty] public ConcurrentDictionary<string, Component> Components;
  6444. public GameObject()
  6445. {
  6446. Components = new ConcurrentDictionary<string, Component>();
  6447. }
  6448. }
  6449. [JsonObject(MemberSerialization.OptIn)]
  6450. public class Component
  6451. {
  6452. [JsonIgnore] // Ignore circular reference
  6453. public GameObject GameObject { get; set; }
  6454. public Component()
  6455. {
  6456. }
  6457. }
  6458. [JsonObject(MemberSerialization.OptIn)]
  6459. public class TestComponent : Component
  6460. {
  6461. [JsonProperty]
  6462. public int MyProperty { get; set; }
  6463. public TestComponent()
  6464. {
  6465. }
  6466. }
  6467. #endif
  6468. [JsonObject(MemberSerialization.OptIn)]
  6469. public class TestComponentSimple
  6470. {
  6471. [JsonProperty]
  6472. public int MyProperty { get; set; }
  6473. public TestComponentSimple()
  6474. {
  6475. }
  6476. }
  6477. [JsonObject(ItemRequired = Required.Always)]
  6478. public class RequiredObject
  6479. {
  6480. public int? NonAttributeProperty { get; set; }
  6481. [JsonProperty]
  6482. public int? UnsetProperty { get; set; }
  6483. [JsonProperty(Required = Required.Default)]
  6484. public int? DefaultProperty { get; set; }
  6485. [JsonProperty(Required = Required.AllowNull)]
  6486. public int? AllowNullProperty { get; set; }
  6487. [JsonProperty(Required = Required.Always)]
  6488. public int? AlwaysProperty { get; set; }
  6489. }
  6490. public class MetroStringConverter : JsonConverter
  6491. {
  6492. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  6493. {
  6494. #if !(SILVERLIGHT || NETFX_CORE)
  6495. writer.WriteValue(":::" + value.ToString().ToUpper(CultureInfo.InvariantCulture) + ":::");
  6496. #else
  6497. writer.WriteValue(":::" + value.ToString().ToUpper() + ":::");
  6498. #endif
  6499. }
  6500. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  6501. {
  6502. string s = (string)reader.Value;
  6503. if (s == null)
  6504. return null;
  6505. #if !(SILVERLIGHT || NETFX_CORE)
  6506. return s.ToLower(CultureInfo.InvariantCulture).Trim(new[] { ':' });
  6507. #else
  6508. return s.ToLower().Trim(new[] { ':' });
  6509. #endif
  6510. }
  6511. public override bool CanConvert(Type objectType)
  6512. {
  6513. return objectType == typeof(string);
  6514. }
  6515. }
  6516. public class MetroPropertyNameResolver : DefaultContractResolver
  6517. {
  6518. protected internal override string ResolvePropertyName(string propertyName)
  6519. {
  6520. #if !(SILVERLIGHT || NETFX_CORE)
  6521. return ":::" + propertyName.ToUpper(CultureInfo.InvariantCulture) + ":::";
  6522. #else
  6523. return ":::" + propertyName.ToUpper() + ":::";
  6524. #endif
  6525. }
  6526. }
  6527. #if !(NET20 || NET35)
  6528. [DataContract]
  6529. public class DataContractSerializationAttributesClass
  6530. {
  6531. public string NoAttribute { get; set; }
  6532. [IgnoreDataMember]
  6533. public string IgnoreDataMemberAttribute { get; set; }
  6534. [DataMember]
  6535. public string DataMemberAttribute { get; set; }
  6536. [IgnoreDataMember]
  6537. [DataMember]
  6538. public string IgnoreDataMemberAndDataMemberAttribute { get; set; }
  6539. }
  6540. public class PocoDataContractSerializationAttributesClass
  6541. {
  6542. public string NoAttribute { get; set; }
  6543. [IgnoreDataMember]
  6544. public string IgnoreDataMemberAttribute { get; set; }
  6545. [DataMember]
  6546. public string DataMemberAttribute { get; set; }
  6547. [IgnoreDataMember]
  6548. [DataMember]
  6549. public string IgnoreDataMemberAndDataMemberAttribute { get; set; }
  6550. }
  6551. #endif
  6552. public class Array2D
  6553. {
  6554. public string Before { get; set; }
  6555. public int[,] Coordinates { get; set; }
  6556. public string After { get; set; }
  6557. }
  6558. public class Array3D
  6559. {
  6560. public string Before { get; set; }
  6561. public int[,,] Coordinates { get; set; }
  6562. public string After { get; set; }
  6563. }
  6564. public class Array3DWithConverter
  6565. {
  6566. public string Before { get; set; }
  6567. [JsonProperty(ItemConverterType = typeof(IntToFloatConverter))]
  6568. public int[, ,] Coordinates { get; set; }
  6569. public string After { get; set; }
  6570. }
  6571. public class IntToFloatConverter : JsonConverter
  6572. {
  6573. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  6574. {
  6575. writer.WriteValue(Convert.ToDouble(value));
  6576. }
  6577. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  6578. {
  6579. return Convert.ToInt32(reader.Value);
  6580. }
  6581. public override bool CanConvert(Type objectType)
  6582. {
  6583. return objectType == typeof (int);
  6584. }
  6585. }
  6586. public class ShouldSerializeTestClass
  6587. {
  6588. internal bool _shouldSerializeName;
  6589. public string Name { get; set; }
  6590. public int Age { get; set; }
  6591. public void ShouldSerializeAge()
  6592. {
  6593. // dummy. should never be used because it doesn't return bool
  6594. }
  6595. public bool ShouldSerializeName()
  6596. {
  6597. return _shouldSerializeName;
  6598. }
  6599. }
  6600. public class SpecifiedTestClass
  6601. {
  6602. private bool _nameSpecified;
  6603. public string Name { get; set; }
  6604. public int Age { get; set; }
  6605. public int Weight { get; set; }
  6606. public int Height { get; set; }
  6607. public int FavoriteNumber { get; set; }
  6608. // dummy. should never be used because it isn't of type bool
  6609. [JsonIgnore]
  6610. public long AgeSpecified { get; set; }
  6611. [JsonIgnore]
  6612. public bool NameSpecified
  6613. {
  6614. get { return _nameSpecified; }
  6615. set { _nameSpecified = value; }
  6616. }
  6617. [JsonIgnore]
  6618. public bool WeightSpecified;
  6619. [JsonIgnore]
  6620. [System.Xml.Serialization.XmlIgnoreAttribute]
  6621. public bool HeightSpecified;
  6622. [JsonIgnore]
  6623. public bool FavoriteNumberSpecified
  6624. {
  6625. // get only example
  6626. get { return FavoriteNumber != 0; }
  6627. }
  6628. }
  6629. }