PageRenderTime 64ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 1ms

/DotNet/ThirdParty/Json45r10/Source/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs

https://github.com/gbeatty/czml-writer
C# | 7562 lines | 6792 code | 636 blank | 134 comment | 76 complexity | 74b9f69467d0e48aa820dc0d93bae23c MD5 | raw file
Possible License(s): Apache-2.0, CC-BY-SA-3.0, LGPL-2.1

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

  1. #region License
  2. // Copyright (c) 2007 James Newton-King
  3. //
  4. // Permission is hereby granted, free of charge, to any person
  5. // obtaining a copy of this software and associated documentation
  6. // files (the "Software"), to deal in the Software without
  7. // restriction, including without limitation the rights to use,
  8. // copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the
  10. // Software is furnished to do so, subject to the following
  11. // conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  18. // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  20. // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21. // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23. // OTHER DEALINGS IN THE SOFTWARE.
  24. #endregion
  25. using System;
  26. #if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE)
  27. using System.Collections.Concurrent;
  28. #endif
  29. using System.Collections.Generic;
  30. #if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE
  31. using System.ComponentModel.DataAnnotations;
  32. using System.Configuration;
  33. using System.Runtime.CompilerServices;
  34. using System.Runtime.Serialization.Formatters;
  35. using System.Threading;
  36. using System.Web.Script.Serialization;
  37. #endif
  38. using System.Text;
  39. #if !NETFX_CORE
  40. using NUnit.Framework;
  41. #else
  42. using Microsoft.VisualStudio.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 !PocketPC && !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 !PocketPC && !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 !PocketPC && !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);

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