PageRenderTime 103ms CodeModel.GetById 28ms RepoModel.GetById 0ms 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
  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);
  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 !PocketPC && !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 !PocketPC && !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 && !PocketPC && !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. public class ShouldSerializeTestClass
  3242. {
  3243. internal bool _shouldSerializeName;
  3244. public string Name { get; set; }
  3245. public int Age { get; set; }
  3246. public void ShouldSerializeAge()
  3247. {
  3248. // dummy. should never be used because it doesn't return bool
  3249. }
  3250. public bool ShouldSerializeName()
  3251. {
  3252. return _shouldSerializeName;
  3253. }
  3254. }
  3255. [Test]
  3256. public void ShouldSerializeTest()
  3257. {
  3258. ShouldSerializeTestClass c = new ShouldSerializeTestClass();
  3259. c.Name = "James";
  3260. c.Age = 27;
  3261. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3262. Assert.AreEqual(@"{
  3263. ""Age"": 27
  3264. }", json);
  3265. c._shouldSerializeName = true;
  3266. json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3267. Assert.AreEqual(@"{
  3268. ""Name"": ""James"",
  3269. ""Age"": 27
  3270. }", json);
  3271. ShouldSerializeTestClass deserialized = JsonConvert.DeserializeObject<ShouldSerializeTestClass>(json);
  3272. Assert.AreEqual("James", deserialized.Name);
  3273. Assert.AreEqual(27, deserialized.Age);
  3274. }
  3275. public class Employee
  3276. {
  3277. public string Name { get; set; }
  3278. public Employee Manager { get; set; }
  3279. public bool ShouldSerializeManager()
  3280. {
  3281. return (Manager != this);
  3282. }
  3283. }
  3284. [Test]
  3285. public void ShouldSerializeExample()
  3286. {
  3287. Employee joe = new Employee();
  3288. joe.Name = "Joe Employee";
  3289. Employee mike = new Employee();
  3290. mike.Name = "Mike Manager";
  3291. joe.Manager = mike;
  3292. mike.Manager = mike;
  3293. string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented);
  3294. // [
  3295. // {
  3296. // "Name": "Joe Employee",
  3297. // "Manager": {
  3298. // "Name": "Mike Manager"
  3299. // }
  3300. // },
  3301. // {
  3302. // "Name": "Mike Manager"
  3303. // }
  3304. // ]
  3305. Console.WriteLine(json);
  3306. }
  3307. public class SpecifiedTestClass
  3308. {
  3309. private bool _nameSpecified;
  3310. public string Name { get; set; }
  3311. public int Age { get; set; }
  3312. public int Weight { get; set; }
  3313. public int Height { get; set; }
  3314. public int FavoriteNumber { get; set; }
  3315. // dummy. should never be used because it isn't of type bool
  3316. [JsonIgnore]
  3317. public long AgeSpecified { get; set; }
  3318. [JsonIgnore]
  3319. public bool NameSpecified
  3320. {
  3321. get { return _nameSpecified; }
  3322. set { _nameSpecified = value; }
  3323. }
  3324. [JsonIgnore]
  3325. public bool WeightSpecified;
  3326. [JsonIgnore]
  3327. [System.Xml.Serialization.XmlIgnoreAttribute]
  3328. public bool HeightSpecified;
  3329. [JsonIgnore]
  3330. public bool FavoriteNumberSpecified
  3331. {
  3332. // get only example
  3333. get { return FavoriteNumber != 0; }
  3334. }
  3335. }
  3336. [Test]
  3337. public void SpecifiedTest()
  3338. {
  3339. SpecifiedTestClass c = new SpecifiedTestClass();
  3340. c.Name = "James";
  3341. c.Age = 27;
  3342. c.NameSpecified = false;
  3343. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3344. Assert.AreEqual(@"{
  3345. ""Age"": 27
  3346. }", json);
  3347. SpecifiedTestClass deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json);
  3348. Assert.IsNull(deserialized.Name);
  3349. Assert.IsFalse(deserialized.NameSpecified);
  3350. Assert.IsFalse(deserialized.WeightSpecified);
  3351. Assert.IsFalse(deserialized.HeightSpecified);
  3352. Assert.IsFalse(deserialized.FavoriteNumberSpecified);
  3353. Assert.AreEqual(27, deserialized.Age);
  3354. c.NameSpecified = true;
  3355. c.WeightSpecified = true;
  3356. c.HeightSpecified = true;
  3357. c.FavoriteNumber = 23;
  3358. json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3359. Assert.AreEqual(@"{
  3360. ""Name"": ""James"",
  3361. ""Age"": 27,
  3362. ""Weight"": 0,
  3363. ""Height"": 0,
  3364. ""FavoriteNumber"": 23
  3365. }", json);
  3366. deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json);
  3367. Assert.AreEqual("James", deserialized.Name);
  3368. Assert.IsTrue(deserialized.NameSpecified);
  3369. Assert.IsTrue(deserialized.WeightSpecified);
  3370. Assert.IsTrue(deserialized.HeightSpecified);
  3371. Assert.IsTrue(deserialized.FavoriteNumberSpecified);
  3372. Assert.AreEqual(27, deserialized.Age);
  3373. Assert.AreEqual(23, deserialized.FavoriteNumber);
  3374. }
  3375. // [Test]
  3376. // public void XmlSerializerSpecifiedTrueTest()
  3377. // {
  3378. // XmlSerializer s = new XmlSerializer(typeof(OptionalOrder));
  3379. // StringWriter sw = new StringWriter();
  3380. // s.Serialize(sw, new OptionalOrder() { FirstOrder = "First", FirstOrderSpecified = true });
  3381. // Console.WriteLine(sw.ToString());
  3382. // string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
  3383. //<OptionalOrder xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  3384. // <FirstOrder>First</FirstOrder>
  3385. //</OptionalOrder>";
  3386. // OptionalOrder o = (OptionalOrder)s.Deserialize(new StringReader(xml));
  3387. // Console.WriteLine(o.FirstOrder);
  3388. // Console.WriteLine(o.FirstOrderSpecified);
  3389. // }
  3390. // [Test]
  3391. // public void XmlSerializerSpecifiedFalseTest()
  3392. // {
  3393. // XmlSerializer s = new XmlSerializer(typeof(OptionalOrder));
  3394. // StringWriter sw = new StringWriter();
  3395. // s.Serialize(sw, new OptionalOrder() { FirstOrder = "First", FirstOrderSpecified = false });
  3396. // Console.WriteLine(sw.ToString());
  3397. // // string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
  3398. // //<OptionalOrder xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  3399. // // <FirstOrder>First</FirstOrder>
  3400. // //</OptionalOrder>";
  3401. // // OptionalOrder o = (OptionalOrder)s.Deserialize(new StringReader(xml));
  3402. // // Console.WriteLine(o.FirstOrder);
  3403. // // Console.WriteLine(o.FirstOrderSpecified);
  3404. // }
  3405. public class OptionalOrder
  3406. {
  3407. // This field shouldn't be serialized
  3408. // if it is uninitialized.
  3409. public string FirstOrder;
  3410. // Use the XmlIgnoreAttribute to ignore the
  3411. // special field named "FirstOrderSpecified".
  3412. [System.Xml.Serialization.XmlIgnoreAttribute]
  3413. public bool FirstOrderSpecified;
  3414. }
  3415. public class FamilyDetails
  3416. {
  3417. public string Name { get; set; }
  3418. public int NumberOfChildren { get; set; }
  3419. [JsonIgnore]
  3420. public bool NumberOfChildrenSpecified { get; set; }
  3421. }
  3422. [Test]
  3423. public void SpecifiedExample()
  3424. {
  3425. FamilyDetails joe = new FamilyDetails();
  3426. joe.Name = "Joe Family Details";
  3427. joe.NumberOfChildren = 4;
  3428. joe.NumberOfChildrenSpecified = true;
  3429. FamilyDetails martha = new FamilyDetails();
  3430. martha.Name = "Martha Family Details";
  3431. martha.NumberOfChildren = 3;
  3432. martha.NumberOfChildrenSpecified = false;
  3433. string json = JsonConvert.SerializeObject(new[] { joe, martha }, Formatting.Indented);
  3434. //[
  3435. // {
  3436. // "Name": "Joe Family Details",
  3437. // "NumberOfChildren": 4
  3438. // },
  3439. // {
  3440. // "Name": "Martha Family Details"
  3441. // }
  3442. //]
  3443. Console.WriteLine(json);
  3444. string mikeString = "{\"Name\": \"Mike Person\"}";
  3445. FamilyDetails mike = JsonConvert.DeserializeObject<FamilyDetails>(mikeString);
  3446. Console.WriteLine("mikeString specifies number of children: {0}", mike.NumberOfChildrenSpecified);
  3447. string mikeFullDisclosureString = "{\"Name\": \"Mike Person\", \"NumberOfChildren\": \"0\"}";
  3448. mike = JsonConvert.DeserializeObject<FamilyDetails>(mikeFullDisclosureString);
  3449. Console.WriteLine("mikeString specifies number of children: {0}", mike.NumberOfChildrenSpecified);
  3450. }
  3451. public class DictionaryKey
  3452. {
  3453. public string Value { get; set; }
  3454. public override string ToString()
  3455. {
  3456. return Value;
  3457. }
  3458. public static implicit operator DictionaryKey(string value)
  3459. {
  3460. return new DictionaryKey() { Value = value };
  3461. }
  3462. }
  3463. [Test]
  3464. public void SerializeDeserializeDictionaryKey()
  3465. {
  3466. Dictionary<DictionaryKey, string> dictionary = new Dictionary<DictionaryKey, string>();
  3467. dictionary.Add(new DictionaryKey() { Value = "First!" }, "First");
  3468. dictionary.Add(new DictionaryKey() { Value = "Second!" }, "Second");
  3469. string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
  3470. Assert.AreEqual(@"{
  3471. ""First!"": ""First"",
  3472. ""Second!"": ""Second""
  3473. }", json);
  3474. Dictionary<DictionaryKey, string> newDictionary =
  3475. JsonConvert.DeserializeObject<Dictionary<DictionaryKey, string>>(json);
  3476. Assert.AreEqual(2, newDictionary.Count);
  3477. }
  3478. [Test]
  3479. public void SerializeNullableArray()
  3480. {
  3481. string jsonText = JsonConvert.SerializeObject(new double?[] { 2.4, 4.3, null }, Formatting.Indented);
  3482. Assert.AreEqual(@"[
  3483. 2.4,
  3484. 4.3,
  3485. null
  3486. ]", jsonText);
  3487. double?[] d = (double?[])JsonConvert.DeserializeObject(jsonText, typeof(double?[]));
  3488. Assert.AreEqual(3, d.Length);
  3489. Assert.AreEqual(2.4, d[0]);
  3490. Assert.AreEqual(4.3, d[1]);
  3491. Assert.AreEqual(null, d[2]);
  3492. }
  3493. #if !SILVERLIGHT && !NET20 && !PocketPC
  3494. [Test]
  3495. public void SerializeHashSet()
  3496. {
  3497. string jsonText = JsonConvert.SerializeObject(new HashSet<string>()
  3498. {
  3499. "One",
  3500. "2",
  3501. "III"
  3502. }, Formatting.Indented);
  3503. Assert.AreEqual(@"[
  3504. ""One"",
  3505. ""2"",
  3506. ""III""
  3507. ]", jsonText);
  3508. HashSet<string> d = JsonConvert.DeserializeObject<HashSet<string>>(jsonText);
  3509. Assert.AreEqual(3, d.Count);
  3510. Assert.IsTrue(d.Contains("One"));
  3511. Assert.IsTrue(d.Contains("2"));
  3512. Assert.IsTrue(d.Contains("III"));
  3513. }
  3514. #endif
  3515. private class MyClass
  3516. {
  3517. public byte[] Prop1 { get; set; }
  3518. public MyClass()
  3519. {
  3520. Prop1 = new byte[0];
  3521. }
  3522. }
  3523. [Test]
  3524. public void DeserializeByteArray()
  3525. {
  3526. JsonSerializer serializer1 = new JsonSerializer();
  3527. serializer1.Converters.Add(new IsoDateTimeConverter());
  3528. serializer1.NullValueHandling = NullValueHandling.Ignore;
  3529. string json = @"[{""Prop1"":""""},{""Prop1"":""""}]";
  3530. JsonTextReader reader = new JsonTextReader(new StringReader(json));
  3531. MyClass[] z = (MyClass[])serializer1.Deserialize(reader, typeof(MyClass[]));
  3532. Assert.AreEqual(2, z.Length);
  3533. Assert.AreEqual(0, z[0].Prop1.Length);
  3534. Assert.AreEqual(0, z[1].Prop1.Length);
  3535. }
  3536. #if !NET20 && !PocketPC && !SILVERLIGHT && !NETFX_CORE
  3537. public class StringDictionaryTestClass
  3538. {
  3539. public StringDictionary StringDictionaryProperty { get; set; }
  3540. }
  3541. [Test]
  3542. public void StringDictionaryTest()
  3543. {
  3544. string classRef = typeof(StringDictionary).FullName;
  3545. StringDictionaryTestClass s1 = new StringDictionaryTestClass()
  3546. {
  3547. StringDictionaryProperty = new StringDictionary()
  3548. {
  3549. {"1", "One"},
  3550. {"2", "II"},
  3551. {"3", "3"}
  3552. }
  3553. };
  3554. string json = JsonConvert.SerializeObject(s1, Formatting.Indented);
  3555. ExceptionAssert.Throws<InvalidOperationException>(
  3556. "Cannot create and populate list type " + classRef + ".",
  3557. () =>
  3558. {
  3559. JsonConvert.DeserializeObject<StringDictionaryTestClass>(json);
  3560. });
  3561. }
  3562. #endif
  3563. [JsonObject(MemberSerialization.OptIn)]
  3564. public struct StructWithAttribute
  3565. {
  3566. public string MyString { get; set; }
  3567. [JsonProperty]
  3568. public int MyInt { get; set; }
  3569. }
  3570. [Test]
  3571. public void SerializeStructWithJsonObjectAttribute()
  3572. {
  3573. StructWithAttribute testStruct = new StructWithAttribute
  3574. {
  3575. MyInt = int.MaxValue
  3576. };
  3577. string json = JsonConvert.SerializeObject(testStruct, Formatting.Indented);
  3578. Assert.AreEqual(@"{
  3579. ""MyInt"": 2147483647
  3580. }", json);
  3581. StructWithAttribute newStruct = JsonConvert.DeserializeObject<StructWithAttribute>(json);
  3582. Assert.AreEqual(int.MaxValue, newStruct.MyInt);
  3583. }
  3584. public class TimeZoneOffsetObject
  3585. {
  3586. public DateTimeOffset Offset { get; set; }
  3587. }
  3588. #if !NET20
  3589. [Test]
  3590. public void ReadWriteTimeZoneOffsetIso()
  3591. {
  3592. var serializeObject = JsonConvert.SerializeObject(new TimeZoneOffsetObject
  3593. {
  3594. Offset = new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6))
  3595. });
  3596. Assert.AreEqual("{\"Offset\":\"2000-01-01T00:00:00+06:00\"}", serializeObject);
  3597. var deserializeObject = JsonConvert.DeserializeObject<TimeZoneOffsetObject>(serializeObject);
  3598. Assert.AreEqual(TimeSpan.FromHours(6), deserializeObject.Offset.Offset);
  3599. Assert.AreEqual(new DateTime(2000, 1, 1), deserializeObject.Offset.Date);
  3600. }
  3601. [Test]
  3602. public void DeserializePropertyNullableDateTimeOffsetExactIso()
  3603. {
  3604. NullableDateTimeTestClass d = JsonConvert.DeserializeObject<NullableDateTimeTestClass>("{\"DateTimeOffsetField\":\"2000-01-01T00:00:00+06:00\"}");
  3605. Assert.AreEqual(new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6)), d.DateTimeOffsetField);
  3606. }
  3607. [Test]
  3608. public void ReadWriteTimeZoneOffsetMsAjax()
  3609. {
  3610. var serializeObject = JsonConvert.SerializeObject(new TimeZoneOffsetObject
  3611. {
  3612. Offset = new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6))
  3613. }, Formatting.None, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
  3614. Assert.AreEqual("{\"Offset\":\"\\/Date(946663200000+0600)\\/\"}", serializeObject);
  3615. var deserializeObject = JsonConvert.DeserializeObject<TimeZoneOffsetObject>(serializeObject);
  3616. Assert.AreEqual(TimeSpan.FromHours(6), deserializeObject.Offset.Offset);
  3617. Assert.AreEqual(new DateTime(2000, 1, 1), deserializeObject.Offset.Date);
  3618. }
  3619. [Test]
  3620. public void DeserializePropertyNullableDateTimeOffsetExactMsAjax()
  3621. {
  3622. NullableDateTimeTestClass d = JsonConvert.DeserializeObject<NullableDateTimeTestClass>("{\"DateTimeOffsetField\":\"\\/Date(946663200000+0600)\\/\"}");
  3623. Assert.AreEqual(new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6)), d.DateTimeOffsetField);
  3624. }
  3625. #endif
  3626. public abstract class LogEvent
  3627. {
  3628. [JsonProperty("event")]
  3629. public abstract string EventName { get; }
  3630. }
  3631. public class DerivedEvent : LogEvent
  3632. {
  3633. public override string EventName
  3634. {
  3635. get { return "derived"; }
  3636. }
  3637. }
  3638. [Test]
  3639. public void OverridenPropertyMembers()
  3640. {
  3641. string json = JsonConvert.SerializeObject(new DerivedEvent(), Formatting.Indented);
  3642. Assert.AreEqual(@"{
  3643. ""event"": ""derived""
  3644. }", json);
  3645. }
  3646. #if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
  3647. [Test]
  3648. public void SerializeExpandoObject()
  3649. {
  3650. dynamic expando = new ExpandoObject();
  3651. expando.Int = 1;
  3652. expando.Decimal = 99.9d;
  3653. expando.Complex = new ExpandoObject();
  3654. expando.Complex.String = "I am a string";
  3655. expando.Complex.DateTime = new DateTime(2000, 12, 20, 18, 55, 0, DateTimeKind.Utc);
  3656. string json = JsonConvert.SerializeObject(expando, Formatting.Indented);
  3657. Assert.AreEqual(@"{
  3658. ""Int"": 1,
  3659. ""Decimal"": 99.9,
  3660. ""Complex"": {
  3661. ""String"": ""I am a string"",
  3662. ""DateTime"": ""2000-12-20T18:55:00Z""
  3663. }
  3664. }", json);
  3665. IDictionary<string, object> newExpando = JsonConvert.DeserializeObject<ExpandoObject>(json);
  3666. CustomAssert.IsInstanceOfType(typeof(long), newExpando["Int"]);
  3667. Assert.AreEqual((long)expando.Int, newExpando["Int"]);
  3668. CustomAssert.IsInstanceOfType(typeof(double), newExpando["Decimal"]);
  3669. Assert.AreEqual(expando.Decimal, newExpando["Decimal"]);
  3670. CustomAssert.IsInstanceOfType(typeof(ExpandoObject), newExpando["Complex"]);
  3671. IDictionary<string, object> o = (ExpandoObject)newExpando["Complex"];
  3672. CustomAssert.IsInstanceOfType(typeof(string), o["String"]);
  3673. Assert.AreEqual(expando.Complex.String, o["String"]);
  3674. CustomAssert.IsInstanceOfType(typeof(DateTime), o["DateTime"]);
  3675. Assert.AreEqual(expando.Complex.DateTime, o["DateTime"]);
  3676. }
  3677. #endif
  3678. [Test]
  3679. public void DeserializeDecimalExact()
  3680. {
  3681. decimal d = JsonConvert.DeserializeObject<decimal>("123456789876543.21");
  3682. Assert.AreEqual(123456789876543.21m, d);
  3683. }
  3684. [Test]
  3685. public void DeserializeNullableDecimalExact()
  3686. {
  3687. decimal? d = JsonConvert.DeserializeObject<decimal?>("123456789876543.21");
  3688. Assert.AreEqual(123456789876543.21m, d);
  3689. }
  3690. [Test]
  3691. public void DeserializeDecimalPropertyExact()
  3692. {
  3693. string json = "{Amount:123456789876543.21}";
  3694. Invoice i = JsonConvert.DeserializeObject<Invoice>(json);
  3695. Assert.AreEqual(123456789876543.21m, i.Amount);
  3696. }
  3697. [Test]
  3698. public void DeserializeDecimalArrayExact()
  3699. {
  3700. string json = "[123456789876543.21]";
  3701. IList<decimal> a = JsonConvert.DeserializeObject<IList<decimal>>(json);
  3702. Assert.AreEqual(123456789876543.21m, a[0]);
  3703. }
  3704. [Test]
  3705. public void DeserializeDecimalDictionaryExact()
  3706. {
  3707. string json = "{'Value':123456789876543.21}";
  3708. IDictionary<string, decimal> d = JsonConvert.DeserializeObject<IDictionary<string, decimal>>(json);
  3709. Assert.AreEqual(123456789876543.21m, d["Value"]);
  3710. }
  3711. public struct Vector
  3712. {
  3713. public float X;
  3714. public float Y;
  3715. public float Z;
  3716. public override string ToString()
  3717. {
  3718. return string.Format("({0},{1},{2})", X, Y, Z);
  3719. }
  3720. }
  3721. public class VectorParent
  3722. {
  3723. public Vector Position;
  3724. }
  3725. [Test]
  3726. public void DeserializeStructProperty()
  3727. {
  3728. VectorParent obj = new VectorParent();
  3729. obj.Position = new Vector { X = 1, Y = 2, Z = 3 };
  3730. string str = JsonConvert.SerializeObject(obj);
  3731. obj = JsonConvert.DeserializeObject<VectorParent>(str);
  3732. Assert.AreEqual(1, obj.Position.X);
  3733. Assert.AreEqual(2, obj.Position.Y);
  3734. Assert.AreEqual(3, obj.Position.Z);
  3735. }
  3736. [JsonObject(MemberSerialization.OptIn)]
  3737. public class Derived : Base
  3738. {
  3739. [JsonProperty]
  3740. public string IDoWork { get; private set; }
  3741. private Derived()
  3742. {
  3743. }
  3744. internal Derived(string dontWork, string doWork)
  3745. : base(dontWork)
  3746. {
  3747. IDoWork = doWork;
  3748. }
  3749. }
  3750. [JsonObject(MemberSerialization.OptIn)]
  3751. public class Base
  3752. {
  3753. [JsonProperty]
  3754. public string IDontWork { get; private set; }
  3755. protected Base()
  3756. {
  3757. }
  3758. internal Base(string dontWork)
  3759. {
  3760. IDontWork = dontWork;
  3761. }
  3762. }
  3763. [Test]
  3764. public void PrivateSetterOnBaseClassProperty()
  3765. {
  3766. var derived = new Derived("meh", "woo");
  3767. var settings = new JsonSerializerSettings
  3768. {
  3769. TypeNameHandling = TypeNameHandling.Objects,
  3770. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
  3771. };
  3772. string json = JsonConvert.SerializeObject(derived, Formatting.Indented, settings);
  3773. var meh = JsonConvert.DeserializeObject<Base>(json, settings);
  3774. Assert.AreEqual(((Derived)meh).IDoWork, "woo");
  3775. Assert.AreEqual(meh.IDontWork, "meh");
  3776. }
  3777. #if !(SILVERLIGHT || PocketPC || NET20 || NETFX_CORE)
  3778. [DataContract]
  3779. public struct StructISerializable : ISerializable
  3780. {
  3781. private string _name;
  3782. public StructISerializable(SerializationInfo info, StreamingContext context)
  3783. {
  3784. _name = info.GetString("Name");
  3785. }
  3786. [DataMember]
  3787. public string Name
  3788. {
  3789. get { return _name; }
  3790. set { _name = value; }
  3791. }
  3792. public void GetObjectData(SerializationInfo info, StreamingContext context)
  3793. {
  3794. info.AddValue("Name", _name);
  3795. }
  3796. }
  3797. [DataContract]
  3798. public class NullableStructPropertyClass
  3799. {
  3800. private StructISerializable _foo1;
  3801. private StructISerializable? _foo2;
  3802. [DataMember]
  3803. public StructISerializable Foo1
  3804. {
  3805. get { return _foo1; }
  3806. set { _foo1 = value; }
  3807. }
  3808. [DataMember]
  3809. public StructISerializable? Foo2
  3810. {
  3811. get { return _foo2; }
  3812. set { _foo2 = value; }
  3813. }
  3814. }
  3815. [Test]
  3816. public void DeserializeNullableStruct()
  3817. {
  3818. NullableStructPropertyClass nullableStructPropertyClass = new NullableStructPropertyClass();
  3819. nullableStructPropertyClass.Foo1 = new StructISerializable() { Name = "foo 1" };
  3820. nullableStructPropertyClass.Foo2 = new StructISerializable() { Name = "foo 2" };
  3821. NullableStructPropertyClass barWithNull = new NullableStructPropertyClass();
  3822. barWithNull.Foo1 = new StructISerializable() { Name = "foo 1" };
  3823. barWithNull.Foo2 = null;
  3824. //throws error on deserialization because bar1.Foo2 is of type Foo?
  3825. string s = JsonConvert.SerializeObject(nullableStructPropertyClass);
  3826. NullableStructPropertyClass deserialized = deserialize(s);
  3827. Assert.AreEqual(deserialized.Foo1.Name, "foo 1");
  3828. Assert.AreEqual(deserialized.Foo2.Value.Name, "foo 2");
  3829. //no error Foo2 is null
  3830. s = JsonConvert.SerializeObject(barWithNull);
  3831. deserialized = deserialize(s);
  3832. Assert.AreEqual(deserialized.Foo1.Name, "foo 1");
  3833. Assert.AreEqual(deserialized.Foo2, null);
  3834. }
  3835. private static NullableStructPropertyClass deserialize(string serStr)
  3836. {
  3837. return JsonConvert.DeserializeObject<NullableStructPropertyClass>(
  3838. serStr,
  3839. new JsonSerializerSettings
  3840. {
  3841. NullValueHandling = NullValueHandling.Ignore,
  3842. MissingMemberHandling = MissingMemberHandling.Ignore
  3843. });
  3844. }
  3845. #endif
  3846. public class Response
  3847. {
  3848. public string Name { get; set; }
  3849. public JToken Data { get; set; }
  3850. }
  3851. [Test]
  3852. public void DeserializeJToken()
  3853. {
  3854. Response response = new Response
  3855. {
  3856. Name = "Success",
  3857. Data = new JObject(new JProperty("First", "Value1"), new JProperty("Second", "Value2"))
  3858. };
  3859. string json = JsonConvert.SerializeObject(response, Formatting.Indented);
  3860. Response deserializedResponse = JsonConvert.DeserializeObject<Response>(json);
  3861. Assert.AreEqual("Success", deserializedResponse.Name);
  3862. Assert.IsTrue(deserializedResponse.Data.DeepEquals(response.Data));
  3863. }
  3864. public abstract class Test<T>
  3865. {
  3866. public abstract T Value { get; set; }
  3867. }
  3868. [JsonObject(MemberSerialization.OptIn)]
  3869. public class DecimalTest : Test<decimal>
  3870. {
  3871. protected DecimalTest()
  3872. {
  3873. }
  3874. public DecimalTest(decimal val)
  3875. {
  3876. Value = val;
  3877. }
  3878. [JsonProperty]
  3879. public override decimal Value { get; set; }
  3880. }
  3881. [Test]
  3882. public void OnError()
  3883. {
  3884. var data = new DecimalTest(decimal.MinValue);
  3885. var json = JsonConvert.SerializeObject(data);
  3886. var obj = JsonConvert.DeserializeObject<DecimalTest>(json);
  3887. Assert.AreEqual(decimal.MinValue, obj.Value);
  3888. }
  3889. public class NonPublicConstructorWithJsonConstructor
  3890. {
  3891. public string Value { get; private set; }
  3892. public string Constructor { get; private set; }
  3893. [JsonConstructor]
  3894. private NonPublicConstructorWithJsonConstructor()
  3895. {
  3896. Constructor = "NonPublic";
  3897. }
  3898. public NonPublicConstructorWithJsonConstructor(string value)
  3899. {
  3900. Value = value;
  3901. Constructor = "Public Paramatized";
  3902. }
  3903. }
  3904. [Test]
  3905. public void NonPublicConstructorWithJsonConstructorTest()
  3906. {
  3907. NonPublicConstructorWithJsonConstructor c = JsonConvert.DeserializeObject<NonPublicConstructorWithJsonConstructor>("{}");
  3908. Assert.AreEqual("NonPublic", c.Constructor);
  3909. }
  3910. public class PublicConstructorOverridenByJsonConstructor
  3911. {
  3912. public string Value { get; private set; }
  3913. public string Constructor { get; private set; }
  3914. public PublicConstructorOverridenByJsonConstructor()
  3915. {
  3916. Constructor = "NonPublic";
  3917. }
  3918. [JsonConstructor]
  3919. public PublicConstructorOverridenByJsonConstructor(string value)
  3920. {
  3921. Value = value;
  3922. Constructor = "Public Paramatized";
  3923. }
  3924. }
  3925. [Test]
  3926. public void PublicConstructorOverridenByJsonConstructorTest()
  3927. {
  3928. PublicConstructorOverridenByJsonConstructor c = JsonConvert.DeserializeObject<PublicConstructorOverridenByJsonConstructor>("{Value:'value!'}");
  3929. Assert.AreEqual("Public Paramatized", c.Constructor);
  3930. Assert.AreEqual("value!", c.Value);
  3931. }
  3932. public class MultipleParamatrizedConstructorsJsonConstructor
  3933. {
  3934. public string Value { get; private set; }
  3935. public int Age { get; private set; }
  3936. public string Constructor { get; private set; }
  3937. public MultipleParamatrizedConstructorsJsonConstructor(string value)
  3938. {
  3939. Value = value;
  3940. Constructor = "Public Paramatized 1";
  3941. }
  3942. [JsonConstructor]
  3943. public MultipleParamatrizedConstructorsJsonConstructor(string value, int age)
  3944. {
  3945. Value = value;
  3946. Age = age;
  3947. Constructor = "Public Paramatized 2";
  3948. }
  3949. }
  3950. [Test]
  3951. public void MultipleParamatrizedConstructorsJsonConstructorTest()
  3952. {
  3953. MultipleParamatrizedConstructorsJsonConstructor c = JsonConvert.DeserializeObject<MultipleParamatrizedConstructorsJsonConstructor>("{Value:'value!', Age:1}");
  3954. Assert.AreEqual("Public Paramatized 2", c.Constructor);
  3955. Assert.AreEqual("value!", c.Value);
  3956. Assert.AreEqual(1, c.Age);
  3957. }
  3958. public class EnumerableClass
  3959. {
  3960. public IEnumerable<string> Enumerable { get; set; }
  3961. }
  3962. [Test]
  3963. public void DeserializeEnumerable()
  3964. {
  3965. EnumerableClass c = new EnumerableClass
  3966. {
  3967. Enumerable = new List<string> { "One", "Two", "Three" }
  3968. };
  3969. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3970. Assert.AreEqual(@"{
  3971. ""Enumerable"": [
  3972. ""One"",
  3973. ""Two"",
  3974. ""Three""
  3975. ]
  3976. }", json);
  3977. EnumerableClass c2 = JsonConvert.DeserializeObject<EnumerableClass>(json);
  3978. Assert.AreEqual("One", c2.Enumerable.ElementAt(0));
  3979. Assert.AreEqual("Two", c2.Enumerable.ElementAt(1));
  3980. Assert.AreEqual("Three", c2.Enumerable.ElementAt(2));
  3981. }
  3982. [JsonObject(MemberSerialization.OptIn)]
  3983. public class ItemBase
  3984. {
  3985. [JsonProperty]
  3986. public string Name { get; set; }
  3987. }
  3988. public class ComplexItem : ItemBase
  3989. {
  3990. public Stream Source { get; set; }
  3991. }
  3992. [Test]
  3993. public void SerializeAttributesOnBase()
  3994. {
  3995. ComplexItem i = new ComplexItem();
  3996. string json = JsonConvert.SerializeObject(i, Formatting.Indented);
  3997. Assert.AreEqual(@"{
  3998. ""Name"": null
  3999. }", json);
  4000. }
  4001. public class DeserializeStringConvert
  4002. {
  4003. public string Name { get; set; }
  4004. public int Age { get; set; }
  4005. public double Height { get; set; }
  4006. public decimal Price { get; set; }
  4007. }
  4008. [Test]
  4009. public void DeserializeStringEnglish()
  4010. {
  4011. string json = @"{
  4012. 'Name': 'James Hughes',
  4013. 'Age': '40',
  4014. 'Height': '44.4',
  4015. 'Price': '4'
  4016. }";
  4017. DeserializeStringConvert p = JsonConvert.DeserializeObject<DeserializeStringConvert>(json);
  4018. Assert.AreEqual(40, p.Age);
  4019. Assert.AreEqual(44.4, p.Height);
  4020. Assert.AreEqual(4m, p.Price);
  4021. }
  4022. [Test]
  4023. public void DeserializeNullDateTimeValueTest()
  4024. {
  4025. ExceptionAssert.Throws<JsonSerializationException>(
  4026. "Error converting value {null} to type 'System.DateTime'. Path '', line 1, position 4.",
  4027. () =>
  4028. {
  4029. JsonConvert.DeserializeObject("null", typeof(DateTime));
  4030. });
  4031. }
  4032. [Test]
  4033. public void DeserializeNullNullableDateTimeValueTest()
  4034. {
  4035. object dateTime = JsonConvert.DeserializeObject("null", typeof(DateTime?));
  4036. Assert.IsNull(dateTime);
  4037. }
  4038. [Test]
  4039. public void MultiIndexSuperTest()
  4040. {
  4041. MultiIndexSuper e = new MultiIndexSuper();
  4042. string json = JsonConvert.SerializeObject(e, Formatting.Indented);
  4043. Assert.AreEqual(@"{}", json);
  4044. }
  4045. public class MultiIndexSuper : MultiIndexBase
  4046. {
  4047. }
  4048. public abstract class MultiIndexBase
  4049. {
  4050. protected internal object this[string propertyName]
  4051. {
  4052. get { return null; }
  4053. set { }
  4054. }
  4055. protected internal object this[object property]
  4056. {
  4057. get { return null; }
  4058. set { }
  4059. }
  4060. }
  4061. public class CommentTestClass
  4062. {
  4063. public bool Indexed { get; set; }
  4064. public int StartYear { get; set; }
  4065. public IList<decimal> Values { get; set; }
  4066. }
  4067. [Test]
  4068. public void CommentTestClassTest()
  4069. {
  4070. string json = @"{""indexed"":true, ""startYear"":1939, ""values"":
  4071. [ 3000, /* 1940-1949 */
  4072. 3000, 3600, 3600, 3600, 3600, 4200, 4200, 4200, 4200, 4800, /* 1950-1959 */
  4073. 4800, 4800, 4800, 4800, 4800, 4800, 6600, 6600, 7800, 7800, /* 1960-1969 */
  4074. 7800, 7800, 9000, 10800, 13200, 14100, 15300, 16500, 17700, 22900, /* 1970-1979 */
  4075. 25900, 29700, 32400, 35700, 37800, 39600, 42000, 43800, 45000, 48000, /* 1980-1989 */
  4076. 51300, 53400, 55500, 57600, 60600, 61200, 62700, 65400, 68400, 72600, /* 1990-1999 */
  4077. 76200, 80400, 84900, 87000, 87900, 90000, 94200, 97500, 102000, 106800, /* 2000-2009 */
  4078. 106800, 106800] /* 2010-2011 */
  4079. }";
  4080. CommentTestClass commentTestClass = JsonConvert.DeserializeObject<CommentTestClass>(json);
  4081. Assert.AreEqual(true, commentTestClass.Indexed);
  4082. Assert.AreEqual(1939, commentTestClass.StartYear);
  4083. Assert.AreEqual(63, commentTestClass.Values.Count);
  4084. }
  4085. private class DTOWithParameterisedConstructor
  4086. {
  4087. public DTOWithParameterisedConstructor(string A)
  4088. {
  4089. this.A = A;
  4090. B = 2;
  4091. }
  4092. public string A { get; set; }
  4093. public int? B { get; set; }
  4094. }
  4095. private class DTOWithoutParameterisedConstructor
  4096. {
  4097. public DTOWithoutParameterisedConstructor()
  4098. {
  4099. B = 2;
  4100. }
  4101. public string A { get; set; }
  4102. public int? B { get; set; }
  4103. }
  4104. [Test]
  4105. public void PopulationBehaviourForOmittedPropertiesIsTheSameForParameterisedConstructorAsForDefaultConstructor()
  4106. {
  4107. string json = @"{A:""Test""}";
  4108. var withoutParameterisedConstructor = JsonConvert.DeserializeObject<DTOWithoutParameterisedConstructor>(json);
  4109. var withParameterisedConstructor = JsonConvert.DeserializeObject<DTOWithParameterisedConstructor>(json);
  4110. Assert.AreEqual(withoutParameterisedConstructor.B, withParameterisedConstructor.B);
  4111. }
  4112. public class EnumerableArrayPropertyClass
  4113. {
  4114. public IEnumerable<int> Numbers
  4115. {
  4116. get
  4117. {
  4118. return new[] { 1, 2, 3 }; //fails
  4119. //return new List<int>(new[] { 1, 2, 3 }); //works
  4120. }
  4121. }
  4122. }
  4123. [Test]
  4124. public void SkipPopulatingArrayPropertyClass()
  4125. {
  4126. string json = JsonConvert.SerializeObject(new EnumerableArrayPropertyClass());
  4127. JsonConvert.DeserializeObject<EnumerableArrayPropertyClass>(json);
  4128. }
  4129. #if !NET20
  4130. [DataContract]
  4131. public class BaseDataContract
  4132. {
  4133. [DataMember(Name = "virtualMember")]
  4134. public virtual string VirtualMember { get; set; }
  4135. [DataMember(Name = "nonVirtualMember")]
  4136. public string NonVirtualMember { get; set; }
  4137. }
  4138. public class ChildDataContract : BaseDataContract
  4139. {
  4140. public override string VirtualMember { get; set; }
  4141. public string NewMember { get; set; }
  4142. }
  4143. [Test]
  4144. public void ChildDataContractTest()
  4145. {
  4146. ChildDataContract cc = new ChildDataContract
  4147. {
  4148. VirtualMember = "VirtualMember!",
  4149. NonVirtualMember = "NonVirtualMember!"
  4150. };
  4151. string result = JsonConvert.SerializeObject(cc);
  4152. Assert.AreEqual(@"{""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  4153. }
  4154. #endif
  4155. [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
  4156. public class BaseObject
  4157. {
  4158. [JsonProperty(PropertyName = "virtualMember")]
  4159. public virtual string VirtualMember { get; set; }
  4160. [JsonProperty(PropertyName = "nonVirtualMember")]
  4161. public string NonVirtualMember { get; set; }
  4162. }
  4163. public class ChildObject : BaseObject
  4164. {
  4165. public override string VirtualMember { get; set; }
  4166. public string NewMember { get; set; }
  4167. }
  4168. public class ChildWithDifferentOverrideObject : BaseObject
  4169. {
  4170. [JsonProperty(PropertyName = "differentVirtualMember")]
  4171. public override string VirtualMember { get; set; }
  4172. }
  4173. [Test]
  4174. public void ChildObjectTest()
  4175. {
  4176. ChildObject cc = new ChildObject
  4177. {
  4178. VirtualMember = "VirtualMember!",
  4179. NonVirtualMember = "NonVirtualMember!"
  4180. };
  4181. string result = JsonConvert.SerializeObject(cc);
  4182. Assert.AreEqual(@"{""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  4183. }
  4184. [Test]
  4185. public void ChildWithDifferentOverrideObjectTest()
  4186. {
  4187. ChildWithDifferentOverrideObject cc = new ChildWithDifferentOverrideObject
  4188. {
  4189. VirtualMember = "VirtualMember!",
  4190. NonVirtualMember = "NonVirtualMember!"
  4191. };
  4192. string result = JsonConvert.SerializeObject(cc);
  4193. Assert.AreEqual(@"{""differentVirtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  4194. }
  4195. [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
  4196. public interface IInterfaceObject
  4197. {
  4198. [JsonProperty(PropertyName = "virtualMember")]
  4199. [JsonConverter(typeof(IsoDateTimeConverter))]
  4200. DateTime InterfaceMember { get; set; }
  4201. }
  4202. public class ImplementInterfaceObject : IInterfaceObject
  4203. {
  4204. public DateTime InterfaceMember { get; set; }
  4205. public string NewMember { get; set; }
  4206. [JsonProperty(PropertyName = "newMemberWithProperty")]
  4207. public string NewMemberWithProperty { get; set; }
  4208. }
  4209. [Test]
  4210. public void ImplementInterfaceObjectTest()
  4211. {
  4212. ImplementInterfaceObject cc = new ImplementInterfaceObject
  4213. {
  4214. InterfaceMember = new DateTime(2010, 12, 31, 0, 0, 0, DateTimeKind.Utc),
  4215. NewMember = "NewMember!"
  4216. };
  4217. string result = JsonConvert.SerializeObject(cc, Formatting.Indented);
  4218. Assert.AreEqual(@"{
  4219. ""virtualMember"": ""2010-12-31T00:00:00Z"",
  4220. ""newMemberWithProperty"": null
  4221. }", result);
  4222. }
  4223. public class NonDefaultConstructorWithReadOnlyCollectionProperty
  4224. {
  4225. public string Title { get; set; }
  4226. public IList<string> Categories { get; private set; }
  4227. public NonDefaultConstructorWithReadOnlyCollectionProperty(string title)
  4228. {
  4229. Title = title;
  4230. Categories = new List<string>();
  4231. }
  4232. }
  4233. [Test]
  4234. public void NonDefaultConstructorWithReadOnlyCollectionPropertyTest()
  4235. {
  4236. NonDefaultConstructorWithReadOnlyCollectionProperty c1 = new NonDefaultConstructorWithReadOnlyCollectionProperty("blah");
  4237. c1.Categories.Add("one");
  4238. c1.Categories.Add("two");
  4239. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4240. Assert.AreEqual(@"{
  4241. ""Title"": ""blah"",
  4242. ""Categories"": [
  4243. ""one"",
  4244. ""two""
  4245. ]
  4246. }", json);
  4247. NonDefaultConstructorWithReadOnlyCollectionProperty c2 = JsonConvert.DeserializeObject<NonDefaultConstructorWithReadOnlyCollectionProperty>(json);
  4248. Assert.AreEqual(c1.Title, c2.Title);
  4249. Assert.AreEqual(c1.Categories.Count, c2.Categories.Count);
  4250. Assert.AreEqual("one", c2.Categories[0]);
  4251. Assert.AreEqual("two", c2.Categories[1]);
  4252. }
  4253. public class NonDefaultConstructorWithReadOnlyDictionaryProperty
  4254. {
  4255. public string Title { get; set; }
  4256. public IDictionary<string, int> Categories { get; private set; }
  4257. public NonDefaultConstructorWithReadOnlyDictionaryProperty(string title)
  4258. {
  4259. Title = title;
  4260. Categories = new Dictionary<string, int>();
  4261. }
  4262. }
  4263. [Test]
  4264. public void NonDefaultConstructorWithReadOnlyDictionaryPropertyTest()
  4265. {
  4266. NonDefaultConstructorWithReadOnlyDictionaryProperty c1 = new NonDefaultConstructorWithReadOnlyDictionaryProperty("blah");
  4267. c1.Categories.Add("one", 1);
  4268. c1.Categories.Add("two", 2);
  4269. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4270. Assert.AreEqual(@"{
  4271. ""Title"": ""blah"",
  4272. ""Categories"": {
  4273. ""one"": 1,
  4274. ""two"": 2
  4275. }
  4276. }", json);
  4277. NonDefaultConstructorWithReadOnlyDictionaryProperty c2 = JsonConvert.DeserializeObject<NonDefaultConstructorWithReadOnlyDictionaryProperty>(json);
  4278. Assert.AreEqual(c1.Title, c2.Title);
  4279. Assert.AreEqual(c1.Categories.Count, c2.Categories.Count);
  4280. Assert.AreEqual(1, c2.Categories["one"]);
  4281. Assert.AreEqual(2, c2.Categories["two"]);
  4282. }
  4283. [JsonObject(MemberSerialization.OptIn)]
  4284. public class ClassAttributeBase
  4285. {
  4286. [JsonProperty]
  4287. public string BaseClassValue { get; set; }
  4288. }
  4289. public class ClassAttributeDerived : ClassAttributeBase
  4290. {
  4291. [JsonProperty]
  4292. public string DerivedClassValue { get; set; }
  4293. public string NonSerialized { get; set; }
  4294. }
  4295. public class CollectionClassAttributeDerived : ClassAttributeBase, ICollection<object>
  4296. {
  4297. [JsonProperty]
  4298. public string CollectionDerivedClassValue { get; set; }
  4299. public void Add(object item)
  4300. {
  4301. throw new NotImplementedException();
  4302. }
  4303. public void Clear()
  4304. {
  4305. throw new NotImplementedException();
  4306. }
  4307. public bool Contains(object item)
  4308. {
  4309. throw new NotImplementedException();
  4310. }
  4311. public void CopyTo(object[] array, int arrayIndex)
  4312. {
  4313. throw new NotImplementedException();
  4314. }
  4315. public int Count
  4316. {
  4317. get { throw new NotImplementedException(); }
  4318. }
  4319. public bool IsReadOnly
  4320. {
  4321. get { throw new NotImplementedException(); }
  4322. }
  4323. public bool Remove(object item)
  4324. {
  4325. throw new NotImplementedException();
  4326. }
  4327. public IEnumerator<object> GetEnumerator()
  4328. {
  4329. throw new NotImplementedException();
  4330. }
  4331. IEnumerator IEnumerable.GetEnumerator()
  4332. {
  4333. throw new NotImplementedException();
  4334. }
  4335. }
  4336. [Test]
  4337. public void ClassAttributesInheritance()
  4338. {
  4339. string json = JsonConvert.SerializeObject(new ClassAttributeDerived
  4340. {
  4341. BaseClassValue = "BaseClassValue!",
  4342. DerivedClassValue = "DerivedClassValue!",
  4343. NonSerialized = "NonSerialized!"
  4344. }, Formatting.Indented);
  4345. Assert.AreEqual(@"{
  4346. ""DerivedClassValue"": ""DerivedClassValue!"",
  4347. ""BaseClassValue"": ""BaseClassValue!""
  4348. }", json);
  4349. json = JsonConvert.SerializeObject(new CollectionClassAttributeDerived
  4350. {
  4351. BaseClassValue = "BaseClassValue!",
  4352. CollectionDerivedClassValue = "CollectionDerivedClassValue!"
  4353. }, Formatting.Indented);
  4354. Assert.AreEqual(@"{
  4355. ""CollectionDerivedClassValue"": ""CollectionDerivedClassValue!"",
  4356. ""BaseClassValue"": ""BaseClassValue!""
  4357. }", json);
  4358. }
  4359. public class PrivateMembersClassWithAttributes
  4360. {
  4361. public PrivateMembersClassWithAttributes(string privateString, string internalString, string readonlyString)
  4362. {
  4363. _privateString = privateString;
  4364. _readonlyString = readonlyString;
  4365. _internalString = internalString;
  4366. }
  4367. public PrivateMembersClassWithAttributes()
  4368. {
  4369. _readonlyString = "default!";
  4370. }
  4371. [JsonProperty]
  4372. private string _privateString;
  4373. [JsonProperty]
  4374. private readonly string _readonlyString;
  4375. [JsonProperty]
  4376. internal string _internalString;
  4377. public string UseValue()
  4378. {
  4379. return _readonlyString;
  4380. }
  4381. }
  4382. [Test]
  4383. public void PrivateMembersClassWithAttributesTest()
  4384. {
  4385. PrivateMembersClassWithAttributes c1 = new PrivateMembersClassWithAttributes("privateString!", "internalString!", "readonlyString!");
  4386. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4387. Assert.AreEqual(@"{
  4388. ""_privateString"": ""privateString!"",
  4389. ""_readonlyString"": ""readonlyString!"",
  4390. ""_internalString"": ""internalString!""
  4391. }", json);
  4392. PrivateMembersClassWithAttributes c2 = JsonConvert.DeserializeObject<PrivateMembersClassWithAttributes>(json);
  4393. Assert.AreEqual("readonlyString!", c2.UseValue());
  4394. }
  4395. public partial class BusRun
  4396. {
  4397. public IEnumerable<Nullable<DateTime>> Departures { get; set; }
  4398. public Boolean WheelchairAccessible { get; set; }
  4399. }
  4400. [Test]
  4401. public void DeserializeGenericEnumerableProperty()
  4402. {
  4403. BusRun r = JsonConvert.DeserializeObject<BusRun>("{\"Departures\":[\"\\/Date(1309874148734-0400)\\/\",\"\\/Date(1309874148739-0400)\\/\",null],\"WheelchairAccessible\":true}");
  4404. Assert.AreEqual(3, r.Departures.Count());
  4405. Assert.IsNotNull(r.Departures.ElementAt(0));
  4406. Assert.IsNotNull(r.Departures.ElementAt(1));
  4407. Assert.IsNull(r.Departures.ElementAt(2));
  4408. }
  4409. #if !(NET20)
  4410. [DataContract]
  4411. public class BaseType
  4412. {
  4413. [DataMember]
  4414. public string zebra;
  4415. }
  4416. [DataContract]
  4417. public class DerivedType : BaseType
  4418. {
  4419. [DataMember(Order = 0)]
  4420. public string bird;
  4421. [DataMember(Order = 1)]
  4422. public string parrot;
  4423. [DataMember]
  4424. public string dog;
  4425. [DataMember(Order = 3)]
  4426. public string antelope;
  4427. [DataMember]
  4428. public string cat;
  4429. [JsonProperty(Order = 1)]
  4430. public string albatross;
  4431. [JsonProperty(Order = -2)]
  4432. public string dinosaur;
  4433. }
  4434. [Test]
  4435. public void JsonPropertyDataMemberOrder()
  4436. {
  4437. DerivedType d = new DerivedType();
  4438. string json = JsonConvert.SerializeObject(d, Formatting.Indented);
  4439. Assert.AreEqual(@"{
  4440. ""dinosaur"": null,
  4441. ""dog"": null,
  4442. ""cat"": null,
  4443. ""zebra"": null,
  4444. ""bird"": null,
  4445. ""parrot"": null,
  4446. ""albatross"": null,
  4447. ""antelope"": null
  4448. }", json);
  4449. }
  4450. #endif
  4451. public class ClassWithException
  4452. {
  4453. public IList<Exception> Exceptions { get; set; }
  4454. public ClassWithException()
  4455. {
  4456. Exceptions = new List<Exception>();
  4457. }
  4458. }
  4459. #if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE)
  4460. [Test]
  4461. public void SerializeException1()
  4462. {
  4463. ClassWithException classWithException = new ClassWithException();
  4464. try
  4465. {
  4466. throw new Exception("Test Exception");
  4467. }
  4468. catch (Exception ex)
  4469. {
  4470. classWithException.Exceptions.Add(ex);
  4471. }
  4472. string sex = JsonConvert.SerializeObject(classWithException);
  4473. ClassWithException dex = JsonConvert.DeserializeObject<ClassWithException>(sex);
  4474. Assert.AreEqual(dex.Exceptions[0].ToString(), dex.Exceptions[0].ToString());
  4475. sex = JsonConvert.SerializeObject(classWithException, Formatting.Indented);
  4476. dex = JsonConvert.DeserializeObject<ClassWithException>(sex); // this fails!
  4477. Assert.AreEqual(dex.Exceptions[0].ToString(), dex.Exceptions[0].ToString());
  4478. }
  4479. #endif
  4480. public void DeserializeIDictionary()
  4481. {
  4482. IDictionary dictionary = JsonConvert.DeserializeObject<IDictionary>("{'name':'value!'}");
  4483. Assert.AreEqual(1, dictionary.Count);
  4484. Assert.AreEqual("value!", dictionary["name"]);
  4485. }
  4486. public void DeserializeIList()
  4487. {
  4488. IList list = JsonConvert.DeserializeObject<IList>("['1', 'two', 'III']");
  4489. Assert.AreEqual(3, list.Count);
  4490. }
  4491. public void UriGuidTimeSpanTestClassEmptyTest()
  4492. {
  4493. UriGuidTimeSpanTestClass c1 = new UriGuidTimeSpanTestClass();
  4494. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4495. Assert.AreEqual(@"{
  4496. ""Guid"": ""00000000-0000-0000-0000-000000000000"",
  4497. ""NullableGuid"": null,
  4498. ""TimeSpan"": ""00:00:00"",
  4499. ""NullableTimeSpan"": null,
  4500. ""Uri"": null
  4501. }", json);
  4502. UriGuidTimeSpanTestClass c2 = JsonConvert.DeserializeObject<UriGuidTimeSpanTestClass>(json);
  4503. Assert.AreEqual(c1.Guid, c2.Guid);
  4504. Assert.AreEqual(c1.NullableGuid, c2.NullableGuid);
  4505. Assert.AreEqual(c1.TimeSpan, c2.TimeSpan);
  4506. Assert.AreEqual(c1.NullableTimeSpan, c2.NullableTimeSpan);
  4507. Assert.AreEqual(c1.Uri, c2.Uri);
  4508. }
  4509. public void UriGuidTimeSpanTestClassValuesTest()
  4510. {
  4511. UriGuidTimeSpanTestClass c1 = new UriGuidTimeSpanTestClass
  4512. {
  4513. Guid = new Guid("1924129C-F7E0-40F3-9607-9939C531395A"),
  4514. NullableGuid = new Guid("9E9F3ADF-E017-4F72-91E0-617EBE85967D"),
  4515. TimeSpan = TimeSpan.FromDays(1),
  4516. NullableTimeSpan = TimeSpan.FromHours(1),
  4517. Uri = new Uri("http://testuri.com")
  4518. };
  4519. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  4520. Assert.AreEqual(@"{
  4521. ""Guid"": ""1924129c-f7e0-40f3-9607-9939c531395a"",
  4522. ""NullableGuid"": ""9e9f3adf-e017-4f72-91e0-617ebe85967d"",
  4523. ""TimeSpan"": ""1.00:00:00"",
  4524. ""NullableTimeSpan"": ""01:00:00"",
  4525. ""Uri"": ""http://testuri.com/""
  4526. }", json);
  4527. UriGuidTimeSpanTestClass c2 = JsonConvert.DeserializeObject<UriGuidTimeSpanTestClass>(json);
  4528. Assert.AreEqual(c1.Guid, c2.Guid);
  4529. Assert.AreEqual(c1.NullableGuid, c2.NullableGuid);
  4530. Assert.AreEqual(c1.TimeSpan, c2.TimeSpan);
  4531. Assert.AreEqual(c1.NullableTimeSpan, c2.NullableTimeSpan);
  4532. Assert.AreEqual(c1.Uri, c2.Uri);
  4533. }
  4534. [Test]
  4535. public void NullableValueGenericDictionary()
  4536. {
  4537. IDictionary<string, int?> v1 = new Dictionary<string, int?>
  4538. {
  4539. {"First", 1},
  4540. {"Second", null},
  4541. {"Third", 3}
  4542. };
  4543. string json = JsonConvert.SerializeObject(v1, Formatting.Indented);
  4544. Assert.AreEqual(@"{
  4545. ""First"": 1,
  4546. ""Second"": null,
  4547. ""Third"": 3
  4548. }", json);
  4549. IDictionary<string, int?> v2 = JsonConvert.DeserializeObject<IDictionary<string, int?>>(json);
  4550. Assert.AreEqual(3, v2.Count);
  4551. Assert.AreEqual(1, v2["First"]);
  4552. Assert.AreEqual(null, v2["Second"]);
  4553. Assert.AreEqual(3, v2["Third"]);
  4554. }
  4555. [Test]
  4556. public void UsingJsonTextWriter()
  4557. {
  4558. // The property of the object has to be a number for the cast exception to occure
  4559. object o = new { p = 1 };
  4560. var json = JObject.FromObject(o);
  4561. using (var sw = new StringWriter())
  4562. using (var jw = new JsonTextWriter(sw))
  4563. {
  4564. jw.WriteToken(json.CreateReader());
  4565. jw.Flush();
  4566. string result = sw.ToString();
  4567. Assert.AreEqual(@"{""p"":1}", result);
  4568. }
  4569. }
  4570. #if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE)
  4571. [Test]
  4572. public void DeserializeConcurrentDictionary()
  4573. {
  4574. IDictionary<string, Component> components = new Dictionary<string, Component>
  4575. {
  4576. {"Key!", new Component()}
  4577. };
  4578. GameObject go = new GameObject
  4579. {
  4580. Components = new ConcurrentDictionary<string, Component>(components),
  4581. Id = "Id!",
  4582. Name = "Name!"
  4583. };
  4584. string originalJson = JsonConvert.SerializeObject(go, Formatting.Indented);
  4585. Assert.AreEqual(@"{
  4586. ""Components"": {
  4587. ""Key!"": {}
  4588. },
  4589. ""Id"": ""Id!"",
  4590. ""Name"": ""Name!""
  4591. }", originalJson);
  4592. GameObject newObject = JsonConvert.DeserializeObject<GameObject>(originalJson);
  4593. Assert.AreEqual(1, newObject.Components.Count);
  4594. Assert.AreEqual("Id!", newObject.Id);
  4595. Assert.AreEqual("Name!", newObject.Name);
  4596. }
  4597. #endif
  4598. [Test]
  4599. public void DeserializeKeyValuePairArray()
  4600. {
  4601. string json = @"[ { ""Value"": [ ""1"", ""2"" ], ""Key"": ""aaa"", ""BadContent"": [ 0 ] }, { ""Value"": [ ""3"", ""4"" ], ""Key"": ""bbb"" } ]";
  4602. IList<KeyValuePair<string, IList<string>>> values = JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json);
  4603. Assert.AreEqual(2, values.Count);
  4604. Assert.AreEqual("aaa", values[0].Key);
  4605. Assert.AreEqual(2, values[0].Value.Count);
  4606. Assert.AreEqual("1", values[0].Value[0]);
  4607. Assert.AreEqual("2", values[0].Value[1]);
  4608. Assert.AreEqual("bbb", values[1].Key);
  4609. Assert.AreEqual(2, values[1].Value.Count);
  4610. Assert.AreEqual("3", values[1].Value[0]);
  4611. Assert.AreEqual("4", values[1].Value[1]);
  4612. }
  4613. [Test]
  4614. public void DeserializeNullableKeyValuePairArray()
  4615. {
  4616. string json = @"[ { ""Value"": [ ""1"", ""2"" ], ""Key"": ""aaa"", ""BadContent"": [ 0 ] }, null, { ""Value"": [ ""3"", ""4"" ], ""Key"": ""bbb"" } ]";
  4617. IList<KeyValuePair<string, IList<string>>?> values = JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>?>>(json);
  4618. Assert.AreEqual(3, values.Count);
  4619. Assert.AreEqual("aaa", values[0].Value.Key);
  4620. Assert.AreEqual(2, values[0].Value.Value.Count);
  4621. Assert.AreEqual("1", values[0].Value.Value[0]);
  4622. Assert.AreEqual("2", values[0].Value.Value[1]);
  4623. Assert.AreEqual(null, values[1]);
  4624. Assert.AreEqual("bbb", values[2].Value.Key);
  4625. Assert.AreEqual(2, values[2].Value.Value.Count);
  4626. Assert.AreEqual("3", values[2].Value.Value[0]);
  4627. Assert.AreEqual("4", values[2].Value.Value[1]);
  4628. }
  4629. [Test]
  4630. public void DeserializeNullToNonNullableKeyValuePairArray()
  4631. {
  4632. string json = @"[ null ]";
  4633. ExceptionAssert.Throws<JsonSerializationException>(
  4634. "Cannot convert null value to KeyValuePair. Path '[0]', line 1, position 6.",
  4635. () =>
  4636. {
  4637. JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json);
  4638. });
  4639. }
  4640. [Test]
  4641. public void SerializeUriWithQuotes()
  4642. {
  4643. string input = "http://test.com/%22foo+bar%22";
  4644. Uri uri = new Uri(input);
  4645. string json = JsonConvert.SerializeObject(uri);
  4646. Uri output = JsonConvert.DeserializeObject<Uri>(json);
  4647. Assert.AreEqual(uri, output);
  4648. }
  4649. [Test]
  4650. public void SerializeUriWithSlashes()
  4651. {
  4652. string input = @"http://tes/?a=b\\c&d=e\";
  4653. Uri uri = new Uri(input);
  4654. string json = JsonConvert.SerializeObject(uri);
  4655. Uri output = JsonConvert.DeserializeObject<Uri>(json);
  4656. Assert.AreEqual(uri, output);
  4657. }
  4658. [Test]
  4659. public void DeserializeByteArrayWithTypeNameHandling()
  4660. {
  4661. TestObject test = new TestObject("Test", new byte[] { 72, 63, 62, 71, 92, 55 });
  4662. JsonSerializer serializer = new JsonSerializer();
  4663. serializer.TypeNameHandling = TypeNameHandling.All;
  4664. byte[] objectBytes;
  4665. using (MemoryStream bsonStream = new MemoryStream())
  4666. using (JsonWriter bsonWriter = new JsonTextWriter(new StreamWriter(bsonStream)))
  4667. {
  4668. serializer.Serialize(bsonWriter, test);
  4669. bsonWriter.Flush();
  4670. objectBytes = bsonStream.ToArray();
  4671. }
  4672. using (MemoryStream bsonStream = new MemoryStream(objectBytes))
  4673. using (JsonReader bsonReader = new JsonTextReader(new StreamReader(bsonStream)))
  4674. {
  4675. // Get exception here
  4676. TestObject newObject = (TestObject)serializer.Deserialize(bsonReader);
  4677. Assert.AreEqual("Test", newObject.Name);
  4678. CollectionAssert.AreEquivalent(new byte[] { 72, 63, 62, 71, 92, 55 }, newObject.Data);
  4679. }
  4680. }
  4681. #if !(SILVERLIGHT || WINDOWS_PHONE || NET20 || NETFX_CORE)
  4682. [Test]
  4683. public void DeserializeDecimalsWithCulture()
  4684. {
  4685. CultureInfo initialCulture = Thread.CurrentThread.CurrentCulture;
  4686. try
  4687. {
  4688. CultureInfo testCulture = CultureInfo.CreateSpecificCulture("nb-NO");
  4689. Thread.CurrentThread.CurrentCulture = testCulture;
  4690. Thread.CurrentThread.CurrentUICulture = testCulture;
  4691. string json = @"{ 'Quantity': '1.5', 'OptionalQuantity': '2.2' }";
  4692. DecimalTestClass c = JsonConvert.DeserializeObject<DecimalTestClass>(json);
  4693. Assert.AreEqual(1.5m, c.Quantity);
  4694. Assert.AreEqual(2.2d, c.OptionalQuantity);
  4695. }
  4696. finally
  4697. {
  4698. Thread.CurrentThread.CurrentCulture = initialCulture;
  4699. Thread.CurrentThread.CurrentUICulture = initialCulture;
  4700. }
  4701. }
  4702. #endif
  4703. [Test]
  4704. public void ReadForTypeHackFixDecimal()
  4705. {
  4706. IList<decimal> d1 = new List<decimal> { 1.1m };
  4707. string json = JsonConvert.SerializeObject(d1);
  4708. IList<decimal> d2 = JsonConvert.DeserializeObject<IList<decimal>>(json);
  4709. Assert.AreEqual(d1.Count, d2.Count);
  4710. Assert.AreEqual(d1[0], d2[0]);
  4711. }
  4712. [Test]
  4713. public void ReadForTypeHackFixDateTimeOffset()
  4714. {
  4715. IList<DateTimeOffset?> d1 = new List<DateTimeOffset?> { null };
  4716. string json = JsonConvert.SerializeObject(d1);
  4717. IList<DateTimeOffset?> d2 = JsonConvert.DeserializeObject<IList<DateTimeOffset?>>(json);
  4718. Assert.AreEqual(d1.Count, d2.Count);
  4719. Assert.AreEqual(d1[0], d2[0]);
  4720. }
  4721. [Test]
  4722. public void ReadForTypeHackFixByteArray()
  4723. {
  4724. IList<byte[]> d1 = new List<byte[]> { null };
  4725. string json = JsonConvert.SerializeObject(d1);
  4726. IList<byte[]> d2 = JsonConvert.DeserializeObject<IList<byte[]>>(json);
  4727. Assert.AreEqual(d1.Count, d2.Count);
  4728. Assert.AreEqual(d1[0], d2[0]);
  4729. }
  4730. [Test]
  4731. public void SerializeInheritanceHierarchyWithDuplicateProperty()
  4732. {
  4733. Bb b = new Bb();
  4734. b.no = true;
  4735. Aa a = b;
  4736. a.no = int.MaxValue;
  4737. string json = JsonConvert.SerializeObject(b);
  4738. Assert.AreEqual(@"{""no"":true}", json);
  4739. Bb b2 = JsonConvert.DeserializeObject<Bb>(json);
  4740. Assert.AreEqual(true, b2.no);
  4741. }
  4742. [Test]
  4743. public void DeserializeNullInt()
  4744. {
  4745. string json = @"[
  4746. 1,
  4747. 2,
  4748. 3,
  4749. null
  4750. ]";
  4751. ExceptionAssert.Throws<JsonSerializationException>(
  4752. "Error converting value {null} to type 'System.Int32'. Path '[3]', line 5, position 7.",
  4753. () =>
  4754. {
  4755. List<int> numbers = JsonConvert.DeserializeObject<List<int>>(json);
  4756. });
  4757. }
  4758. [Test]
  4759. public void SerializeNullableWidgetStruct()
  4760. {
  4761. Widget widget = new Widget { Id = new WidgetId { Value = "id" } };
  4762. string json = JsonConvert.SerializeObject(widget);
  4763. Assert.AreEqual(@"{""Id"":{""Value"":""id""}}", json);
  4764. }
  4765. [Test]
  4766. public void DeserializeNullableWidgetStruct()
  4767. {
  4768. string json = @"{""Id"":{""Value"":""id""}}";
  4769. Widget w = JsonConvert.DeserializeObject<Widget>(json);
  4770. Assert.AreEqual(new WidgetId { Value = "id" }, w.Id);
  4771. Assert.AreEqual(new WidgetId { Value = "id" }, w.Id.Value);
  4772. Assert.AreEqual("id", w.Id.Value.Value);
  4773. }
  4774. [Test]
  4775. public void DeserializeBoolInt()
  4776. {
  4777. ExceptionAssert.Throws<JsonReaderException>(
  4778. "Error reading integer. Unexpected token: Boolean. Path 'PreProperty', line 2, position 22.",
  4779. () =>
  4780. {
  4781. string json = @"{
  4782. ""PreProperty"": true,
  4783. ""PostProperty"": ""-1""
  4784. }";
  4785. JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
  4786. });
  4787. }
  4788. [Test]
  4789. public void DeserializeUnexpectedEndInt()
  4790. {
  4791. ExceptionAssert.Throws<JsonSerializationException>(
  4792. "Unexpected end when setting PreProperty's value. Path 'PreProperty', line 2, position 18.",
  4793. () =>
  4794. {
  4795. string json = @"{
  4796. ""PreProperty"": ";
  4797. JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
  4798. });
  4799. }
  4800. [Test]
  4801. public void DeserializeNullableGuid()
  4802. {
  4803. string json = @"{""Id"":null}";
  4804. var c = JsonConvert.DeserializeObject<NullableGuid>(json);
  4805. Assert.AreEqual(null, c.Id);
  4806. json = @"{""Id"":""d8220a4b-75b1-4b7a-8112-b7bdae956a45""}";
  4807. c = JsonConvert.DeserializeObject<NullableGuid>(json);
  4808. Assert.AreEqual(new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"), c.Id);
  4809. }
  4810. [Test]
  4811. public void DeserializeGuid()
  4812. {
  4813. Item expected = new Item()
  4814. {
  4815. SourceTypeID = new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"),
  4816. BrokerID = new Guid("951663c4-924e-4c86-a57a-7ed737501dbd"),
  4817. Latitude = 33.657145,
  4818. Longitude = -117.766684,
  4819. TimeStamp = new DateTime(2000, 3, 1, 23, 59, 59, DateTimeKind.Utc),
  4820. Payload = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
  4821. };
  4822. string jsonString = JsonConvert.SerializeObject(expected, Formatting.Indented);
  4823. Assert.AreEqual(@"{
  4824. ""SourceTypeID"": ""d8220a4b-75b1-4b7a-8112-b7bdae956a45"",
  4825. ""BrokerID"": ""951663c4-924e-4c86-a57a-7ed737501dbd"",
  4826. ""Latitude"": 33.657145,
  4827. ""Longitude"": -117.766684,
  4828. ""TimeStamp"": ""2000-03-01T23:59:59Z"",
  4829. ""Payload"": {
  4830. ""$type"": ""System.Byte[], mscorlib"",
  4831. ""$value"": ""AAECAwQFBgcICQ==""
  4832. }
  4833. }", jsonString);
  4834. Item actual = JsonConvert.DeserializeObject<Item>(jsonString);
  4835. Assert.AreEqual(new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"), actual.SourceTypeID);
  4836. Assert.AreEqual(new Guid("951663c4-924e-4c86-a57a-7ed737501dbd"), actual.BrokerID);
  4837. byte[] bytes = (byte[])actual.Payload;
  4838. CollectionAssert.AreEquivalent((new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }).ToList(), bytes.ToList());
  4839. }
  4840. [Test]
  4841. public void DeserializeObjectDictionary()
  4842. {
  4843. var serializer = JsonSerializer.Create(new JsonSerializerSettings());
  4844. var dict = serializer.Deserialize<Dictionary<string, string>>(new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}")));
  4845. Assert.AreEqual("", dict["k1"]);
  4846. Assert.AreEqual("v2", dict["k2"]);
  4847. }
  4848. [Test]
  4849. public void DeserializeNullableEnum()
  4850. {
  4851. string json = JsonConvert.SerializeObject(new WithEnums
  4852. {
  4853. Id = 7,
  4854. NullableEnum = null
  4855. });
  4856. Assert.AreEqual(@"{""Id"":7,""NullableEnum"":null}", json);
  4857. WithEnums e = JsonConvert.DeserializeObject<WithEnums>(json);
  4858. Assert.AreEqual(null, e.NullableEnum);
  4859. json = JsonConvert.SerializeObject(new WithEnums
  4860. {
  4861. Id = 7,
  4862. NullableEnum = MyEnum.Value2
  4863. });
  4864. Assert.AreEqual(@"{""Id"":7,""NullableEnum"":1}", json);
  4865. e = JsonConvert.DeserializeObject<WithEnums>(json);
  4866. Assert.AreEqual(MyEnum.Value2, e.NullableEnum);
  4867. }
  4868. [Test]
  4869. public void NullableStructWithConverter()
  4870. {
  4871. string json = JsonConvert.SerializeObject(new Widget1 { Id = new WidgetId1 { Value = 1234 } });
  4872. Assert.AreEqual(@"{""Id"":""1234""}", json);
  4873. Widget1 w = JsonConvert.DeserializeObject<Widget1>(@"{""Id"":""1234""}");
  4874. Assert.AreEqual(new WidgetId1 { Value = 1234 }, w.Id);
  4875. }
  4876. [Test]
  4877. public void SerializeDictionaryStringStringAndStringObject()
  4878. {
  4879. var serializer = JsonSerializer.Create(new JsonSerializerSettings());
  4880. var dict = serializer.Deserialize<Dictionary<string, string>>(new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}")));
  4881. var reader = new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}"));
  4882. var dict2 = serializer.Deserialize<Dictionary<string, object>>(reader);
  4883. Assert.AreEqual(dict["k1"], dict2["k1"]);
  4884. }
  4885. [Test]
  4886. public void DeserializeEmptyStrings()
  4887. {
  4888. object v = JsonConvert.DeserializeObject<double?>("");
  4889. Assert.IsNull(v);
  4890. v = JsonConvert.DeserializeObject<char?>("");
  4891. Assert.IsNull(v);
  4892. v = JsonConvert.DeserializeObject<int?>("");
  4893. Assert.IsNull(v);
  4894. v = JsonConvert.DeserializeObject<decimal?>("");
  4895. Assert.IsNull(v);
  4896. v = JsonConvert.DeserializeObject<DateTime?>("");
  4897. Assert.IsNull(v);
  4898. v = JsonConvert.DeserializeObject<DateTimeOffset?>("");
  4899. Assert.IsNull(v);
  4900. v = JsonConvert.DeserializeObject<byte[]>("");
  4901. Assert.IsNull(v);
  4902. }
  4903. public class Sdfsdf
  4904. {
  4905. public double Id { get; set; }
  4906. }
  4907. [Test]
  4908. public void DeserializeDoubleFromEmptyString()
  4909. {
  4910. ExceptionAssert.Throws<JsonSerializationException>(
  4911. "No JSON content found and type 'System.Double' is not nullable. Path '', line 0, position 0.",
  4912. () =>
  4913. {
  4914. JsonConvert.DeserializeObject<double>("");
  4915. });
  4916. }
  4917. [Test]
  4918. public void DeserializeEnumFromEmptyString()
  4919. {
  4920. ExceptionAssert.Throws<JsonSerializationException>(
  4921. "No JSON content found and type 'System.StringComparison' is not nullable. Path '', line 0, position 0.",
  4922. () =>
  4923. {
  4924. JsonConvert.DeserializeObject<StringComparison>("");
  4925. });
  4926. }
  4927. [Test]
  4928. public void DeserializeInt32FromEmptyString()
  4929. {
  4930. ExceptionAssert.Throws<JsonSerializationException>(
  4931. "No JSON content found and type 'System.Int32' is not nullable. Path '', line 0, position 0.",
  4932. () =>
  4933. {
  4934. JsonConvert.DeserializeObject<int>("");
  4935. });
  4936. }
  4937. [Test]
  4938. public void DeserializeByteArrayFromEmptyString()
  4939. {
  4940. byte[] b = JsonConvert.DeserializeObject<byte[]>("");
  4941. Assert.IsNull(b);
  4942. }
  4943. [Test]
  4944. public void DeserializeDoubleFromNullString()
  4945. {
  4946. ExceptionAssert.Throws<ArgumentNullException>(
  4947. @"Value cannot be null.
  4948. Parameter name: value",
  4949. () =>
  4950. {
  4951. JsonConvert.DeserializeObject<double>(null);
  4952. });
  4953. }
  4954. [Test]
  4955. public void DeserializeFromNullString()
  4956. {
  4957. ExceptionAssert.Throws<ArgumentNullException>(
  4958. @"Value cannot be null.
  4959. Parameter name: value",
  4960. () =>
  4961. {
  4962. JsonConvert.DeserializeObject(null);
  4963. });
  4964. }
  4965. [Test]
  4966. public void DeserializeIsoDatesWithIsoConverter()
  4967. {
  4968. string jsonIsoText =
  4969. @"{""Value"":""2012-02-25T19:55:50.6095676+13:00""}";
  4970. DateTimeWrapper c = JsonConvert.DeserializeObject<DateTimeWrapper>(jsonIsoText, new IsoDateTimeConverter());
  4971. Assert.AreEqual(DateTimeKind.Local, c.Value.Kind);
  4972. }
  4973. #if !NET20
  4974. [Test]
  4975. public void DeserializeUTC()
  4976. {
  4977. DateTimeTestClass c =
  4978. JsonConvert.DeserializeObject<DateTimeTestClass>(
  4979. @"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12Z"",""PostField"":""Post""}",
  4980. new JsonSerializerSettings
  4981. {
  4982. DateTimeZoneHandling = DateTimeZoneHandling.Local
  4983. });
  4984. Assert.AreEqual(new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime(), c.DateTimeField);
  4985. Assert.AreEqual(new DateTimeOffset(2008, 12, 12, 12, 12, 12, 0, TimeSpan.Zero), c.DateTimeOffsetField);
  4986. Assert.AreEqual("Pre", c.PreField);
  4987. Assert.AreEqual("Post", c.PostField);
  4988. DateTimeTestClass c2 =
  4989. JsonConvert.DeserializeObject<DateTimeTestClass>(
  4990. @"{""PreField"":""Pre"",""DateTimeField"":""2008-01-01T01:01:01Z"",""DateTimeOffsetField"":""2008-01-01T01:01:01Z"",""PostField"":""Post""}",
  4991. new JsonSerializerSettings
  4992. {
  4993. DateTimeZoneHandling = DateTimeZoneHandling.Local
  4994. });
  4995. Assert.AreEqual(new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc).ToLocalTime(), c2.DateTimeField);
  4996. Assert.AreEqual(new DateTimeOffset(2008, 1, 1, 1, 1, 1, 0, TimeSpan.Zero), c2.DateTimeOffsetField);
  4997. Assert.AreEqual("Pre", c2.PreField);
  4998. Assert.AreEqual("Post", c2.PostField);
  4999. }
  5000. [Test]
  5001. public void NullableDeserializeUTC()
  5002. {
  5003. NullableDateTimeTestClass c =
  5004. JsonConvert.DeserializeObject<NullableDateTimeTestClass>(
  5005. @"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12Z"",""PostField"":""Post""}",
  5006. new JsonSerializerSettings
  5007. {
  5008. DateTimeZoneHandling = DateTimeZoneHandling.Local
  5009. });
  5010. Assert.AreEqual(new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime(), c.DateTimeField);
  5011. Assert.AreEqual(new DateTimeOffset(2008, 12, 12, 12, 12, 12, 0, TimeSpan.Zero), c.DateTimeOffsetField);
  5012. Assert.AreEqual("Pre", c.PreField);
  5013. Assert.AreEqual("Post", c.PostField);
  5014. NullableDateTimeTestClass c2 =
  5015. JsonConvert.DeserializeObject<NullableDateTimeTestClass>(
  5016. @"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}");
  5017. Assert.AreEqual(null, c2.DateTimeField);
  5018. Assert.AreEqual(null, c2.DateTimeOffsetField);
  5019. Assert.AreEqual("Pre", c2.PreField);
  5020. Assert.AreEqual("Post", c2.PostField);
  5021. }
  5022. [Test]
  5023. public void PrivateConstructor()
  5024. {
  5025. var person = PersonWithPrivateConstructor.CreatePerson();
  5026. person.Name = "John Doe";
  5027. person.Age = 25;
  5028. var serializedPerson = JsonConvert.SerializeObject(person);
  5029. var roundtrippedPerson = JsonConvert.DeserializeObject<PersonWithPrivateConstructor>(serializedPerson);
  5030. Assert.AreEqual(person.Name, roundtrippedPerson.Name);
  5031. }
  5032. #endif
  5033. #if !(SILVERLIGHT || NETFX_CORE)
  5034. [Test]
  5035. public void MetroBlogPost()
  5036. {
  5037. Product product = new Product();
  5038. product.Name = "Apple";
  5039. product.ExpiryDate = new DateTime(2012, 4, 1);
  5040. product.Price = 3.99M;
  5041. product.Sizes = new[] { "Small", "Medium", "Large" };
  5042. string json = JsonConvert.SerializeObject(product);
  5043. //{
  5044. // "Name": "Apple",
  5045. // "ExpiryDate": "2012-04-01T00:00:00",
  5046. // "Price": 3.99,
  5047. // "Sizes": [ "Small", "Medium", "Large" ]
  5048. //}
  5049. string metroJson = JsonConvert.SerializeObject(product, new JsonSerializerSettings
  5050. {
  5051. ContractResolver = new MetroPropertyNameResolver(),
  5052. Converters = { new MetroStringConverter() },
  5053. Formatting = Formatting.Indented
  5054. });
  5055. Assert.AreEqual(@"{
  5056. "":::NAME:::"": "":::APPLE:::"",
  5057. "":::EXPIRYDATE:::"": ""2012-04-01T00:00:00"",
  5058. "":::PRICE:::"": 3.99,
  5059. "":::SIZES:::"": [
  5060. "":::SMALL:::"",
  5061. "":::MEDIUM:::"",
  5062. "":::LARGE:::""
  5063. ]
  5064. }", metroJson);
  5065. //{
  5066. // ":::NAME:::": ":::APPLE:::",
  5067. // ":::EXPIRYDATE:::": "2012-04-01T00:00:00",
  5068. // ":::PRICE:::": 3.99,
  5069. // ":::SIZES:::": [ ":::SMALL:::", ":::MEDIUM:::", ":::LARGE:::" ]
  5070. //}
  5071. Color[] colors = new[] { Color.Blue, Color.Red, Color.Yellow, Color.Green, Color.Black, Color.Brown };
  5072. string json2 = JsonConvert.SerializeObject(colors, new JsonSerializerSettings
  5073. {
  5074. ContractResolver = new MetroPropertyNameResolver(),
  5075. Converters = { new MetroStringConverter(), new MetroColorConverter() },
  5076. Formatting = Formatting.Indented
  5077. });
  5078. Assert.AreEqual(@"[
  5079. "":::GRAY:::"",
  5080. "":::GRAY:::"",
  5081. "":::GRAY:::"",
  5082. "":::GRAY:::"",
  5083. "":::BLACK:::"",
  5084. "":::GRAY:::""
  5085. ]", json2);
  5086. }
  5087. public class MetroColorConverter : JsonConverter
  5088. {
  5089. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  5090. {
  5091. Color color = (Color)value;
  5092. Color fixedColor = (color == Color.White || color == Color.Black) ? color : Color.Gray;
  5093. writer.WriteValue(":::" + fixedColor.ToKnownColor().ToString().ToUpper() + ":::");
  5094. }
  5095. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  5096. {
  5097. return Enum.Parse(typeof(Color), reader.Value.ToString());
  5098. }
  5099. public override bool CanConvert(Type objectType)
  5100. {
  5101. return objectType == typeof(Color);
  5102. }
  5103. }
  5104. #endif
  5105. private class FooBar
  5106. {
  5107. public DateTimeOffset Foo { get; set; }
  5108. }
  5109. [Test]
  5110. public void TokenFromBson()
  5111. {
  5112. MemoryStream ms = new MemoryStream();
  5113. BsonWriter writer = new BsonWriter(ms);
  5114. writer.WriteStartArray();
  5115. writer.WriteValue("2000-01-02T03:04:05+06:00");
  5116. writer.WriteEndArray();
  5117. byte[] data = ms.ToArray();
  5118. BsonReader reader = new BsonReader(new MemoryStream(data))
  5119. {
  5120. ReadRootValueAsArray = true
  5121. };
  5122. JArray a = (JArray)JArray.ReadFrom(reader);
  5123. JValue v = (JValue)a[0];
  5124. Console.WriteLine(v.Value.GetType());
  5125. Console.WriteLine(a.ToString());
  5126. }
  5127. [Test]
  5128. public void ObjectRequiredDeserializeMissing()
  5129. {
  5130. string json = "{}";
  5131. IList<string> errors = new List<string>();
  5132. EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
  5133. {
  5134. errors.Add(e.ErrorContext.Error.Message);
  5135. e.ErrorContext.Handled = true;
  5136. };
  5137. var o = JsonConvert.DeserializeObject<RequiredObject>(json, new JsonSerializerSettings
  5138. {
  5139. Error = error
  5140. });
  5141. Assert.IsNotNull(o);
  5142. Assert.AreEqual(4, errors.Count);
  5143. Assert.AreEqual("Required property 'NonAttributeProperty' not found in JSON. Path '', line 1, position 2.", errors[0]);
  5144. Assert.AreEqual("Required property 'UnsetProperty' not found in JSON. Path '', line 1, position 2.", errors[1]);
  5145. Assert.AreEqual("Required property 'AllowNullProperty' not found in JSON. Path '', line 1, position 2.", errors[2]);
  5146. Assert.AreEqual("Required property 'AlwaysProperty' not found in JSON. Path '', line 1, position 2.", errors[3]);
  5147. }
  5148. [Test]
  5149. public void ObjectRequiredDeserializeNull()
  5150. {
  5151. string json = "{'NonAttributeProperty':null,'UnsetProperty':null,'AllowNullProperty':null,'AlwaysProperty':null}";
  5152. IList<string> errors = new List<string>();
  5153. EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
  5154. {
  5155. errors.Add(e.ErrorContext.Error.Message);
  5156. e.ErrorContext.Handled = true;
  5157. };
  5158. var o = JsonConvert.DeserializeObject<RequiredObject>(json, new JsonSerializerSettings
  5159. {
  5160. Error = error
  5161. });
  5162. Assert.IsNotNull(o);
  5163. Assert.AreEqual(3, errors.Count);
  5164. Assert.AreEqual("Required property 'NonAttributeProperty' expects a value but got null. Path '', line 1, position 97.", errors[0]);
  5165. Assert.AreEqual("Required property 'UnsetProperty' expects a value but got null. Path '', line 1, position 97.", errors[1]);
  5166. Assert.AreEqual("Required property 'AlwaysProperty' expects a value but got null. Path '', line 1, position 97.", errors[2]);
  5167. }
  5168. [Test]
  5169. public void ObjectRequiredSerialize()
  5170. {
  5171. IList<string> errors = new List<string>();
  5172. EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
  5173. {
  5174. errors.Add(e.ErrorContext.Error.Message);
  5175. e.ErrorContext.Handled = true;
  5176. };
  5177. string json = JsonConvert.SerializeObject(new RequiredObject(), new JsonSerializerSettings
  5178. {
  5179. Error = error,
  5180. Formatting = Formatting.Indented
  5181. });
  5182. Assert.AreEqual(@"{
  5183. ""DefaultProperty"": null,
  5184. ""AllowNullProperty"": null
  5185. }", json);
  5186. Assert.AreEqual(3, errors.Count);
  5187. Assert.AreEqual("Cannot write a null value for property 'NonAttributeProperty'. Property requires a value. Path ''.", errors[0]);
  5188. Assert.AreEqual("Cannot write a null value for property 'UnsetProperty'. Property requires a value. Path ''.", errors[1]);
  5189. Assert.AreEqual("Cannot write a null value for property 'AlwaysProperty'. Property requires a value. Path ''.", errors[2]);
  5190. }
  5191. [Test]
  5192. public void DeserializeCollectionItemConverter()
  5193. {
  5194. PropertyItemConverter c = new PropertyItemConverter
  5195. {
  5196. Data =
  5197. new[]{
  5198. "one",
  5199. "two",
  5200. "three"
  5201. }
  5202. };
  5203. var c2 = JsonConvert.DeserializeObject<PropertyItemConverter>("{'Data':['::ONE::','::TWO::']}");
  5204. Assert.IsNotNull(c2);
  5205. Assert.AreEqual(2, c2.Data.Count);
  5206. Assert.AreEqual("one", c2.Data[0]);
  5207. Assert.AreEqual("two", c2.Data[1]);
  5208. }
  5209. [Test]
  5210. public void SerializeCollectionItemConverter()
  5211. {
  5212. PropertyItemConverter c = new PropertyItemConverter
  5213. {
  5214. Data = new[]
  5215. {
  5216. "one",
  5217. "two",
  5218. "three"
  5219. }
  5220. };
  5221. string json = JsonConvert.SerializeObject(c);
  5222. Assert.AreEqual(@"{""Data"":["":::ONE:::"","":::TWO:::"","":::THREE:::""]}", json);
  5223. }
  5224. [Test]
  5225. public void DeserializeEmptyJsonString()
  5226. {
  5227. string s = (string) new JsonSerializer().Deserialize(new JsonTextReader(new StringReader("''")));
  5228. Assert.AreEqual("", s);
  5229. }
  5230. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  5231. [Test]
  5232. public void SerializeAndDeserializeWithAttributes()
  5233. {
  5234. var testObj = new PersonSerializable() { Name = "John Doe", Age = 28 };
  5235. var objDeserialized = this.SerializeAndDeserialize<PersonSerializable>(testObj);
  5236. Assert.AreEqual(testObj.Name, objDeserialized.Name);
  5237. Assert.AreEqual(0, objDeserialized.Age);
  5238. }
  5239. private T SerializeAndDeserialize<T>(T obj)
  5240. where T : class
  5241. {
  5242. var json = Serialize(obj);
  5243. return Deserialize<T>(json);
  5244. }
  5245. private string Serialize<T>(T obj)
  5246. where T : class
  5247. {
  5248. var stringWriter = new StringWriter();
  5249. var serializer = new Newtonsoft.Json.JsonSerializer();
  5250. serializer.ContractResolver = new DefaultContractResolver(false)
  5251. {
  5252. IgnoreSerializableAttribute = false
  5253. };
  5254. serializer.Serialize(stringWriter, obj);
  5255. return stringWriter.ToString();
  5256. }
  5257. private T Deserialize<T>(string json)
  5258. where T : class
  5259. {
  5260. var jsonReader = new Newtonsoft.Json.JsonTextReader(new StringReader(json));
  5261. var serializer = new Newtonsoft.Json.JsonSerializer();
  5262. serializer.ContractResolver = new DefaultContractResolver(false)
  5263. {
  5264. IgnoreSerializableAttribute = false
  5265. };
  5266. return serializer.Deserialize(jsonReader, typeof(T)) as T;
  5267. }
  5268. #endif
  5269. [Test]
  5270. public void PropertyItemConverter()
  5271. {
  5272. Event e = new Event
  5273. {
  5274. EventName = "Blackadder III",
  5275. Venue = "Gryphon Theatre",
  5276. Performances = new List<DateTime>
  5277. {
  5278. JsonConvert.ConvertJavaScriptTicksToDateTime(1336458600000),
  5279. JsonConvert.ConvertJavaScriptTicksToDateTime(1336545000000),
  5280. JsonConvert.ConvertJavaScriptTicksToDateTime(1336636800000)
  5281. }
  5282. };
  5283. string json = JsonConvert.SerializeObject(e, Formatting.Indented);
  5284. //{
  5285. // "EventName": "Blackadder III",
  5286. // "Venue": "Gryphon Theatre",
  5287. // "Performances": [
  5288. // new Date(1336458600000),
  5289. // new Date(1336545000000),
  5290. // new Date(1336636800000)
  5291. // ]
  5292. //}
  5293. Assert.AreEqual(@"{
  5294. ""EventName"": ""Blackadder III"",
  5295. ""Venue"": ""Gryphon Theatre"",
  5296. ""Performances"": [
  5297. new Date(
  5298. 1336458600000
  5299. ),
  5300. new Date(
  5301. 1336545000000
  5302. ),
  5303. new Date(
  5304. 1336636800000
  5305. )
  5306. ]
  5307. }", json);
  5308. }
  5309. #if !(NET20 || NET35)
  5310. [Test]
  5311. public void SerializeDataContractSerializationAttributes()
  5312. {
  5313. DataContractSerializationAttributesClass dataContract = new DataContractSerializationAttributesClass
  5314. {
  5315. NoAttribute = "Value!",
  5316. IgnoreDataMemberAttribute = "Value!",
  5317. DataMemberAttribute = "Value!",
  5318. IgnoreDataMemberAndDataMemberAttribute = "Value!"
  5319. };
  5320. string json = JsonConvert.SerializeObject(dataContract, Formatting.Indented);
  5321. Assert.AreEqual(@"{
  5322. ""DataMemberAttribute"": ""Value!"",
  5323. ""IgnoreDataMemberAndDataMemberAttribute"": ""Value!""
  5324. }", json);
  5325. PocoDataContractSerializationAttributesClass poco = new PocoDataContractSerializationAttributesClass
  5326. {
  5327. NoAttribute = "Value!",
  5328. IgnoreDataMemberAttribute = "Value!",
  5329. DataMemberAttribute = "Value!",
  5330. IgnoreDataMemberAndDataMemberAttribute = "Value!"
  5331. };
  5332. json = JsonConvert.SerializeObject(poco, Formatting.Indented);
  5333. Assert.AreEqual(@"{
  5334. ""NoAttribute"": ""Value!"",
  5335. ""DataMemberAttribute"": ""Value!""
  5336. }", json);
  5337. }
  5338. #endif
  5339. [Test]
  5340. public void CheckAdditionalContent()
  5341. {
  5342. string json = "{one:1}{}";
  5343. JsonSerializerSettings settings = new JsonSerializerSettings();
  5344. JsonSerializer s = JsonSerializer.Create(settings);
  5345. IDictionary<string, int> o = s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json)));
  5346. Assert.IsNotNull(o);
  5347. Assert.AreEqual(1, o["one"]);
  5348. settings.CheckAdditionalContent = true;
  5349. s = JsonSerializer.Create(settings);
  5350. ExceptionAssert.Throws<JsonReaderException>(
  5351. "Additional text encountered after finished reading JSON content: {. Path '', line 1, position 7.",
  5352. () =>
  5353. {
  5354. s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json)));
  5355. });
  5356. }
  5357. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  5358. [Test]
  5359. public void DeserializeException()
  5360. {
  5361. string json = @"{ ""ClassName"" : ""System.InvalidOperationException"",
  5362. ""Data"" : null,
  5363. ""ExceptionMethod"" : ""8\nLogin\nAppBiz, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null\nMyApp.LoginBiz\nMyApp.User Login()"",
  5364. ""HResult"" : -2146233079,
  5365. ""HelpURL"" : null,
  5366. ""InnerException"" : { ""ClassName"" : ""System.Exception"",
  5367. ""Data"" : null,
  5368. ""ExceptionMethod"" : null,
  5369. ""HResult"" : -2146233088,
  5370. ""HelpURL"" : null,
  5371. ""InnerException"" : null,
  5372. ""Message"" : ""Inner exception..."",
  5373. ""RemoteStackIndex"" : 0,
  5374. ""RemoteStackTraceString"" : null,
  5375. ""Source"" : null,
  5376. ""StackTraceString"" : null,
  5377. ""WatsonBuckets"" : null
  5378. },
  5379. ""Message"" : ""Outter exception..."",
  5380. ""RemoteStackIndex"" : 0,
  5381. ""RemoteStackTraceString"" : null,
  5382. ""Source"" : ""AppBiz"",
  5383. ""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)"",
  5384. ""WatsonBuckets"" : null
  5385. }";
  5386. InvalidOperationException exception = JsonConvert.DeserializeObject<InvalidOperationException>(json);
  5387. Assert.IsNotNull(exception);
  5388. CustomAssert.IsInstanceOfType(typeof(InvalidOperationException), exception);
  5389. Assert.AreEqual("Outter exception...", exception.Message);
  5390. }
  5391. #endif
  5392. [Test]
  5393. public void AdditionalContentAfterFinish()
  5394. {
  5395. ExceptionAssert.Throws<JsonException>(
  5396. "Additional text found in JSON string after finishing deserializing object.",
  5397. () =>
  5398. {
  5399. string json = "[{},1]";
  5400. JsonSerializer serializer = new JsonSerializer();
  5401. serializer.CheckAdditionalContent = true;
  5402. var reader = new JsonTextReader(new StringReader(json));
  5403. reader.Read();
  5404. reader.Read();
  5405. serializer.Deserialize(reader, typeof (MyType));
  5406. });
  5407. }
  5408. [Test]
  5409. public void DeserializeRelativeUri()
  5410. {
  5411. IList<Uri> uris = JsonConvert.DeserializeObject<IList<Uri>>(@"[""http://localhost/path?query#hash""]");
  5412. Assert.AreEqual(1, uris.Count);
  5413. Assert.AreEqual(new Uri("http://localhost/path?query#hash"), uris[0]);
  5414. Uri uri = JsonConvert.DeserializeObject<Uri>(@"""http://localhost/path?query#hash""");
  5415. Assert.IsNotNull(uri);
  5416. Uri i1 = new Uri("http://localhost/path?query#hash", UriKind.RelativeOrAbsolute);
  5417. Uri i2 = new Uri("http://localhost/path?query#hash");
  5418. Assert.AreEqual(i1, i2);
  5419. uri = JsonConvert.DeserializeObject<Uri>(@"""/path?query#hash""");
  5420. Assert.IsNotNull(uri);
  5421. Assert.AreEqual(new Uri("/path?query#hash", UriKind.RelativeOrAbsolute), uri);
  5422. }
  5423. public class MyConverter : JsonConverter
  5424. {
  5425. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  5426. {
  5427. writer.WriteValue("X");
  5428. }
  5429. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  5430. {
  5431. return "X";
  5432. }
  5433. public override bool CanConvert(Type objectType)
  5434. {
  5435. return true;
  5436. }
  5437. }
  5438. public class MyType
  5439. {
  5440. [JsonProperty(ItemConverterType = typeof(MyConverter))]
  5441. public Dictionary<string, object> MyProperty { get; set; }
  5442. }
  5443. [Test]
  5444. public void DeserializeDictionaryItemConverter()
  5445. {
  5446. var actual = JsonConvert.DeserializeObject<MyType>(@"{ ""MyProperty"":{""Key"":""Y""}}");
  5447. Assert.AreEqual("X", actual.MyProperty["Key"]);
  5448. }
  5449. [Test]
  5450. public void DeserializeCaseInsensitiveKeyValuePairConverter()
  5451. {
  5452. KeyValuePair<int, string> result =
  5453. JsonConvert.DeserializeObject<KeyValuePair<int, string>>(
  5454. "{key: 123, \"VALUE\": \"test value\"}"
  5455. );
  5456. Assert.AreEqual(123, result.Key);
  5457. Assert.AreEqual("test value", result.Value);
  5458. }
  5459. [Test]
  5460. public void SerializeKeyValuePairConverterWithCamelCase()
  5461. {
  5462. string json =
  5463. JsonConvert.SerializeObject(new KeyValuePair<int, string>(123, "test value"), Formatting.Indented, new JsonSerializerSettings
  5464. {
  5465. ContractResolver = new CamelCasePropertyNamesContractResolver()
  5466. });
  5467. Assert.AreEqual(@"{
  5468. ""key"": 123,
  5469. ""value"": ""test value""
  5470. }", json);
  5471. }
  5472. [JsonObject(MemberSerialization.Fields)]
  5473. public class MyTuple<T1>
  5474. {
  5475. private readonly T1 m_Item1;
  5476. public MyTuple(T1 item1)
  5477. {
  5478. m_Item1 = item1;
  5479. }
  5480. public T1 Item1
  5481. {
  5482. get { return m_Item1; }
  5483. }
  5484. }
  5485. [JsonObject(MemberSerialization.Fields)]
  5486. public class MyTuplePartial<T1>
  5487. {
  5488. private readonly T1 m_Item1;
  5489. public MyTuplePartial(T1 item1)
  5490. {
  5491. m_Item1 = item1;
  5492. }
  5493. public T1 Item1
  5494. {
  5495. get { return m_Item1; }
  5496. }
  5497. }
  5498. [Test]
  5499. public void SerializeCustomTupleWithSerializableAttribute()
  5500. {
  5501. var tuple = new MyTuple<int>(500);
  5502. var json = JsonConvert.SerializeObject(tuple);
  5503. Assert.AreEqual(@"{""m_Item1"":500}", json);
  5504. MyTuple<int> obj = null;
  5505. Action doStuff = () =>
  5506. {
  5507. obj = JsonConvert.DeserializeObject<MyTuple<int>>(json);
  5508. };
  5509. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  5510. doStuff();
  5511. Assert.AreEqual(500, obj.Item1);
  5512. #else
  5513. ExceptionAssert.Throws<JsonSerializationException>(
  5514. "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.",
  5515. doStuff);
  5516. #endif
  5517. }
  5518. #if DEBUG
  5519. [Test]
  5520. public void SerializeCustomTupleWithSerializableAttributeInPartialTrust()
  5521. {
  5522. try
  5523. {
  5524. JsonTypeReflector.SetFullyTrusted(false);
  5525. var tuple = new MyTuplePartial<int>(500);
  5526. var json = JsonConvert.SerializeObject(tuple);
  5527. Assert.AreEqual(@"{""m_Item1"":500}", json);
  5528. ExceptionAssert.Throws<JsonSerializationException>(
  5529. "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.",
  5530. () => JsonConvert.DeserializeObject<MyTuplePartial<int>>(json));
  5531. }
  5532. finally
  5533. {
  5534. JsonTypeReflector.SetFullyTrusted(true);
  5535. }
  5536. }
  5537. #endif
  5538. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || NET35 || NET20)
  5539. [Test]
  5540. public void SerializeTupleWithSerializableAttribute()
  5541. {
  5542. var tuple = Tuple.Create(500);
  5543. var json = JsonConvert.SerializeObject(tuple, new JsonSerializerSettings
  5544. {
  5545. ContractResolver = new SerializableContractResolver()
  5546. });
  5547. Assert.AreEqual(@"{""m_Item1"":500}", json);
  5548. var obj = JsonConvert.DeserializeObject<Tuple<int>>(json, new JsonSerializerSettings
  5549. {
  5550. ContractResolver = new SerializableContractResolver()
  5551. });
  5552. Assert.AreEqual(500, obj.Item1);
  5553. }
  5554. public class SerializableContractResolver : DefaultContractResolver
  5555. {
  5556. public SerializableContractResolver()
  5557. {
  5558. IgnoreSerializableAttribute = false;
  5559. }
  5560. }
  5561. #endif
  5562. [Test]
  5563. public void SerializeArray2D()
  5564. {
  5565. Array2D aa = new Array2D();
  5566. aa.Before = "Before!";
  5567. aa.After = "After!";
  5568. aa.Coordinates = new[,] { { 1, 1 }, { 1, 2 }, { 2, 1 }, { 2, 2 } };
  5569. string json = JsonConvert.SerializeObject(aa);
  5570. Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}", json);
  5571. }
  5572. [Test]
  5573. public void SerializeArray3D()
  5574. {
  5575. Array3D aa = new Array3D();
  5576. aa.Before = "Before!";
  5577. aa.After = "After!";
  5578. 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 } } };
  5579. string json = JsonConvert.SerializeObject(aa);
  5580. 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);
  5581. }
  5582. [Test]
  5583. public void SerializeArray3DWithConverter()
  5584. {
  5585. Array3DWithConverter aa = new Array3DWithConverter();
  5586. aa.Before = "Before!";
  5587. aa.After = "After!";
  5588. 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 } } };
  5589. string json = JsonConvert.SerializeObject(aa, Formatting.Indented);
  5590. Assert.AreEqual(@"{
  5591. ""Before"": ""Before!"",
  5592. ""Coordinates"": [
  5593. [
  5594. [
  5595. 1.0,
  5596. 1.0,
  5597. 1.0
  5598. ],
  5599. [
  5600. 1.0,
  5601. 1.0,
  5602. 2.0
  5603. ]
  5604. ],
  5605. [
  5606. [
  5607. 1.0,
  5608. 2.0,
  5609. 1.0
  5610. ],
  5611. [
  5612. 1.0,
  5613. 2.0,
  5614. 2.0
  5615. ]
  5616. ],
  5617. [
  5618. [
  5619. 2.0,
  5620. 1.0,
  5621. 1.0
  5622. ],
  5623. [
  5624. 2.0,
  5625. 1.0,
  5626. 2.0
  5627. ]
  5628. ],
  5629. [
  5630. [
  5631. 2.0,
  5632. 2.0,
  5633. 1.0
  5634. ],
  5635. [
  5636. 2.0,
  5637. 2.0,
  5638. 2.0
  5639. ]
  5640. ]
  5641. ],
  5642. ""After"": ""After!""
  5643. }", json);
  5644. }
  5645. [Test]
  5646. public void DeserializeArray3DWithConverter()
  5647. {
  5648. string json = @"{
  5649. ""Before"": ""Before!"",
  5650. ""Coordinates"": [
  5651. [
  5652. [
  5653. 1.0,
  5654. 1.0,
  5655. 1.0
  5656. ],
  5657. [
  5658. 1.0,
  5659. 1.0,
  5660. 2.0
  5661. ]
  5662. ],
  5663. [
  5664. [
  5665. 1.0,
  5666. 2.0,
  5667. 1.0
  5668. ],
  5669. [
  5670. 1.0,
  5671. 2.0,
  5672. 2.0
  5673. ]
  5674. ],
  5675. [
  5676. [
  5677. 2.0,
  5678. 1.0,
  5679. 1.0
  5680. ],
  5681. [
  5682. 2.0,
  5683. 1.0,
  5684. 2.0
  5685. ]
  5686. ],
  5687. [
  5688. [
  5689. 2.0,
  5690. 2.0,
  5691. 1.0
  5692. ],
  5693. [
  5694. 2.0,
  5695. 2.0,
  5696. 2.0
  5697. ]
  5698. ]
  5699. ],
  5700. ""After"": ""After!""
  5701. }";
  5702. Array3DWithConverter aa = JsonConvert.DeserializeObject<Array3DWithConverter>(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. }
  5711. [Test]
  5712. public void DeserializeArray2D()
  5713. {
  5714. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}";
  5715. Array2D aa = JsonConvert.DeserializeObject<Array2D>(json);
  5716. Assert.AreEqual("Before!", aa.Before);
  5717. Assert.AreEqual("After!", aa.After);
  5718. Assert.AreEqual(4, aa.Coordinates.GetLength(0));
  5719. Assert.AreEqual(2, aa.Coordinates.GetLength(1));
  5720. Assert.AreEqual(1, aa.Coordinates[0, 0]);
  5721. Assert.AreEqual(2, aa.Coordinates[1, 1]);
  5722. string after = JsonConvert.SerializeObject(aa);
  5723. Assert.AreEqual(json, after);
  5724. }
  5725. [Test]
  5726. public void DeserializeArray2D_WithTooManyItems()
  5727. {
  5728. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2,3],[2,1],[2,2]],""After"":""After!""}";
  5729. ExceptionAssert.Throws<Exception>(
  5730. "Cannot deserialize non-cubical array as multidimensional array.",
  5731. () => JsonConvert.DeserializeObject<Array2D>(json));
  5732. }
  5733. [Test]
  5734. public void DeserializeArray2D_WithTooFewItems()
  5735. {
  5736. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1],[2,1],[2,2]],""After"":""After!""}";
  5737. ExceptionAssert.Throws<Exception>(
  5738. "Cannot deserialize non-cubical array as multidimensional array.",
  5739. () => JsonConvert.DeserializeObject<Array2D>(json));
  5740. }
  5741. [Test]
  5742. public void DeserializeArray3D()
  5743. {
  5744. 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!""}";
  5745. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  5746. Assert.AreEqual("Before!", aa.Before);
  5747. Assert.AreEqual("After!", aa.After);
  5748. Assert.AreEqual(4, aa.Coordinates.GetLength(0));
  5749. Assert.AreEqual(2, aa.Coordinates.GetLength(1));
  5750. Assert.AreEqual(3, aa.Coordinates.GetLength(2));
  5751. Assert.AreEqual(1, aa.Coordinates[0, 0, 0]);
  5752. Assert.AreEqual(2, aa.Coordinates[1, 1, 1]);
  5753. string after = JsonConvert.SerializeObject(aa);
  5754. Assert.AreEqual(json, after);
  5755. }
  5756. [Test]
  5757. public void DeserializeArray3D_WithTooManyItems()
  5758. {
  5759. 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!""}";
  5760. ExceptionAssert.Throws<Exception>(
  5761. "Cannot deserialize non-cubical array as multidimensional array.",
  5762. () => JsonConvert.DeserializeObject<Array3D>(json));
  5763. }
  5764. [Test]
  5765. public void DeserializeArray3D_WithBadItems()
  5766. {
  5767. 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!""}";
  5768. ExceptionAssert.Throws<JsonSerializationException>(
  5769. "Unexpected token when deserializing multidimensional array: StartObject. Path 'Coordinates[3][1]', line 1, position 99.",
  5770. () => JsonConvert.DeserializeObject<Array3D>(json));
  5771. }
  5772. [Test]
  5773. public void DeserializeArray3D_WithTooFewItems()
  5774. {
  5775. 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!""}";
  5776. ExceptionAssert.Throws<Exception>(
  5777. "Cannot deserialize non-cubical array as multidimensional array.",
  5778. () => JsonConvert.DeserializeObject<Array3D>(json));
  5779. }
  5780. [Test]
  5781. public void SerializeEmpty3DArray()
  5782. {
  5783. Array3D aa = new Array3D();
  5784. aa.Before = "Before!";
  5785. aa.After = "After!";
  5786. aa.Coordinates = new int[0, 0, 0];
  5787. string json = JsonConvert.SerializeObject(aa);
  5788. Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[],""After"":""After!""}", json);
  5789. }
  5790. [Test]
  5791. public void DeserializeEmpty3DArray()
  5792. {
  5793. string json = @"{""Before"":""Before!"",""Coordinates"":[],""After"":""After!""}";
  5794. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  5795. Assert.AreEqual("Before!", aa.Before);
  5796. Assert.AreEqual("After!", aa.After);
  5797. Assert.AreEqual(0, aa.Coordinates.GetLength(0));
  5798. Assert.AreEqual(0, aa.Coordinates.GetLength(1));
  5799. Assert.AreEqual(0, aa.Coordinates.GetLength(2));
  5800. string after = JsonConvert.SerializeObject(aa);
  5801. Assert.AreEqual(json, after);
  5802. }
  5803. [Test]
  5804. public void DeserializeIncomplete3DArray()
  5805. {
  5806. string json = @"{""Before"":""Before!"",""Coordinates"":[/*hi*/[/*hi*/[1/*hi*/,/*hi*/1/*hi*/,1]/*hi*/,/*hi*/[1,1";
  5807. ExceptionAssert.Throws<JsonSerializationException>(
  5808. "Unexpected end when deserializing array. Path 'Coordinates[0][1][1]', line 1, position 90.",
  5809. () => JsonConvert.DeserializeObject<Array3D>(json));
  5810. }
  5811. [Test]
  5812. public void DeserializeIncompleteNotTopLevel3DArray()
  5813. {
  5814. string json = @"{""Before"":""Before!"",""Coordinates"":[/*hi*/[/*hi*/";
  5815. ExceptionAssert.Throws<JsonSerializationException>(
  5816. "Unexpected end when deserializing array. Path 'Coordinates[0]', line 1, position 48.",
  5817. () => JsonConvert.DeserializeObject<Array3D>(json));
  5818. }
  5819. [Test]
  5820. public void DeserializeNull3DArray()
  5821. {
  5822. string json = @"{""Before"":""Before!"",""Coordinates"":null,""After"":""After!""}";
  5823. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  5824. Assert.AreEqual("Before!", aa.Before);
  5825. Assert.AreEqual("After!", aa.After);
  5826. Assert.AreEqual(null, aa.Coordinates);
  5827. string after = JsonConvert.SerializeObject(aa);
  5828. Assert.AreEqual(json, after);
  5829. }
  5830. [Test]
  5831. public void DeserializeSemiEmpty3DArray()
  5832. {
  5833. string json = @"{""Before"":""Before!"",""Coordinates"":[[]],""After"":""After!""}";
  5834. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  5835. Assert.AreEqual("Before!", aa.Before);
  5836. Assert.AreEqual("After!", aa.After);
  5837. Assert.AreEqual(1, aa.Coordinates.GetLength(0));
  5838. Assert.AreEqual(0, aa.Coordinates.GetLength(1));
  5839. Assert.AreEqual(0, aa.Coordinates.GetLength(2));
  5840. string after = JsonConvert.SerializeObject(aa);
  5841. Assert.AreEqual(json, after);
  5842. }
  5843. [Test]
  5844. public void SerializeReferenceTracked3DArray()
  5845. {
  5846. Event e1 = new Event
  5847. {
  5848. EventName = "EventName!"
  5849. };
  5850. Event[,] array1 = new [,] { { e1, e1 }, { e1, e1 } };
  5851. IList<Event[,]> values1 = new List<Event[,]>
  5852. {
  5853. array1,
  5854. array1
  5855. };
  5856. string json = JsonConvert.SerializeObject(values1, new JsonSerializerSettings
  5857. {
  5858. PreserveReferencesHandling = PreserveReferencesHandling.All,
  5859. Formatting = Formatting.Indented
  5860. });
  5861. Assert.AreEqual(@"{
  5862. ""$id"": ""1"",
  5863. ""$values"": [
  5864. {
  5865. ""$id"": ""2"",
  5866. ""$values"": [
  5867. [
  5868. {
  5869. ""$id"": ""3"",
  5870. ""EventName"": ""EventName!"",
  5871. ""Venue"": null,
  5872. ""Performances"": null
  5873. },
  5874. {
  5875. ""$ref"": ""3""
  5876. }
  5877. ],
  5878. [
  5879. {
  5880. ""$ref"": ""3""
  5881. },
  5882. {
  5883. ""$ref"": ""3""
  5884. }
  5885. ]
  5886. ]
  5887. },
  5888. {
  5889. ""$ref"": ""2""
  5890. }
  5891. ]
  5892. }", json);
  5893. }
  5894. [Test]
  5895. public void SerializeTypeName3DArray()
  5896. {
  5897. Event e1 = new Event
  5898. {
  5899. EventName = "EventName!"
  5900. };
  5901. Event[,] array1 = new[,] { { e1, e1 }, { e1, e1 } };
  5902. IList<Event[,]> values1 = new List<Event[,]>
  5903. {
  5904. array1,
  5905. array1
  5906. };
  5907. string json = JsonConvert.SerializeObject(values1, new JsonSerializerSettings
  5908. {
  5909. TypeNameHandling = TypeNameHandling.All,
  5910. Formatting = Formatting.Indented
  5911. });
  5912. Assert.AreEqual(@"{
  5913. ""$type"": ""System.Collections.Generic.List`1[[Newtonsoft.Json.Tests.Serialization.Event[,], Newtonsoft.Json.Tests]], mscorlib"",
  5914. ""$values"": [
  5915. {
  5916. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event[,], Newtonsoft.Json.Tests"",
  5917. ""$values"": [
  5918. [
  5919. {
  5920. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5921. ""EventName"": ""EventName!"",
  5922. ""Venue"": null,
  5923. ""Performances"": null
  5924. },
  5925. {
  5926. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5927. ""EventName"": ""EventName!"",
  5928. ""Venue"": null,
  5929. ""Performances"": null
  5930. }
  5931. ],
  5932. [
  5933. {
  5934. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5935. ""EventName"": ""EventName!"",
  5936. ""Venue"": null,
  5937. ""Performances"": null
  5938. },
  5939. {
  5940. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5941. ""EventName"": ""EventName!"",
  5942. ""Venue"": null,
  5943. ""Performances"": null
  5944. }
  5945. ]
  5946. ]
  5947. },
  5948. {
  5949. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event[,], Newtonsoft.Json.Tests"",
  5950. ""$values"": [
  5951. [
  5952. {
  5953. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5954. ""EventName"": ""EventName!"",
  5955. ""Venue"": null,
  5956. ""Performances"": null
  5957. },
  5958. {
  5959. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5960. ""EventName"": ""EventName!"",
  5961. ""Venue"": null,
  5962. ""Performances"": null
  5963. }
  5964. ],
  5965. [
  5966. {
  5967. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5968. ""EventName"": ""EventName!"",
  5969. ""Venue"": null,
  5970. ""Performances"": null
  5971. },
  5972. {
  5973. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  5974. ""EventName"": ""EventName!"",
  5975. ""Venue"": null,
  5976. ""Performances"": null
  5977. }
  5978. ]
  5979. ]
  5980. }
  5981. ]
  5982. }", json);
  5983. IList<Event[,]> values2 = (IList<Event[,]>)JsonConvert.DeserializeObject(json, new JsonSerializerSettings
  5984. {
  5985. TypeNameHandling = TypeNameHandling.All
  5986. });
  5987. Assert.AreEqual(2, values2.Count);
  5988. Assert.AreEqual("EventName!", values2[0][0, 0].EventName);
  5989. }
  5990. #if NETFX_CORE
  5991. [Test]
  5992. public void SerializeWinRTJsonObject()
  5993. {
  5994. var o = Windows.Data.Json.JsonObject.Parse(@"{
  5995. ""CPU"": ""Intel"",
  5996. ""Drives"": [
  5997. ""DVD read/writer"",
  5998. ""500 gigabyte hard drive""
  5999. ]
  6000. }");
  6001. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  6002. Assert.AreEqual(@"{
  6003. ""Drives"": [
  6004. ""DVD read/writer"",
  6005. ""500 gigabyte hard drive""
  6006. ],
  6007. ""CPU"": ""Intel""
  6008. }", json);
  6009. }
  6010. #endif
  6011. #if !NET20
  6012. [Test]
  6013. public void RoundtripOfDateTimeOffset()
  6014. {
  6015. var content = @"{""startDateTime"":""2012-07-19T14:30:00+09:30""}";
  6016. var jsonSerializerSettings = new JsonSerializerSettings() {DateFormatHandling = DateFormatHandling.IsoDateFormat, DateParseHandling = DateParseHandling.DateTimeOffset, DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind};
  6017. var obj = (JObject)JsonConvert.DeserializeObject(content, jsonSerializerSettings);
  6018. var dateTimeOffset = (DateTimeOffset)((JValue) obj["startDateTime"]).Value;
  6019. Assert.AreEqual(TimeSpan.FromHours(9.5), dateTimeOffset.Offset);
  6020. Assert.AreEqual("07/19/2012 14:30:00 +09:30", dateTimeOffset.ToString(CultureInfo.InvariantCulture));
  6021. }
  6022. #endif
  6023. #if !NET20
  6024. public class NullableTestClass
  6025. {
  6026. public bool? MyNullableBool { get; set; }
  6027. public int? MyNullableInteger { get; set; }
  6028. public DateTime? MyNullableDateTime { get; set; }
  6029. public DateTimeOffset? MyNullableDateTimeOffset { get; set; }
  6030. public Decimal? MyNullableDecimal { get; set; }
  6031. }
  6032. [Test]
  6033. public void TestStringToNullableDeserialization()
  6034. {
  6035. string json = @"{
  6036. ""MyNullableBool"": """",
  6037. ""MyNullableInteger"": """",
  6038. ""MyNullableDateTime"": """",
  6039. ""MyNullableDateTimeOffset"": """",
  6040. ""MyNullableDecimal"": """"
  6041. }";
  6042. NullableTestClass c2 = JsonConvert.DeserializeObject<NullableTestClass>(json);
  6043. Assert.IsNull(c2.MyNullableBool);
  6044. Assert.IsNull(c2.MyNullableInteger);
  6045. Assert.IsNull(c2.MyNullableDateTime);
  6046. Assert.IsNull(c2.MyNullableDateTimeOffset);
  6047. Assert.IsNull(c2.MyNullableDecimal);
  6048. }
  6049. #endif
  6050. }
  6051. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  6052. [Serializable]
  6053. public class PersonSerializable
  6054. {
  6055. public PersonSerializable()
  6056. { }
  6057. private string _name = "";
  6058. public string Name
  6059. {
  6060. get { return _name; }
  6061. set { _name = value; }
  6062. }
  6063. [NonSerialized]
  6064. private int _age = 0;
  6065. public int Age
  6066. {
  6067. get { return _age; }
  6068. set { _age = value; }
  6069. }
  6070. }
  6071. #endif
  6072. public class Event
  6073. {
  6074. public string EventName { get; set; }
  6075. public string Venue { get; set; }
  6076. [JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
  6077. public IList<DateTime> Performances { get; set; }
  6078. }
  6079. public class PropertyItemConverter
  6080. {
  6081. [JsonProperty(ItemConverterType = typeof(MetroStringConverter))]
  6082. public IList<string> Data { get; set; }
  6083. }
  6084. public class PersonWithPrivateConstructor
  6085. {
  6086. private PersonWithPrivateConstructor()
  6087. { }
  6088. public static PersonWithPrivateConstructor CreatePerson()
  6089. {
  6090. return new PersonWithPrivateConstructor();
  6091. }
  6092. public string Name { get; set; }
  6093. public int Age { get; set; }
  6094. }
  6095. public class DateTimeWrapper
  6096. {
  6097. public DateTime Value { get; set; }
  6098. }
  6099. public class Widget1
  6100. {
  6101. public WidgetId1? Id { get; set; }
  6102. }
  6103. [JsonConverter(typeof(WidgetIdJsonConverter))]
  6104. public struct WidgetId1
  6105. {
  6106. public long Value { get; set; }
  6107. }
  6108. public class WidgetIdJsonConverter : JsonConverter
  6109. {
  6110. public override bool CanConvert(Type objectType)
  6111. {
  6112. return objectType == typeof(WidgetId1) || objectType == typeof(WidgetId1?);
  6113. }
  6114. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  6115. {
  6116. WidgetId1 id = (WidgetId1)value;
  6117. writer.WriteValue(id.Value.ToString());
  6118. }
  6119. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  6120. {
  6121. if (reader.TokenType == JsonToken.Null)
  6122. return null;
  6123. return new WidgetId1 { Value = int.Parse(reader.Value.ToString()) };
  6124. }
  6125. }
  6126. public enum MyEnum
  6127. {
  6128. Value1,
  6129. Value2,
  6130. Value3
  6131. }
  6132. public class WithEnums
  6133. {
  6134. public int Id { get; set; }
  6135. public MyEnum? NullableEnum { get; set; }
  6136. }
  6137. public class Item
  6138. {
  6139. public Guid SourceTypeID { get; set; }
  6140. public Guid BrokerID { get; set; }
  6141. public double Latitude { get; set; }
  6142. public double Longitude { get; set; }
  6143. public DateTime TimeStamp { get; set; }
  6144. [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
  6145. public object Payload { get; set; }
  6146. }
  6147. public class NullableGuid
  6148. {
  6149. public Guid? Id { get; set; }
  6150. }
  6151. public class Widget
  6152. {
  6153. public WidgetId? Id { get; set; }
  6154. }
  6155. public struct WidgetId
  6156. {
  6157. public string Value { get; set; }
  6158. }
  6159. public class DecimalTestClass
  6160. {
  6161. public decimal Quantity { get; set; }
  6162. public double OptionalQuantity { get; set; }
  6163. }
  6164. public class TestObject
  6165. {
  6166. public TestObject()
  6167. {
  6168. }
  6169. public TestObject(string name, byte[] data)
  6170. {
  6171. Name = name;
  6172. Data = data;
  6173. }
  6174. public string Name { get; set; }
  6175. public byte[] Data { get; set; }
  6176. }
  6177. public class UriGuidTimeSpanTestClass
  6178. {
  6179. public Guid Guid { get; set; }
  6180. public Guid? NullableGuid { get; set; }
  6181. public TimeSpan TimeSpan { get; set; }
  6182. public TimeSpan? NullableTimeSpan { get; set; }
  6183. public Uri Uri { get; set; }
  6184. }
  6185. internal class Aa
  6186. {
  6187. public int no;
  6188. }
  6189. internal class Bb : Aa
  6190. {
  6191. public new bool no;
  6192. }
  6193. #if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE)
  6194. [JsonObject(MemberSerialization.OptIn)]
  6195. public class GameObject
  6196. {
  6197. [JsonProperty]
  6198. public string Id { get; set; }
  6199. [JsonProperty]
  6200. public string Name { get; set; }
  6201. [JsonProperty] public ConcurrentDictionary<string, Component> Components;
  6202. public GameObject()
  6203. {
  6204. Components = new ConcurrentDictionary<string, Component>();
  6205. }
  6206. }
  6207. [JsonObject(MemberSerialization.OptIn)]
  6208. public class Component
  6209. {
  6210. [JsonIgnore] // Ignore circular reference
  6211. public GameObject GameObject { get; set; }
  6212. public Component()
  6213. {
  6214. }
  6215. }
  6216. [JsonObject(MemberSerialization.OptIn)]
  6217. public class TestComponent : Component
  6218. {
  6219. [JsonProperty]
  6220. public int MyProperty { get; set; }
  6221. public TestComponent()
  6222. {
  6223. }
  6224. }
  6225. #endif
  6226. [JsonObject(MemberSerialization.OptIn)]
  6227. public class TestComponentSimple
  6228. {
  6229. [JsonProperty]
  6230. public int MyProperty { get; set; }
  6231. public TestComponentSimple()
  6232. {
  6233. }
  6234. }
  6235. [JsonObject(ItemRequired = Required.Always)]
  6236. public class RequiredObject
  6237. {
  6238. public int? NonAttributeProperty { get; set; }
  6239. [JsonProperty]
  6240. public int? UnsetProperty { get; set; }
  6241. [JsonProperty(Required = Required.Default)]
  6242. public int? DefaultProperty { get; set; }
  6243. [JsonProperty(Required = Required.AllowNull)]
  6244. public int? AllowNullProperty { get; set; }
  6245. [JsonProperty(Required = Required.Always)]
  6246. public int? AlwaysProperty { get; set; }
  6247. }
  6248. public class MetroStringConverter : JsonConverter
  6249. {
  6250. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  6251. {
  6252. #if !(SILVERLIGHT || NETFX_CORE)
  6253. writer.WriteValue(":::" + value.ToString().ToUpper(CultureInfo.InvariantCulture) + ":::");
  6254. #else
  6255. writer.WriteValue(":::" + value.ToString().ToUpper() + ":::");
  6256. #endif
  6257. }
  6258. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  6259. {
  6260. string s = (string)reader.Value;
  6261. if (s == null)
  6262. return null;
  6263. #if !(SILVERLIGHT || NETFX_CORE)
  6264. return s.ToLower(CultureInfo.InvariantCulture).Trim(new[] { ':' });
  6265. #else
  6266. return s.ToLower().Trim(new[] { ':' });
  6267. #endif
  6268. }
  6269. public override bool CanConvert(Type objectType)
  6270. {
  6271. return objectType == typeof(string);
  6272. }
  6273. }
  6274. public class MetroPropertyNameResolver : DefaultContractResolver
  6275. {
  6276. protected internal override string ResolvePropertyName(string propertyName)
  6277. {
  6278. #if !(SILVERLIGHT || NETFX_CORE)
  6279. return ":::" + propertyName.ToUpper(CultureInfo.InvariantCulture) + ":::";
  6280. #else
  6281. return ":::" + propertyName.ToUpper() + ":::";
  6282. #endif
  6283. }
  6284. }
  6285. #if !(NET20 || NET35)
  6286. [DataContract]
  6287. public class DataContractSerializationAttributesClass
  6288. {
  6289. public string NoAttribute { get; set; }
  6290. [IgnoreDataMember]
  6291. public string IgnoreDataMemberAttribute { get; set; }
  6292. [DataMember]
  6293. public string DataMemberAttribute { get; set; }
  6294. [IgnoreDataMember]
  6295. [DataMember]
  6296. public string IgnoreDataMemberAndDataMemberAttribute { get; set; }
  6297. }
  6298. public class PocoDataContractSerializationAttributesClass
  6299. {
  6300. public string NoAttribute { get; set; }
  6301. [IgnoreDataMember]
  6302. public string IgnoreDataMemberAttribute { get; set; }
  6303. [DataMember]
  6304. public string DataMemberAttribute { get; set; }
  6305. [IgnoreDataMember]
  6306. [DataMember]
  6307. public string IgnoreDataMemberAndDataMemberAttribute { get; set; }
  6308. }
  6309. #endif
  6310. public class Array2D
  6311. {
  6312. public string Before { get; set; }
  6313. public int[,] Coordinates { get; set; }
  6314. public string After { get; set; }
  6315. }
  6316. public class Array3D
  6317. {
  6318. public string Before { get; set; }
  6319. public int[,,] Coordinates { get; set; }
  6320. public string After { get; set; }
  6321. }
  6322. public class Array3DWithConverter
  6323. {
  6324. public string Before { get; set; }
  6325. [JsonProperty(ItemConverterType = typeof(IntToFloatConverter))]
  6326. public int[, ,] Coordinates { get; set; }
  6327. public string After { get; set; }
  6328. }
  6329. public class IntToFloatConverter : JsonConverter
  6330. {
  6331. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  6332. {
  6333. writer.WriteValue(Convert.ToDouble(value));
  6334. }
  6335. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  6336. {
  6337. return Convert.ToInt32(reader.Value);
  6338. }
  6339. public override bool CanConvert(Type objectType)
  6340. {
  6341. return objectType == typeof (int);
  6342. }
  6343. }
  6344. }