PageRenderTime 269ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 3ms

/modules/JSON/Source/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs

https://bitbucket.org/ipre/calico
C# | 10532 lines | 9489 code | 889 blank | 154 comment | 89 complexity | 1710ae0df72a54210941fb297c9bbcbd MD5 | raw file
Possible License(s): LGPL-2.1, LGPL-3.0, GPL-2.0, GPL-3.0, LGPL-2.0
  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. using System.ComponentModel;
  27. #if !(NET35 || NET20 || SILVERLIGHT)
  28. using System.Collections.Concurrent;
  29. #endif
  30. using System.Collections.Generic;
  31. #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
  32. using System.Numerics;
  33. #endif
  34. #if !SILVERLIGHT && !NET20 && !NETFX_CORE
  35. using System.ComponentModel.DataAnnotations;
  36. using System.Configuration;
  37. using System.Runtime.CompilerServices;
  38. using System.Runtime.Serialization.Formatters;
  39. using System.Threading;
  40. using System.Web.Script.Serialization;
  41. #endif
  42. using System.Text;
  43. using System.Text.RegularExpressions;
  44. #if !NETFX_CORE
  45. using NUnit.Framework;
  46. #else
  47. using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
  48. using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
  49. using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
  50. #endif
  51. using Newtonsoft.Json;
  52. using System.IO;
  53. using System.Collections;
  54. using System.Xml;
  55. using System.Xml.Serialization;
  56. using System.Collections.ObjectModel;
  57. using Newtonsoft.Json.Bson;
  58. using Newtonsoft.Json.Linq;
  59. using Newtonsoft.Json.Converters;
  60. #if !NET20
  61. using System.Runtime.Serialization.Json;
  62. #endif
  63. using Newtonsoft.Json.Serialization;
  64. using Newtonsoft.Json.Tests.Linq;
  65. using Newtonsoft.Json.Tests.TestObjects;
  66. using System.Runtime.Serialization;
  67. using System.Globalization;
  68. using Newtonsoft.Json.Utilities;
  69. using System.Reflection;
  70. #if !NET20 && !SILVERLIGHT
  71. using System.Xml.Linq;
  72. using System.Collections.Specialized;
  73. using System.Linq.Expressions;
  74. #endif
  75. #if !(NET35 || NET20)
  76. using System.Dynamic;
  77. #endif
  78. #if NET20
  79. using Newtonsoft.Json.Utilities.LinqBridge;
  80. #else
  81. using System.Linq;
  82. #endif
  83. #if !(SILVERLIGHT || NETFX_CORE)
  84. using System.Drawing;
  85. using System.Diagnostics;
  86. #endif
  87. namespace Newtonsoft.Json.Tests.Serialization
  88. {
  89. [TestFixture]
  90. public class JsonSerializerTest : TestFixtureBase
  91. {
  92. public class GenericItem<T>
  93. {
  94. public T Value { get; set; }
  95. }
  96. public class NonGenericItem : GenericItem<string>
  97. {
  98. }
  99. public class GenericClass<T, TValue> : IEnumerable<T>
  100. where T : GenericItem<TValue>, new()
  101. {
  102. public IList<T> Items { get; set; }
  103. public GenericClass()
  104. {
  105. Items = new List<T>();
  106. }
  107. public IEnumerator<T> GetEnumerator()
  108. {
  109. if (Items != null)
  110. {
  111. foreach (T item in Items)
  112. {
  113. yield return item;
  114. }
  115. }
  116. else
  117. yield break;
  118. }
  119. IEnumerator IEnumerable.GetEnumerator()
  120. {
  121. return GetEnumerator();
  122. }
  123. }
  124. public class NonGenericClass : GenericClass<GenericItem<string>, string>
  125. {
  126. }
  127. #pragma warning disable 169
  128. public class CustomerInvoice
  129. {
  130. // we're only modifing the tax rate
  131. public decimal TaxRate { get; set; }
  132. // everything else gets stored here
  133. [JsonExtensionData]
  134. private IDictionary<string, JToken> _additionalData;
  135. }
  136. #pragma warning restore 169
  137. [Test]
  138. public void ExtensionDataExample()
  139. {
  140. string json = @"{
  141. 'HourlyRate': 150,
  142. 'Hours': 40,
  143. 'TaxRate': 0.125
  144. }";
  145. var invoice = JsonConvert.DeserializeObject<CustomerInvoice>(json);
  146. // increase tax to 15%
  147. invoice.TaxRate = 0.15m;
  148. string result = JsonConvert.SerializeObject(invoice);
  149. // {
  150. // 'TaxRate': 0.15,
  151. // 'HourlyRate': 150,
  152. // 'Hours': 40
  153. // }
  154. Assert.AreEqual(@"{""TaxRate"":0.15,""HourlyRate"":150,""Hours"":40}", result);
  155. }
  156. public class ExtensionDataTestClass
  157. {
  158. public string Name { get; set; }
  159. [JsonProperty("custom_name")]
  160. public string CustomName { get; set; }
  161. [JsonIgnore]
  162. public IList<int> Ignored { get; set; }
  163. public bool GetPrivate { get; internal set; }
  164. public bool GetOnly
  165. {
  166. get { return true; }
  167. }
  168. public readonly string Readonly = "Readonly";
  169. public IList<int> Ints { get; set; }
  170. [JsonExtensionData]
  171. internal IDictionary<string, JToken> ExtensionData { get; set; }
  172. public ExtensionDataTestClass()
  173. {
  174. Ints = new List<int> { 0 };
  175. }
  176. }
  177. public class JObjectExtensionDataTestClass
  178. {
  179. public string Name { get; set; }
  180. [JsonExtensionData]
  181. public JObject ExtensionData { get; set; }
  182. }
  183. [Test]
  184. public void RoundTripJObjectExtensionData()
  185. {
  186. JObjectExtensionDataTestClass c = new JObjectExtensionDataTestClass();
  187. c.Name = "Name!";
  188. c.ExtensionData = new JObject
  189. {
  190. {"one",1},
  191. {"two","II"},
  192. {"three",new JArray(1,1,1)}
  193. };
  194. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  195. JObjectExtensionDataTestClass c2 = JsonConvert.DeserializeObject<JObjectExtensionDataTestClass>(json);
  196. Assert.AreEqual("Name!", c2.Name);
  197. Assert.IsTrue(JToken.DeepEquals(c.ExtensionData, c2.ExtensionData));
  198. }
  199. [Test]
  200. public void JsonSerializerProperties()
  201. {
  202. JsonSerializer serializer = new JsonSerializer();
  203. DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
  204. serializer.Binder = customBinder;
  205. Assert.AreEqual(customBinder, serializer.Binder);
  206. serializer.CheckAdditionalContent = true;
  207. Assert.AreEqual(true, serializer.CheckAdditionalContent);
  208. serializer.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
  209. Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, serializer.ConstructorHandling);
  210. #if !NETFX_CORE
  211. serializer.Context = new StreamingContext(StreamingContextStates.Other);
  212. Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), serializer.Context);
  213. #endif
  214. CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
  215. serializer.ContractResolver = resolver;
  216. Assert.AreEqual(resolver, serializer.ContractResolver);
  217. serializer.Converters.Add(new StringEnumConverter());
  218. Assert.AreEqual(1, serializer.Converters.Count);
  219. serializer.Culture = new CultureInfo("en-nz");
  220. Assert.AreEqual("en-NZ", serializer.Culture.ToString());
  221. serializer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
  222. Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, serializer.DateFormatHandling);
  223. serializer.DateFormatString = "yyyy";
  224. Assert.AreEqual("yyyy", serializer.DateFormatString);
  225. serializer.DateParseHandling = DateParseHandling.None;
  226. Assert.AreEqual(DateParseHandling.None, serializer.DateParseHandling);
  227. serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
  228. Assert.AreEqual(DateTimeZoneHandling.Utc, serializer.DateTimeZoneHandling);
  229. serializer.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
  230. Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, serializer.DefaultValueHandling);
  231. serializer.FloatFormatHandling = FloatFormatHandling.Symbol;
  232. Assert.AreEqual(FloatFormatHandling.Symbol, serializer.FloatFormatHandling);
  233. serializer.FloatParseHandling = FloatParseHandling.Decimal;
  234. Assert.AreEqual(FloatParseHandling.Decimal, serializer.FloatParseHandling);
  235. serializer.Formatting = Formatting.Indented;
  236. Assert.AreEqual(Formatting.Indented, serializer.Formatting);
  237. serializer.MaxDepth = 9001;
  238. Assert.AreEqual(9001, serializer.MaxDepth);
  239. serializer.MissingMemberHandling = MissingMemberHandling.Error;
  240. Assert.AreEqual(MissingMemberHandling.Error, serializer.MissingMemberHandling);
  241. serializer.NullValueHandling = NullValueHandling.Ignore;
  242. Assert.AreEqual(NullValueHandling.Ignore, serializer.NullValueHandling);
  243. serializer.ObjectCreationHandling = ObjectCreationHandling.Replace;
  244. Assert.AreEqual(ObjectCreationHandling.Replace, serializer.ObjectCreationHandling);
  245. serializer.PreserveReferencesHandling = PreserveReferencesHandling.All;
  246. Assert.AreEqual(PreserveReferencesHandling.All, serializer.PreserveReferencesHandling);
  247. serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  248. Assert.AreEqual(ReferenceLoopHandling.Ignore, serializer.ReferenceLoopHandling);
  249. IdReferenceResolver referenceResolver = new IdReferenceResolver();
  250. serializer.ReferenceResolver = referenceResolver;
  251. Assert.AreEqual(referenceResolver, serializer.ReferenceResolver);
  252. serializer.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
  253. Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, serializer.StringEscapeHandling);
  254. MemoryTraceWriter traceWriter = new MemoryTraceWriter();
  255. serializer.TraceWriter = traceWriter;
  256. Assert.AreEqual(traceWriter, serializer.TraceWriter);
  257. #if !(PORTABLE || PORTABLE40 || NETFX_CORE || NET20)
  258. serializer.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
  259. Assert.AreEqual(FormatterAssemblyStyle.Full, serializer.TypeNameAssemblyFormat);
  260. #endif
  261. serializer.TypeNameHandling = TypeNameHandling.All;
  262. Assert.AreEqual(TypeNameHandling.All, serializer.TypeNameHandling);
  263. }
  264. [Test]
  265. public void JsonSerializerSettingsProperties()
  266. {
  267. JsonSerializerSettings settings = new JsonSerializerSettings();
  268. DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
  269. settings.Binder = customBinder;
  270. Assert.AreEqual(customBinder, settings.Binder);
  271. settings.CheckAdditionalContent = true;
  272. Assert.AreEqual(true, settings.CheckAdditionalContent);
  273. settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
  274. Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, settings.ConstructorHandling);
  275. #if !NETFX_CORE
  276. settings.Context = new StreamingContext(StreamingContextStates.Other);
  277. Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), settings.Context);
  278. #endif
  279. CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
  280. settings.ContractResolver = resolver;
  281. Assert.AreEqual(resolver, settings.ContractResolver);
  282. settings.Converters.Add(new StringEnumConverter());
  283. Assert.AreEqual(1, settings.Converters.Count);
  284. settings.Culture = new CultureInfo("en-nz");
  285. Assert.AreEqual("en-NZ", settings.Culture.ToString());
  286. settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
  287. Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, settings.DateFormatHandling);
  288. settings.DateFormatString = "yyyy";
  289. Assert.AreEqual("yyyy", settings.DateFormatString);
  290. settings.DateParseHandling = DateParseHandling.None;
  291. Assert.AreEqual(DateParseHandling.None, settings.DateParseHandling);
  292. settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
  293. Assert.AreEqual(DateTimeZoneHandling.Utc, settings.DateTimeZoneHandling);
  294. settings.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
  295. Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, settings.DefaultValueHandling);
  296. settings.FloatFormatHandling = FloatFormatHandling.Symbol;
  297. Assert.AreEqual(FloatFormatHandling.Symbol, settings.FloatFormatHandling);
  298. settings.FloatParseHandling = FloatParseHandling.Decimal;
  299. Assert.AreEqual(FloatParseHandling.Decimal, settings.FloatParseHandling);
  300. settings.Formatting = Formatting.Indented;
  301. Assert.AreEqual(Formatting.Indented, settings.Formatting);
  302. settings.MaxDepth = 9001;
  303. Assert.AreEqual(9001, settings.MaxDepth);
  304. settings.MissingMemberHandling = MissingMemberHandling.Error;
  305. Assert.AreEqual(MissingMemberHandling.Error, settings.MissingMemberHandling);
  306. settings.NullValueHandling = NullValueHandling.Ignore;
  307. Assert.AreEqual(NullValueHandling.Ignore, settings.NullValueHandling);
  308. settings.ObjectCreationHandling = ObjectCreationHandling.Replace;
  309. Assert.AreEqual(ObjectCreationHandling.Replace, settings.ObjectCreationHandling);
  310. settings.PreserveReferencesHandling = PreserveReferencesHandling.All;
  311. Assert.AreEqual(PreserveReferencesHandling.All, settings.PreserveReferencesHandling);
  312. settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  313. Assert.AreEqual(ReferenceLoopHandling.Ignore, settings.ReferenceLoopHandling);
  314. IdReferenceResolver referenceResolver = new IdReferenceResolver();
  315. settings.ReferenceResolver = referenceResolver;
  316. Assert.AreEqual(referenceResolver, settings.ReferenceResolver);
  317. settings.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
  318. Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, settings.StringEscapeHandling);
  319. MemoryTraceWriter traceWriter = new MemoryTraceWriter();
  320. settings.TraceWriter = traceWriter;
  321. Assert.AreEqual(traceWriter, settings.TraceWriter);
  322. #if !(PORTABLE || PORTABLE40 || NETFX_CORE || NET20)
  323. settings.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
  324. Assert.AreEqual(FormatterAssemblyStyle.Full, settings.TypeNameAssemblyFormat);
  325. #endif
  326. settings.TypeNameHandling = TypeNameHandling.All;
  327. Assert.AreEqual(TypeNameHandling.All, settings.TypeNameHandling);
  328. }
  329. [Test]
  330. public void JsonSerializerProxyProperties()
  331. {
  332. JsonSerializerProxy serializerProxy = new JsonSerializerProxy(new JsonSerializerInternalReader(new JsonSerializer()));
  333. DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
  334. serializerProxy.Binder = customBinder;
  335. Assert.AreEqual(customBinder, serializerProxy.Binder);
  336. serializerProxy.CheckAdditionalContent = true;
  337. Assert.AreEqual(true, serializerProxy.CheckAdditionalContent);
  338. serializerProxy.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
  339. Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, serializerProxy.ConstructorHandling);
  340. #if !NETFX_CORE
  341. serializerProxy.Context = new StreamingContext(StreamingContextStates.Other);
  342. Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), serializerProxy.Context);
  343. #endif
  344. CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
  345. serializerProxy.ContractResolver = resolver;
  346. Assert.AreEqual(resolver, serializerProxy.ContractResolver);
  347. serializerProxy.Converters.Add(new StringEnumConverter());
  348. Assert.AreEqual(1, serializerProxy.Converters.Count);
  349. serializerProxy.Culture = new CultureInfo("en-nz");
  350. Assert.AreEqual("en-NZ", serializerProxy.Culture.ToString());
  351. serializerProxy.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
  352. Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, serializerProxy.DateFormatHandling);
  353. serializerProxy.DateFormatString = "yyyy";
  354. Assert.AreEqual("yyyy", serializerProxy.DateFormatString);
  355. serializerProxy.DateParseHandling = DateParseHandling.None;
  356. Assert.AreEqual(DateParseHandling.None, serializerProxy.DateParseHandling);
  357. serializerProxy.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
  358. Assert.AreEqual(DateTimeZoneHandling.Utc, serializerProxy.DateTimeZoneHandling);
  359. serializerProxy.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
  360. Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, serializerProxy.DefaultValueHandling);
  361. serializerProxy.FloatFormatHandling = FloatFormatHandling.Symbol;
  362. Assert.AreEqual(FloatFormatHandling.Symbol, serializerProxy.FloatFormatHandling);
  363. serializerProxy.FloatParseHandling = FloatParseHandling.Decimal;
  364. Assert.AreEqual(FloatParseHandling.Decimal, serializerProxy.FloatParseHandling);
  365. serializerProxy.Formatting = Formatting.Indented;
  366. Assert.AreEqual(Formatting.Indented, serializerProxy.Formatting);
  367. serializerProxy.MaxDepth = 9001;
  368. Assert.AreEqual(9001, serializerProxy.MaxDepth);
  369. serializerProxy.MissingMemberHandling = MissingMemberHandling.Error;
  370. Assert.AreEqual(MissingMemberHandling.Error, serializerProxy.MissingMemberHandling);
  371. serializerProxy.NullValueHandling = NullValueHandling.Ignore;
  372. Assert.AreEqual(NullValueHandling.Ignore, serializerProxy.NullValueHandling);
  373. serializerProxy.ObjectCreationHandling = ObjectCreationHandling.Replace;
  374. Assert.AreEqual(ObjectCreationHandling.Replace, serializerProxy.ObjectCreationHandling);
  375. serializerProxy.PreserveReferencesHandling = PreserveReferencesHandling.All;
  376. Assert.AreEqual(PreserveReferencesHandling.All, serializerProxy.PreserveReferencesHandling);
  377. serializerProxy.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  378. Assert.AreEqual(ReferenceLoopHandling.Ignore, serializerProxy.ReferenceLoopHandling);
  379. IdReferenceResolver referenceResolver = new IdReferenceResolver();
  380. serializerProxy.ReferenceResolver = referenceResolver;
  381. Assert.AreEqual(referenceResolver, serializerProxy.ReferenceResolver);
  382. serializerProxy.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
  383. Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, serializerProxy.StringEscapeHandling);
  384. MemoryTraceWriter traceWriter = new MemoryTraceWriter();
  385. serializerProxy.TraceWriter = traceWriter;
  386. Assert.AreEqual(traceWriter, serializerProxy.TraceWriter);
  387. #if !(PORTABLE || PORTABLE40 || NETFX_CORE || NET20)
  388. serializerProxy.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
  389. Assert.AreEqual(FormatterAssemblyStyle.Full, serializerProxy.TypeNameAssemblyFormat);
  390. #endif
  391. serializerProxy.TypeNameHandling = TypeNameHandling.All;
  392. Assert.AreEqual(TypeNameHandling.All, serializerProxy.TypeNameHandling);
  393. }
  394. #if !(NETFX_CORE || PORTABLE || PORTABLE40)
  395. [Test]
  396. public void DeserializeISerializableIConvertible()
  397. {
  398. Ratio ratio = new Ratio(2, 1);
  399. string json = JsonConvert.SerializeObject(ratio);
  400. Assert.AreEqual(@"{""n"":2,""d"":1}", json);
  401. Ratio ratio2 = JsonConvert.DeserializeObject<Ratio>(json);
  402. Assert.AreEqual(ratio.Denominator, ratio2.Denominator);
  403. Assert.AreEqual(ratio.Numerator, ratio2.Numerator);
  404. }
  405. #endif
  406. [Test]
  407. public void DeserializeLargeFloat()
  408. {
  409. object o = JsonConvert.DeserializeObject("100000000000000000000000000000000000000.0");
  410. CustomAssert.IsInstanceOfType(typeof(double), o);
  411. Assert.IsTrue(MathUtils.ApproxEquals(1E+38, (double)o));
  412. }
  413. [Test]
  414. public void SerializeDeserializeRegex()
  415. {
  416. Regex regex = new Regex("(hi)", RegexOptions.CultureInvariant);
  417. string json = JsonConvert.SerializeObject(regex, Formatting.Indented);
  418. Regex r2 = JsonConvert.DeserializeObject<Regex>(json);
  419. Assert.AreEqual("(hi)", r2.ToString());
  420. Assert.AreEqual(RegexOptions.CultureInvariant, r2.Options);
  421. }
  422. [Test]
  423. public void ExtensionDataTest()
  424. {
  425. string json = @"{
  426. ""Ints"": [1,2,3],
  427. ""Ignored"": [1,2,3],
  428. ""Readonly"": ""Readonly"",
  429. ""Name"": ""Actually set!"",
  430. ""CustomName"": ""Wrong name!"",
  431. ""GetPrivate"": true,
  432. ""GetOnly"": true,
  433. ""NewValueSimple"": true,
  434. ""NewValueComplex"": [1,2,3]
  435. }";
  436. ExtensionDataTestClass c = JsonConvert.DeserializeObject<ExtensionDataTestClass>(json);
  437. Assert.AreEqual("Actually set!", c.Name);
  438. Assert.AreEqual(4, c.Ints.Count);
  439. Assert.AreEqual("Readonly", (string)c.ExtensionData["Readonly"]);
  440. Assert.AreEqual("Wrong name!", (string)c.ExtensionData["CustomName"]);
  441. Assert.AreEqual(true, (bool)c.ExtensionData["GetPrivate"]);
  442. Assert.AreEqual(true, (bool)c.ExtensionData["GetOnly"]);
  443. Assert.AreEqual(true, (bool)c.ExtensionData["NewValueSimple"]);
  444. Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), c.ExtensionData["NewValueComplex"]));
  445. Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), c.ExtensionData["Ignored"]));
  446. Assert.AreEqual(7, c.ExtensionData.Count);
  447. }
  448. public class MultipleExtensionDataAttributesTestClass
  449. {
  450. public string Name { get; set; }
  451. [JsonExtensionData]
  452. internal IDictionary<string, JToken> ExtensionData1 { get; set; }
  453. [JsonExtensionData]
  454. internal IDictionary<string, JToken> ExtensionData2 { get; set; }
  455. }
  456. public class ExtensionDataAttributesInheritanceTestClass : MultipleExtensionDataAttributesTestClass
  457. {
  458. [JsonExtensionData]
  459. internal IDictionary<string, JToken> ExtensionData0 { get; set; }
  460. }
  461. public class FieldExtensionDataAttributeTestClass
  462. {
  463. [JsonExtensionData]
  464. internal IDictionary<object, object> ExtensionData;
  465. }
  466. public class PublicExtensionDataAttributeTestClass
  467. {
  468. public string Name { get; set; }
  469. [JsonExtensionData]
  470. public IDictionary<object, object> ExtensionData;
  471. }
  472. public class PublicNoReadExtensionDataAttributeTestClass
  473. {
  474. public string Name { get; set; }
  475. [JsonExtensionData(ReadData = false)]
  476. public IDictionary<object, object> ExtensionData;
  477. }
  478. public class PublicNoWriteExtensionDataAttributeTestClass
  479. {
  480. public string Name { get; set; }
  481. [JsonExtensionData(WriteData = false)]
  482. public IDictionary<object, object> ExtensionData;
  483. }
  484. public class PublicJTokenExtensionDataAttributeTestClass
  485. {
  486. public string Name { get; set; }
  487. [JsonExtensionData]
  488. public IDictionary<string, JToken> ExtensionData;
  489. }
  490. [Test]
  491. public void DeserializeDirectoryAccount()
  492. {
  493. string json = @"{'DisplayName':'John Smith', 'SAMAccountName':'contoso\\johns'}";
  494. DirectoryAccount account = JsonConvert.DeserializeObject<DirectoryAccount>(json);
  495. Assert.AreEqual("John Smith", account.DisplayName);
  496. Assert.AreEqual("contoso", account.Domain);
  497. Assert.AreEqual("johns", account.UserName);
  498. }
  499. [Test]
  500. public void SerializePublicExtensionData()
  501. {
  502. string json = JsonConvert.SerializeObject(new PublicExtensionDataAttributeTestClass
  503. {
  504. Name = "Name!",
  505. ExtensionData = new Dictionary<object, object>
  506. {
  507. { "Test", 1 }
  508. }
  509. });
  510. Assert.AreEqual(@"{""Name"":""Name!"",""Test"":1}", json);
  511. }
  512. [Test]
  513. public void SerializePublicExtensionDataNull()
  514. {
  515. string json = JsonConvert.SerializeObject(new PublicExtensionDataAttributeTestClass
  516. {
  517. Name = "Name!"
  518. });
  519. Assert.AreEqual(@"{""Name"":""Name!""}", json);
  520. }
  521. [Test]
  522. public void SerializePublicNoWriteExtensionData()
  523. {
  524. string json = JsonConvert.SerializeObject(new PublicNoWriteExtensionDataAttributeTestClass
  525. {
  526. Name = "Name!",
  527. ExtensionData = new Dictionary<object, object>
  528. {
  529. { "Test", 1 }
  530. }
  531. });
  532. Assert.AreEqual(@"{""Name"":""Name!""}", json);
  533. }
  534. [Test]
  535. public void DeserializeNoReadPublicExtensionData()
  536. {
  537. PublicNoReadExtensionDataAttributeTestClass c = JsonConvert.DeserializeObject<PublicNoReadExtensionDataAttributeTestClass>(@"{""Name"":""Name!"",""Test"":1}");
  538. Assert.AreEqual(null, c.ExtensionData);
  539. }
  540. [Test]
  541. public void SerializePublicExtensionDataCircularReference()
  542. {
  543. var c = new PublicExtensionDataAttributeTestClass
  544. {
  545. Name = "Name!",
  546. ExtensionData = new Dictionary<object, object>
  547. {
  548. { "Test", 1 }
  549. }
  550. };
  551. c.ExtensionData["Self"] = c;
  552. string json = JsonConvert.SerializeObject(c, new JsonSerializerSettings
  553. {
  554. PreserveReferencesHandling = PreserveReferencesHandling.All,
  555. Formatting = Formatting.Indented
  556. });
  557. Assert.AreEqual(@"{
  558. ""$id"": ""1"",
  559. ""Name"": ""Name!"",
  560. ""Test"": 1,
  561. ""Self"": {
  562. ""$ref"": ""1""
  563. }
  564. }", json);
  565. var c2 = JsonConvert.DeserializeObject<PublicExtensionDataAttributeTestClass>(json, new JsonSerializerSettings
  566. {
  567. PreserveReferencesHandling = PreserveReferencesHandling.All
  568. });
  569. Assert.AreEqual("Name!", c2.Name);
  570. PublicExtensionDataAttributeTestClass bizzaroC2 = (PublicExtensionDataAttributeTestClass)c2.ExtensionData["Self"];
  571. Assert.AreEqual(c2, bizzaroC2);
  572. Assert.AreEqual(1, (long)bizzaroC2.ExtensionData["Test"]);
  573. }
  574. [Test]
  575. public void DeserializePublicJTokenExtensionDataCircularReference()
  576. {
  577. string json = @"{
  578. ""$id"": ""1"",
  579. ""Name"": ""Name!"",
  580. ""Test"": 1,
  581. ""Self"": {
  582. ""$ref"": ""1""
  583. }
  584. }";
  585. var c2 = JsonConvert.DeserializeObject<PublicJTokenExtensionDataAttributeTestClass>(json, new JsonSerializerSettings
  586. {
  587. PreserveReferencesHandling = PreserveReferencesHandling.All
  588. });
  589. Assert.AreEqual("Name!", c2.Name);
  590. JObject bizzaroC2 = (JObject)c2.ExtensionData["Self"];
  591. Assert.AreEqual("Name!", (string)bizzaroC2["Name"]);
  592. Assert.AreEqual(1, (int)bizzaroC2["Test"]);
  593. Assert.AreEqual(1, (int)c2.ExtensionData["Test"]);
  594. }
  595. [Test]
  596. public void DeserializePublicExtensionDataTypeNamdHandling()
  597. {
  598. string json = @"{
  599. ""$id"": ""1"",
  600. ""Name"": ""Name!"",
  601. ""Test"": 1,
  602. ""Self"": {
  603. ""$type"": ""Newtonsoft.Json.Tests.TestObjects.WagePerson, Newtonsoft.Json.Tests"",
  604. ""HourlyWage"": 2.0,
  605. ""Name"": null,
  606. ""BirthDate"": ""0001-01-01T00:00:00"",
  607. ""LastModified"": ""0001-01-01T00:00:00""
  608. }
  609. }";
  610. PublicExtensionDataAttributeTestClass c2 = JsonConvert.DeserializeObject<PublicExtensionDataAttributeTestClass>(json, new JsonSerializerSettings
  611. {
  612. TypeNameHandling = TypeNameHandling.Objects
  613. });
  614. Assert.AreEqual("Name!", c2.Name);
  615. WagePerson bizzaroC2 = (WagePerson)c2.ExtensionData["Self"];
  616. Assert.AreEqual(2m, bizzaroC2.HourlyWage);
  617. }
  618. [Test]
  619. public void SerializePublicExtensionDataTypeNamdHandling()
  620. {
  621. PublicExtensionDataAttributeTestClass c = new PublicExtensionDataAttributeTestClass
  622. {
  623. Name = "Name!",
  624. ExtensionData = new Dictionary<object, object>
  625. {
  626. {
  627. "Test", new WagePerson
  628. {
  629. HourlyWage = 2.1m
  630. }
  631. }
  632. }
  633. };
  634. string json = JsonConvert.SerializeObject(c, new JsonSerializerSettings
  635. {
  636. TypeNameHandling = TypeNameHandling.Objects,
  637. Formatting = Formatting.Indented
  638. });
  639. Assert.AreEqual(@"{
  640. ""$type"": ""Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+PublicExtensionDataAttributeTestClass, Newtonsoft.Json.Tests"",
  641. ""Name"": ""Name!"",
  642. ""Test"": {
  643. ""$type"": ""Newtonsoft.Json.Tests.TestObjects.WagePerson, Newtonsoft.Json.Tests"",
  644. ""HourlyWage"": 2.1,
  645. ""Name"": null,
  646. ""BirthDate"": ""0001-01-01T00:00:00"",
  647. ""LastModified"": ""0001-01-01T00:00:00""
  648. }
  649. }", json);
  650. }
  651. [Test]
  652. public void DeserializePublicExtensionData()
  653. {
  654. string json = @"{
  655. 'Name':'Name!',
  656. 'NoMatch':'NoMatch!',
  657. 'ExtensionData':{'HAI':true}
  658. }";
  659. var c = JsonConvert.DeserializeObject<PublicExtensionDataAttributeTestClass>(json);
  660. Assert.AreEqual("Name!", c.Name);
  661. Assert.AreEqual(2, c.ExtensionData.Count);
  662. Assert.AreEqual("NoMatch!", (string)c.ExtensionData["NoMatch"]);
  663. // the ExtensionData property is put into the extension data
  664. // inception
  665. var o = (JObject)c.ExtensionData["ExtensionData"];
  666. Assert.AreEqual(1, o.Count);
  667. Assert.IsTrue(JToken.DeepEquals(new JObject { { "HAI", true } }, o));
  668. }
  669. [Test]
  670. public void FieldExtensionDataAttributeTest_Serialize()
  671. {
  672. FieldExtensionDataAttributeTestClass c = new FieldExtensionDataAttributeTestClass
  673. {
  674. ExtensionData = new Dictionary<object, object>()
  675. };
  676. string json = JsonConvert.SerializeObject(c);
  677. Assert.AreEqual("{}", json);
  678. }
  679. [Test]
  680. public void FieldExtensionDataAttributeTest_Deserialize()
  681. {
  682. var c = JsonConvert.DeserializeObject<FieldExtensionDataAttributeTestClass>("{'first':1,'second':2}");
  683. Assert.AreEqual(2, c.ExtensionData.Count);
  684. Assert.AreEqual(1, (long)c.ExtensionData["first"]);
  685. Assert.AreEqual(2, (long)c.ExtensionData["second"]);
  686. }
  687. [Test]
  688. public void MultipleExtensionDataAttributesTest()
  689. {
  690. var c = JsonConvert.DeserializeObject<MultipleExtensionDataAttributesTestClass>("{'first':[1],'second':[2]}");
  691. Assert.AreEqual(null, c.ExtensionData1);
  692. Assert.AreEqual(2, c.ExtensionData2.Count);
  693. Assert.AreEqual(1, (int)((JArray)c.ExtensionData2["first"])[0]);
  694. Assert.AreEqual(2, (int)((JArray)c.ExtensionData2["second"])[0]);
  695. }
  696. [Test]
  697. public void ExtensionDataAttributesInheritanceTest()
  698. {
  699. var c = JsonConvert.DeserializeObject<ExtensionDataAttributesInheritanceTestClass>("{'first':1,'second':2}");
  700. Assert.AreEqual(null, c.ExtensionData1);
  701. Assert.AreEqual(null, c.ExtensionData2);
  702. Assert.AreEqual(2, c.ExtensionData0.Count);
  703. Assert.AreEqual(1, (int)c.ExtensionData0["first"]);
  704. Assert.AreEqual(2, (int)c.ExtensionData0["second"]);
  705. }
  706. [Test]
  707. public void GenericCollectionInheritance()
  708. {
  709. string json;
  710. GenericClass<GenericItem<string>, string> foo1 = new GenericClass<GenericItem<string>, string>();
  711. foo1.Items.Add(new GenericItem<string> {Value = "Hello"});
  712. json = JsonConvert.SerializeObject(new {selectList = foo1});
  713. Assert.AreEqual(@"{""selectList"":[{""Value"":""Hello""}]}", json);
  714. GenericClass<NonGenericItem, string> foo2 = new GenericClass<NonGenericItem, string>();
  715. foo2.Items.Add(new NonGenericItem {Value = "Hello"});
  716. json = JsonConvert.SerializeObject(new { selectList = foo2 });
  717. Assert.AreEqual(@"{""selectList"":[{""Value"":""Hello""}]}", json);
  718. NonGenericClass foo3 = new NonGenericClass();
  719. foo3.Items.Add(new NonGenericItem {Value = "Hello"});
  720. json = JsonConvert.SerializeObject(new { selectList = foo3 });
  721. Assert.AreEqual(@"{""selectList"":[{""Value"":""Hello""}]}", json);
  722. }
  723. #if !NET20
  724. [DataContract]
  725. public class BaseDataContractWithHidden
  726. {
  727. [DataMember(Name = "virtualMember")]
  728. public virtual string VirtualMember { get; set; }
  729. [DataMember(Name = "nonVirtualMember")]
  730. public string NonVirtualMember { get; set; }
  731. public virtual object NewMember { get; set; }
  732. }
  733. public class ChildDataContractWithHidden : BaseDataContractWithHidden
  734. {
  735. [DataMember(Name = "NewMember")]
  736. public virtual new string NewMember { get; set; }
  737. public override string VirtualMember { get; set; }
  738. public string AddedMember { get; set; }
  739. }
  740. [Test]
  741. public void ChildDataContractTestWithHidden()
  742. {
  743. var cc = new ChildDataContractWithHidden
  744. {
  745. VirtualMember = "VirtualMember!",
  746. NonVirtualMember = "NonVirtualMember!",
  747. NewMember = "NewMember!"
  748. };
  749. string result = JsonConvert.SerializeObject(cc);
  750. Assert.AreEqual(@"{""NewMember"":""NewMember!"",""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  751. }
  752. // ignore hiding members compiler warning
  753. #pragma warning disable 108,114
  754. [DataContract]
  755. public class BaseWithContract
  756. {
  757. [DataMember(Name = "VirtualWithDataMemberBase")]
  758. public virtual string VirtualWithDataMember { get; set; }
  759. [DataMember]
  760. public virtual string Virtual { get; set; }
  761. [DataMember(Name = "WithDataMemberBase")]
  762. public string WithDataMember { get; set; }
  763. [DataMember]
  764. public string JustAProperty { get; set; }
  765. }
  766. [DataContract]
  767. public class BaseWithoutContract
  768. {
  769. [DataMember(Name = "VirtualWithDataMemberBase")]
  770. public virtual string VirtualWithDataMember { get; set; }
  771. [DataMember]
  772. public virtual string Virtual { get; set; }
  773. [DataMember(Name = "WithDataMemberBase")]
  774. public string WithDataMember { get; set; }
  775. [DataMember]
  776. public string JustAProperty { get; set; }
  777. }
  778. [DataContract]
  779. public class SubWithoutContractNewProperties : BaseWithContract
  780. {
  781. [DataMember(Name = "VirtualWithDataMemberSub")]
  782. public string VirtualWithDataMember { get; set; }
  783. public string Virtual { get; set; }
  784. [DataMember(Name = "WithDataMemberSub")]
  785. public string WithDataMember { get; set; }
  786. public string JustAProperty { get; set; }
  787. }
  788. [DataContract]
  789. public class SubWithoutContractVirtualProperties : BaseWithContract
  790. {
  791. public override string VirtualWithDataMember { get; set; }
  792. [DataMember(Name = "VirtualSub")]
  793. public override string Virtual { get; set; }
  794. }
  795. [DataContract]
  796. public class SubWithContractNewProperties : BaseWithContract
  797. {
  798. [DataMember(Name = "VirtualWithDataMemberSub")]
  799. public string VirtualWithDataMember { get; set; }
  800. [DataMember(Name = "Virtual2")]
  801. public string Virtual { get; set; }
  802. [DataMember(Name = "WithDataMemberSub")]
  803. public string WithDataMember { get; set; }
  804. [DataMember(Name = "JustAProperty2")]
  805. public string JustAProperty { get; set; }
  806. }
  807. [DataContract]
  808. public class SubWithContractVirtualProperties : BaseWithContract
  809. {
  810. [DataMember(Name = "VirtualWithDataMemberSub")]
  811. public virtual string VirtualWithDataMember { get; set; }
  812. }
  813. #pragma warning restore 108,114
  814. [Test]
  815. public void SubWithoutContractNewPropertiesTest()
  816. {
  817. BaseWithContract baseWith = new SubWithoutContractNewProperties
  818. {
  819. JustAProperty = "JustAProperty!",
  820. Virtual = "Virtual!",
  821. VirtualWithDataMember = "VirtualWithDataMember!",
  822. WithDataMember = "WithDataMember!"
  823. };
  824. baseWith.JustAProperty = "JustAProperty2!";
  825. baseWith.Virtual = "Virtual2!";
  826. baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
  827. baseWith.WithDataMember = "WithDataMember2!";
  828. string json = AssertSerializeDeserializeEqual(baseWith);
  829. Assert.AreEqual(@"{
  830. ""JustAProperty"": ""JustAProperty2!"",
  831. ""Virtual"": ""Virtual2!"",
  832. ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
  833. ""VirtualWithDataMemberSub"": ""VirtualWithDataMember!"",
  834. ""WithDataMemberBase"": ""WithDataMember2!"",
  835. ""WithDataMemberSub"": ""WithDataMember!""
  836. }", json);
  837. }
  838. [Test]
  839. public void SubWithoutContractVirtualPropertiesTest()
  840. {
  841. BaseWithContract baseWith = new SubWithoutContractVirtualProperties
  842. {
  843. JustAProperty = "JustAProperty!",
  844. Virtual = "Virtual!",
  845. VirtualWithDataMember = "VirtualWithDataMember!",
  846. WithDataMember = "WithDataMember!"
  847. };
  848. baseWith.JustAProperty = "JustAProperty2!";
  849. baseWith.Virtual = "Virtual2!";
  850. baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
  851. baseWith.WithDataMember = "WithDataMember2!";
  852. string json = JsonConvert.SerializeObject(baseWith, Formatting.Indented);
  853. Console.WriteLine(json);
  854. Assert.AreEqual(@"{
  855. ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
  856. ""VirtualSub"": ""Virtual2!"",
  857. ""WithDataMemberBase"": ""WithDataMember2!"",
  858. ""JustAProperty"": ""JustAProperty2!""
  859. }", json);
  860. }
  861. [Test]
  862. public void SubWithContractNewPropertiesTest()
  863. {
  864. BaseWithContract baseWith = new SubWithContractNewProperties
  865. {
  866. JustAProperty = "JustAProperty!",
  867. Virtual = "Virtual!",
  868. VirtualWithDataMember = "VirtualWithDataMember!",
  869. WithDataMember = "WithDataMember!"
  870. };
  871. baseWith.JustAProperty = "JustAProperty2!";
  872. baseWith.Virtual = "Virtual2!";
  873. baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
  874. baseWith.WithDataMember = "WithDataMember2!";
  875. string json = AssertSerializeDeserializeEqual(baseWith);
  876. Assert.AreEqual(@"{
  877. ""JustAProperty"": ""JustAProperty2!"",
  878. ""JustAProperty2"": ""JustAProperty!"",
  879. ""Virtual"": ""Virtual2!"",
  880. ""Virtual2"": ""Virtual!"",
  881. ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
  882. ""VirtualWithDataMemberSub"": ""VirtualWithDataMember!"",
  883. ""WithDataMemberBase"": ""WithDataMember2!"",
  884. ""WithDataMemberSub"": ""WithDataMember!""
  885. }", json);
  886. }
  887. [Test]
  888. public void SubWithContractVirtualPropertiesTest()
  889. {
  890. BaseWithContract baseWith = new SubWithContractVirtualProperties
  891. {
  892. JustAProperty = "JustAProperty!",
  893. Virtual = "Virtual!",
  894. VirtualWithDataMember = "VirtualWithDataMember!",
  895. WithDataMember = "WithDataMember!"
  896. };
  897. baseWith.JustAProperty = "JustAProperty2!";
  898. baseWith.Virtual = "Virtual2!";
  899. baseWith.VirtualWithDataMember = "VirtualWithDataMember2!";
  900. baseWith.WithDataMember = "WithDataMember2!";
  901. string json = AssertSerializeDeserializeEqual(baseWith);
  902. Assert.AreEqual(@"{
  903. ""JustAProperty"": ""JustAProperty2!"",
  904. ""Virtual"": ""Virtual2!"",
  905. ""VirtualWithDataMemberBase"": ""VirtualWithDataMember2!"",
  906. ""VirtualWithDataMemberSub"": ""VirtualWithDataMember!"",
  907. ""WithDataMemberBase"": ""WithDataMember2!""
  908. }", json);
  909. }
  910. private string AssertSerializeDeserializeEqual(object o)
  911. {
  912. MemoryStream ms = new MemoryStream();
  913. DataContractJsonSerializer s = new DataContractJsonSerializer(o.GetType());
  914. s.WriteObject(ms, o);
  915. var data = ms.ToArray();
  916. JObject dataContractJson = JObject.Parse(Encoding.UTF8.GetString(data, 0, data.Length));
  917. dataContractJson = new JObject(dataContractJson.Properties().OrderBy(p => p.Name));
  918. JObject jsonNetJson = JObject.Parse(JsonConvert.SerializeObject(o));
  919. jsonNetJson = new JObject(jsonNetJson.Properties().OrderBy(p => p.Name));
  920. Console.WriteLine("Results for " + o.GetType().Name);
  921. Console.WriteLine("DataContractJsonSerializer: " + dataContractJson);
  922. Console.WriteLine("JsonDotNetSerializer : " + jsonNetJson);
  923. Assert.AreEqual(dataContractJson.Count, jsonNetJson.Count);
  924. foreach (KeyValuePair<string, JToken> property in dataContractJson)
  925. {
  926. Assert.IsTrue(JToken.DeepEquals(jsonNetJson[property.Key], property.Value), "Property not equal: " + property.Key);
  927. }
  928. return jsonNetJson.ToString();
  929. }
  930. #endif
  931. [Test]
  932. public void PersonTypedObjectDeserialization()
  933. {
  934. Store store = new Store();
  935. string jsonText = JsonConvert.SerializeObject(store);
  936. Store deserializedStore = (Store)JsonConvert.DeserializeObject(jsonText, typeof(Store));
  937. Assert.AreEqual(store.Establised, deserializedStore.Establised);
  938. Assert.AreEqual(store.product.Count, deserializedStore.product.Count);
  939. Console.WriteLine(jsonText);
  940. }
  941. [Test]
  942. public void TypedObjectDeserialization()
  943. {
  944. Product product = new Product();
  945. product.Name = "Apple";
  946. product.ExpiryDate = new DateTime(2008, 12, 28);
  947. product.Price = 3.99M;
  948. product.Sizes = new string[] { "Small", "Medium", "Large" };
  949. string output = JsonConvert.SerializeObject(product);
  950. //{
  951. // "Name": "Apple",
  952. // "ExpiryDate": "\/Date(1230375600000+1300)\/",
  953. // "Price": 3.99,
  954. // "Sizes": [
  955. // "Small",
  956. // "Medium",
  957. // "Large"
  958. // ]
  959. //}
  960. Product deserializedProduct = (Product)JsonConvert.DeserializeObject(output, typeof(Product));
  961. Assert.AreEqual("Apple", deserializedProduct.Name);
  962. Assert.AreEqual(new DateTime(2008, 12, 28), deserializedProduct.ExpiryDate);
  963. Assert.AreEqual(3.99m, deserializedProduct.Price);
  964. Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
  965. Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
  966. Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
  967. }
  968. //[Test]
  969. //public void Advanced()
  970. //{
  971. // Product product = new Product();
  972. // product.ExpiryDate = new DateTime(2008, 12, 28);
  973. // JsonSerializer serializer = new JsonSerializer();
  974. // serializer.Converters.Add(new JavaScriptDateTimeConverter());
  975. // serializer.NullValueHandling = NullValueHandling.Ignore;
  976. // using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
  977. // using (JsonWriter writer = new JsonTextWriter(sw))
  978. // {
  979. // serializer.Serialize(writer, product);
  980. // // {"ExpiryDate":new Date(1230375600000),"Price":0}
  981. // }
  982. //}
  983. [Test]
  984. public void JsonConvertSerializer()
  985. {
  986. string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
  987. Product p = JsonConvert.DeserializeObject(value, typeof(Product)) as Product;
  988. Assert.AreEqual("Orange", p.Name);
  989. Assert.AreEqual(new DateTime(2010, 1, 24, 12, 0, 0), p.ExpiryDate);
  990. Assert.AreEqual(3.99m, p.Price);
  991. }
  992. [Test]
  993. public void DeserializeJavaScriptDate()
  994. {
  995. DateTime dateValue = new DateTime(2010, 3, 30);
  996. Dictionary<string, object> testDictionary = new Dictionary<string, object>();
  997. testDictionary["date"] = dateValue;
  998. string jsonText = JsonConvert.SerializeObject(testDictionary);
  999. #if !NET20
  1000. MemoryStream ms = new MemoryStream();
  1001. DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<string, object>));
  1002. serializer.WriteObject(ms, testDictionary);
  1003. byte[] data = ms.ToArray();
  1004. string output = Encoding.UTF8.GetString(data, 0, data.Length);
  1005. #endif
  1006. Dictionary<string, object> deserializedDictionary = (Dictionary<string, object>)JsonConvert.DeserializeObject(jsonText, typeof(Dictionary<string, object>));
  1007. DateTime deserializedDate = (DateTime)deserializedDictionary["date"];
  1008. Assert.AreEqual(dateValue, deserializedDate);
  1009. }
  1010. [Test]
  1011. public void TestMethodExecutorObject()
  1012. {
  1013. MethodExecutorObject executorObject = new MethodExecutorObject();
  1014. executorObject.serverClassName = "BanSubs";
  1015. executorObject.serverMethodParams = new object[] { "21321546", "101", "1236", "D:\\1.txt" };
  1016. executorObject.clientGetResultFunction = "ClientBanSubsCB";
  1017. string output = JsonConvert.SerializeObject(executorObject);
  1018. MethodExecutorObject executorObject2 = JsonConvert.DeserializeObject(output, typeof(MethodExecutorObject)) as MethodExecutorObject;
  1019. Assert.AreNotSame(executorObject, executorObject2);
  1020. Assert.AreEqual(executorObject2.serverClassName, "BanSubs");
  1021. Assert.AreEqual(executorObject2.serverMethodParams.Length, 4);
  1022. CustomAssert.Contains(executorObject2.serverMethodParams, "101");
  1023. Assert.AreEqual(executorObject2.clientGetResultFunction, "ClientBanSubsCB");
  1024. }
  1025. #if !SILVERLIGHT && !NETFX_CORE
  1026. [Test]
  1027. public void HashtableDeserialization()
  1028. {
  1029. string value = @"{""Name"":""Orange"", ""Price"":3.99, ""ExpiryDate"":""01/24/2010 12:00:00""}";
  1030. Hashtable p = JsonConvert.DeserializeObject(value, typeof(Hashtable)) as Hashtable;
  1031. Assert.AreEqual("Orange", p["Name"].ToString());
  1032. }
  1033. [Test]
  1034. public void TypedHashtableDeserialization()
  1035. {
  1036. string value = @"{""Name"":""Orange"", ""Hash"":{""ExpiryDate"":""01/24/2010 12:00:00"",""UntypedArray"":[""01/24/2010 12:00:00""]}}";
  1037. TypedSubHashtable p = JsonConvert.DeserializeObject(value, typeof(TypedSubHashtable)) as TypedSubHashtable;
  1038. Assert.AreEqual("01/24/2010 12:00:00", p.Hash["ExpiryDate"].ToString());
  1039. Assert.AreEqual(@"[
  1040. ""01/24/2010 12:00:00""
  1041. ]", p.Hash["UntypedArray"].ToString());
  1042. }
  1043. #endif
  1044. [Test]
  1045. public void SerializeDeserializeGetOnlyProperty()
  1046. {
  1047. string value = JsonConvert.SerializeObject(new GetOnlyPropertyClass());
  1048. GetOnlyPropertyClass c = JsonConvert.DeserializeObject<GetOnlyPropertyClass>(value);
  1049. Assert.AreEqual(c.Field, "Field");
  1050. Assert.AreEqual(c.GetOnlyProperty, "GetOnlyProperty");
  1051. }
  1052. [Test]
  1053. public void SerializeDeserializeSetOnlyProperty()
  1054. {
  1055. string value = JsonConvert.SerializeObject(new SetOnlyPropertyClass());
  1056. SetOnlyPropertyClass c = JsonConvert.DeserializeObject<SetOnlyPropertyClass>(value);
  1057. Assert.AreEqual(c.Field, "Field");
  1058. }
  1059. [Test]
  1060. public void JsonIgnoreAttributeTest()
  1061. {
  1062. string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeTestClass());
  1063. Assert.AreEqual(@"{""Field"":0,""Property"":21}", json);
  1064. JsonIgnoreAttributeTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeTestClass>(@"{""Field"":99,""Property"":-1,""IgnoredField"":-1,""IgnoredObject"":[1,2,3,4,5]}");
  1065. Assert.AreEqual(0, c.IgnoredField);
  1066. Assert.AreEqual(99, c.Field);
  1067. }
  1068. [Test]
  1069. public void GoogleSearchAPI()
  1070. {
  1071. string json = @"{
  1072. results:
  1073. [
  1074. {
  1075. GsearchResultClass:""GwebSearch"",
  1076. unescapedUrl : ""http://www.google.com/"",
  1077. url : ""http://www.google.com/"",
  1078. visibleUrl : ""www.google.com"",
  1079. cacheUrl :
  1080. ""http://www.google.com/search?q=cache:zhool8dxBV4J:www.google.com"",
  1081. title : ""Google"",
  1082. titleNoFormatting : ""Google"",
  1083. content : ""Enables users to search the Web, Usenet, and
  1084. images. Features include PageRank, caching and translation of
  1085. results, and an option to find similar pages.""
  1086. },
  1087. {
  1088. GsearchResultClass:""GwebSearch"",
  1089. unescapedUrl : ""http://news.google.com/"",
  1090. url : ""http://news.google.com/"",
  1091. visibleUrl : ""news.google.com"",
  1092. cacheUrl :
  1093. ""http://www.google.com/search?q=cache:Va_XShOz_twJ:news.google.com"",
  1094. title : ""Google News"",
  1095. titleNoFormatting : ""Google News"",
  1096. content : ""Aggregated headlines and a search engine of many of the world's news sources.""
  1097. },
  1098. {
  1099. GsearchResultClass:""GwebSearch"",
  1100. unescapedUrl : ""http://groups.google.com/"",
  1101. url : ""http://groups.google.com/"",
  1102. visibleUrl : ""groups.google.com"",
  1103. cacheUrl :
  1104. ""http://www.google.com/search?q=cache:x2uPD3hfkn0J:groups.google.com"",
  1105. title : ""Google Groups"",
  1106. titleNoFormatting : ""Google Groups"",
  1107. content : ""Enables users to search and browse the Usenet
  1108. archives which consist of over 700 million messages, and post new
  1109. comments.""
  1110. },
  1111. {
  1112. GsearchResultClass:""GwebSearch"",
  1113. unescapedUrl : ""http://maps.google.com/"",
  1114. url : ""http://maps.google.com/"",
  1115. visibleUrl : ""maps.google.com"",
  1116. cacheUrl :
  1117. ""http://www.google.com/search?q=cache:dkf5u2twBXIJ:maps.google.com"",
  1118. title : ""Google Maps"",
  1119. titleNoFormatting : ""Google Maps"",
  1120. content : ""Provides directions, interactive maps, and
  1121. satellite/aerial imagery of the United States. Can also search by
  1122. keyword such as type of business.""
  1123. }
  1124. ],
  1125. adResults:
  1126. [
  1127. {
  1128. GsearchResultClass:""GwebSearch.ad"",
  1129. title : ""Gartner Symposium/ITxpo"",
  1130. content1 : ""Meet brilliant Gartner IT analysts"",
  1131. content2 : ""20-23 May 2007- Barcelona, Spain"",
  1132. url :
  1133. ""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="",
  1134. impressionUrl :
  1135. ""http://www.google.com/uds/css/ad-indicator-on.gif?ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB"",
  1136. unescapedUrl :
  1137. ""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="",
  1138. visibleUrl : ""www.gartner.com""
  1139. }
  1140. ]
  1141. }
  1142. ";
  1143. object o = JsonConvert.DeserializeObject(json);
  1144. string s = string.Empty;
  1145. s += s;
  1146. }
  1147. [Test]
  1148. public void TorrentDeserializeTest()
  1149. {
  1150. string jsonText = @"{
  1151. """":"""",
  1152. ""label"": [
  1153. [""SomeName"",6]
  1154. ],
  1155. ""torrents"": [
  1156. [""192D99A5C943555CB7F00A852821CF6D6DB3008A"",201,""filename.avi"",178311826,1000,178311826,72815250,408,1603,7,121430,""NameOfLabelPrevioslyDefined"",3,6,0,8,128954,-1,0],
  1157. ],
  1158. ""torrentc"": ""1816000723""
  1159. }";
  1160. JObject o = (JObject)JsonConvert.DeserializeObject(jsonText);
  1161. Assert.AreEqual(4, o.Children().Count());
  1162. JToken torrentsArray = (JToken)o["torrents"];
  1163. JToken nestedTorrentsArray = (JToken)torrentsArray[0];
  1164. Assert.AreEqual(nestedTorrentsArray.Children().Count(), 19);
  1165. }
  1166. [Test]
  1167. public void JsonPropertyClassSerialize()
  1168. {
  1169. JsonPropertyClass test = new JsonPropertyClass();
  1170. test.Pie = "Delicious";
  1171. test.SweetCakesCount = int.MaxValue;
  1172. string jsonText = JsonConvert.SerializeObject(test);
  1173. Assert.AreEqual(@"{""pie"":""Delicious"",""pie1"":""PieChart!"",""sweet_cakes_count"":2147483647}", jsonText);
  1174. JsonPropertyClass test2 = JsonConvert.DeserializeObject<JsonPropertyClass>(jsonText);
  1175. Assert.AreEqual(test.Pie, test2.Pie);
  1176. Assert.AreEqual(test.SweetCakesCount, test2.SweetCakesCount);
  1177. }
  1178. [Test]
  1179. public void BadJsonPropertyClassSerialize()
  1180. {
  1181. ExceptionAssert.Throws<JsonSerializationException>(
  1182. @"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name.",
  1183. () =>
  1184. {
  1185. JsonConvert.SerializeObject(new BadJsonPropertyClass());
  1186. });
  1187. }
  1188. [Test]
  1189. public void InheritedListSerialize()
  1190. {
  1191. Article a1 = new Article("a1");
  1192. Article a2 = new Article("a2");
  1193. ArticleCollection articles1 = new ArticleCollection();
  1194. articles1.Add(a1);
  1195. articles1.Add(a2);
  1196. string jsonText = JsonConvert.SerializeObject(articles1);
  1197. ArticleCollection articles2 = JsonConvert.DeserializeObject<ArticleCollection>(jsonText);
  1198. Assert.AreEqual(articles1.Count, articles2.Count);
  1199. Assert.AreEqual(articles1[0].Name, articles2[0].Name);
  1200. }
  1201. [Test]
  1202. public void ReadOnlyCollectionSerialize()
  1203. {
  1204. ReadOnlyCollection<int> r1 = new ReadOnlyCollection<int>(new int[] { 0, 1, 2, 3, 4 });
  1205. string jsonText = JsonConvert.SerializeObject(r1);
  1206. Assert.AreEqual("[0,1,2,3,4]", jsonText);
  1207. ReadOnlyCollection<int> r2 = JsonConvert.DeserializeObject<ReadOnlyCollection<int>>(jsonText);
  1208. CollectionAssert.AreEqual(r1, r2);
  1209. }
  1210. #if !NET20
  1211. [Test]
  1212. public void Unicode()
  1213. {
  1214. string json = @"[""PRE\u003cPOST""]";
  1215. DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<string>));
  1216. List<string> dataContractResult = (List<string>)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
  1217. List<string> jsonNetResult = JsonConvert.DeserializeObject<List<string>>(json);
  1218. Assert.AreEqual(1, jsonNetResult.Count);
  1219. Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
  1220. }
  1221. [Test]
  1222. public void BackslashEqivilence()
  1223. {
  1224. string json = @"[""vvv\/vvv\tvvv\""vvv\bvvv\nvvv\rvvv\\vvv\fvvv""]";
  1225. #if !SILVERLIGHT && !NETFX_CORE
  1226. JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
  1227. List<string> javaScriptSerializerResult = javaScriptSerializer.Deserialize<List<string>>(json);
  1228. #endif
  1229. DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<string>));
  1230. List<string> dataContractResult = (List<string>)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
  1231. List<string> jsonNetResult = JsonConvert.DeserializeObject<List<string>>(json);
  1232. Assert.AreEqual(1, jsonNetResult.Count);
  1233. Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
  1234. #if !SILVERLIGHT && !NETFX_CORE
  1235. Assert.AreEqual(javaScriptSerializerResult[0], jsonNetResult[0]);
  1236. #endif
  1237. }
  1238. [Test]
  1239. public void InvalidBackslash()
  1240. {
  1241. string json = @"[""vvv\jvvv""]";
  1242. ExceptionAssert.Throws<JsonReaderException>(
  1243. @"Bad JSON escape sequence: \j. Path '', line 1, position 7.",
  1244. () =>
  1245. {
  1246. JsonConvert.DeserializeObject<List<string>>(json);
  1247. });
  1248. }
  1249. [Test]
  1250. public void DateTimeTest()
  1251. {
  1252. List<DateTime> testDates = new List<DateTime>
  1253. {
  1254. new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Local),
  1255. new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
  1256. new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc),
  1257. new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local),
  1258. new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
  1259. new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc),
  1260. };
  1261. MemoryStream ms = new MemoryStream();
  1262. DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<DateTime>));
  1263. s.WriteObject(ms, testDates);
  1264. ms.Seek(0, SeekOrigin.Begin);
  1265. StreamReader sr = new StreamReader(ms);
  1266. string expected = sr.ReadToEnd();
  1267. string result = JsonConvert.SerializeObject(testDates, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
  1268. Assert.AreEqual(expected, result);
  1269. }
  1270. [Test]
  1271. public void DateTimeOffsetIso()
  1272. {
  1273. List<DateTimeOffset> testDates = new List<DateTimeOffset>
  1274. {
  1275. new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
  1276. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
  1277. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
  1278. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
  1279. };
  1280. string result = JsonConvert.SerializeObject(testDates);
  1281. 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);
  1282. }
  1283. [Test]
  1284. public void DateTimeOffsetMsAjax()
  1285. {
  1286. List<DateTimeOffset> testDates = new List<DateTimeOffset>
  1287. {
  1288. new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
  1289. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
  1290. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
  1291. new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
  1292. };
  1293. string result = JsonConvert.SerializeObject(testDates, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
  1294. Assert.AreEqual(@"[""\/Date(-59011455539000+0000)\/"",""\/Date(946688461000+0000)\/"",""\/Date(946641661000+1300)\/"",""\/Date(946701061000-0330)\/""]", result);
  1295. }
  1296. #endif
  1297. [Test]
  1298. public void NonStringKeyDictionary()
  1299. {
  1300. Dictionary<int, int> values = new Dictionary<int, int>();
  1301. values.Add(-5, 6);
  1302. values.Add(int.MinValue, int.MaxValue);
  1303. string json = JsonConvert.SerializeObject(values);
  1304. Assert.AreEqual(@"{""-5"":6,""-2147483648"":2147483647}", json);
  1305. Dictionary<int, int> newValues = JsonConvert.DeserializeObject<Dictionary<int, int>>(json);
  1306. CollectionAssert.AreEqual(values, newValues);
  1307. }
  1308. [Test]
  1309. public void AnonymousObjectSerialization()
  1310. {
  1311. var anonymous =
  1312. new
  1313. {
  1314. StringValue = "I am a string",
  1315. IntValue = int.MaxValue,
  1316. NestedAnonymous = new { NestedValue = byte.MaxValue },
  1317. NestedArray = new[] { 1, 2 },
  1318. Product = new Product() { Name = "TestProduct" }
  1319. };
  1320. string json = JsonConvert.SerializeObject(anonymous);
  1321. 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);
  1322. anonymous = JsonConvert.DeserializeAnonymousType(json, anonymous);
  1323. Assert.AreEqual("I am a string", anonymous.StringValue);
  1324. Assert.AreEqual(int.MaxValue, anonymous.IntValue);
  1325. Assert.AreEqual(255, anonymous.NestedAnonymous.NestedValue);
  1326. Assert.AreEqual(2, anonymous.NestedArray.Length);
  1327. Assert.AreEqual(1, anonymous.NestedArray[0]);
  1328. Assert.AreEqual(2, anonymous.NestedArray[1]);
  1329. Assert.AreEqual("TestProduct", anonymous.Product.Name);
  1330. }
  1331. [Test]
  1332. public void AnonymousObjectSerializationWithSetting()
  1333. {
  1334. DateTime d = new DateTime(2000, 1, 1);
  1335. var anonymous =
  1336. new
  1337. {
  1338. DateValue = d
  1339. };
  1340. JsonSerializerSettings settings = new JsonSerializerSettings();
  1341. settings.Converters.Add(new IsoDateTimeConverter
  1342. {
  1343. DateTimeFormat = "yyyy"
  1344. });
  1345. string json = JsonConvert.SerializeObject(anonymous, settings);
  1346. Assert.AreEqual(@"{""DateValue"":""2000""}", json);
  1347. anonymous = JsonConvert.DeserializeAnonymousType(json, anonymous, settings);
  1348. Assert.AreEqual(d, anonymous.DateValue);
  1349. }
  1350. [Test]
  1351. public void CustomCollectionSerialization()
  1352. {
  1353. ProductCollection collection = new ProductCollection()
  1354. {
  1355. new Product() {Name = "Test1"},
  1356. new Product() {Name = "Test2"},
  1357. new Product() {Name = "Test3"}
  1358. };
  1359. JsonSerializer jsonSerializer = new JsonSerializer();
  1360. jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  1361. StringWriter sw = new StringWriter();
  1362. jsonSerializer.Serialize(sw, collection);
  1363. 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}]",
  1364. sw.GetStringBuilder().ToString());
  1365. ProductCollection collectionNew = (ProductCollection)jsonSerializer.Deserialize(new JsonTextReader(new StringReader(sw.GetStringBuilder().ToString())), typeof(ProductCollection));
  1366. CollectionAssert.AreEqual(collection, collectionNew);
  1367. }
  1368. [Test]
  1369. public void SerializeObject()
  1370. {
  1371. string json = JsonConvert.SerializeObject(new object());
  1372. Assert.AreEqual("{}", json);
  1373. }
  1374. [Test]
  1375. public void SerializeNull()
  1376. {
  1377. string json = JsonConvert.SerializeObject(null);
  1378. Assert.AreEqual("null", json);
  1379. }
  1380. [Test]
  1381. public void CanDeserializeIntArrayWhenNotFirstPropertyInJson()
  1382. {
  1383. string json = "{foo:'hello',bar:[1,2,3]}";
  1384. ClassWithArray wibble = JsonConvert.DeserializeObject<ClassWithArray>(json);
  1385. Assert.AreEqual("hello", wibble.Foo);
  1386. Assert.AreEqual(4, wibble.Bar.Count);
  1387. Assert.AreEqual(int.MaxValue, wibble.Bar[0]);
  1388. Assert.AreEqual(1, wibble.Bar[1]);
  1389. Assert.AreEqual(2, wibble.Bar[2]);
  1390. Assert.AreEqual(3, wibble.Bar[3]);
  1391. }
  1392. [Test]
  1393. public void CanDeserializeIntArray_WhenArrayIsFirstPropertyInJson()
  1394. {
  1395. string json = "{bar:[1,2,3], foo:'hello'}";
  1396. ClassWithArray wibble = JsonConvert.DeserializeObject<ClassWithArray>(json);
  1397. Assert.AreEqual("hello", wibble.Foo);
  1398. Assert.AreEqual(4, wibble.Bar.Count);
  1399. Assert.AreEqual(int.MaxValue, wibble.Bar[0]);
  1400. Assert.AreEqual(1, wibble.Bar[1]);
  1401. Assert.AreEqual(2, wibble.Bar[2]);
  1402. Assert.AreEqual(3, wibble.Bar[3]);
  1403. }
  1404. [Test]
  1405. public void ObjectCreationHandlingReplace()
  1406. {
  1407. string json = "{bar:[1,2,3], foo:'hello'}";
  1408. JsonSerializer s = new JsonSerializer();
  1409. s.ObjectCreationHandling = ObjectCreationHandling.Replace;
  1410. ClassWithArray wibble = (ClassWithArray)s.Deserialize(new StringReader(json), typeof(ClassWithArray));
  1411. Assert.AreEqual("hello", wibble.Foo);
  1412. Assert.AreEqual(1, wibble.Bar.Count);
  1413. }
  1414. [Test]
  1415. public void CanDeserializeSerializedJson()
  1416. {
  1417. ClassWithArray wibble = new ClassWithArray();
  1418. wibble.Foo = "hello";
  1419. wibble.Bar.Add(1);
  1420. wibble.Bar.Add(2);
  1421. wibble.Bar.Add(3);
  1422. string json = JsonConvert.SerializeObject(wibble);
  1423. ClassWithArray wibbleOut = JsonConvert.DeserializeObject<ClassWithArray>(json);
  1424. Assert.AreEqual("hello", wibbleOut.Foo);
  1425. Assert.AreEqual(5, wibbleOut.Bar.Count);
  1426. Assert.AreEqual(int.MaxValue, wibbleOut.Bar[0]);
  1427. Assert.AreEqual(int.MaxValue, wibbleOut.Bar[1]);
  1428. Assert.AreEqual(1, wibbleOut.Bar[2]);
  1429. Assert.AreEqual(2, wibbleOut.Bar[3]);
  1430. Assert.AreEqual(3, wibbleOut.Bar[4]);
  1431. }
  1432. [Test]
  1433. public void SerializeConverableObjects()
  1434. {
  1435. string json = JsonConvert.SerializeObject(new ConverableMembers(), Formatting.Indented);
  1436. string expected = null;
  1437. #if !(NETFX_CORE || PORTABLE)
  1438. expected = @"{
  1439. ""String"": ""string"",
  1440. ""Int32"": 2147483647,
  1441. ""UInt32"": 4294967295,
  1442. ""Byte"": 255,
  1443. ""SByte"": 127,
  1444. ""Short"": 32767,
  1445. ""UShort"": 65535,
  1446. ""Long"": 9223372036854775807,
  1447. ""ULong"": 9223372036854775807,
  1448. ""Double"": 1.7976931348623157E+308,
  1449. ""Float"": 3.40282347E+38,
  1450. ""DBNull"": null,
  1451. ""Bool"": true,
  1452. ""Char"": ""\u0000""
  1453. }";
  1454. #else
  1455. expected = @"{
  1456. ""String"": ""string"",
  1457. ""Int32"": 2147483647,
  1458. ""UInt32"": 4294967295,
  1459. ""Byte"": 255,
  1460. ""SByte"": 127,
  1461. ""Short"": 32767,
  1462. ""UShort"": 65535,
  1463. ""Long"": 9223372036854775807,
  1464. ""ULong"": 9223372036854775807,
  1465. ""Double"": 1.7976931348623157E+308,
  1466. ""Float"": 3.40282347E+38,
  1467. ""Bool"": true,
  1468. ""Char"": ""\u0000""
  1469. }";
  1470. #endif
  1471. Assert.AreEqual(expected, json);
  1472. ConverableMembers c = JsonConvert.DeserializeObject<ConverableMembers>(json);
  1473. Assert.AreEqual("string", c.String);
  1474. Assert.AreEqual(double.MaxValue, c.Double);
  1475. #if !(NETFX_CORE || PORTABLE || PORTABLE40)
  1476. Assert.AreEqual(DBNull.Value, c.DBNull);
  1477. #endif
  1478. }
  1479. [Test]
  1480. public void SerializeStack()
  1481. {
  1482. Stack<object> s = new Stack<object>();
  1483. s.Push(1);
  1484. s.Push(2);
  1485. s.Push(3);
  1486. string json = JsonConvert.SerializeObject(s);
  1487. Assert.AreEqual("[3,2,1]", json);
  1488. }
  1489. [Test]
  1490. public void GuidTest()
  1491. {
  1492. Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
  1493. string json = JsonConvert.SerializeObject(new ClassWithGuid { GuidField = guid });
  1494. Assert.AreEqual(@"{""GuidField"":""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""}", json);
  1495. ClassWithGuid c = JsonConvert.DeserializeObject<ClassWithGuid>(json);
  1496. Assert.AreEqual(guid, c.GuidField);
  1497. }
  1498. [Test]
  1499. public void EnumTest()
  1500. {
  1501. string json = JsonConvert.SerializeObject(StringComparison.CurrentCultureIgnoreCase);
  1502. Assert.AreEqual(@"1", json);
  1503. StringComparison s = JsonConvert.DeserializeObject<StringComparison>(json);
  1504. Assert.AreEqual(StringComparison.CurrentCultureIgnoreCase, s);
  1505. }
  1506. public class ClassWithTimeSpan
  1507. {
  1508. public TimeSpan TimeSpanField;
  1509. }
  1510. [Test]
  1511. public void TimeSpanTest()
  1512. {
  1513. TimeSpan ts = new TimeSpan(00, 23, 59, 1);
  1514. string json = JsonConvert.SerializeObject(new ClassWithTimeSpan { TimeSpanField = ts }, Formatting.Indented);
  1515. Assert.AreEqual(@"{
  1516. ""TimeSpanField"": ""23:59:01""
  1517. }", json);
  1518. ClassWithTimeSpan c = JsonConvert.DeserializeObject<ClassWithTimeSpan>(json);
  1519. Assert.AreEqual(ts, c.TimeSpanField);
  1520. }
  1521. [Test]
  1522. public void JsonIgnoreAttributeOnClassTest()
  1523. {
  1524. string json = JsonConvert.SerializeObject(new JsonIgnoreAttributeOnClassTestClass());
  1525. Assert.AreEqual(@"{""TheField"":0,""Property"":21}", json);
  1526. JsonIgnoreAttributeOnClassTestClass c = JsonConvert.DeserializeObject<JsonIgnoreAttributeOnClassTestClass>(@"{""TheField"":99,""Property"":-1,""IgnoredField"":-1}");
  1527. Assert.AreEqual(0, c.IgnoredField);
  1528. Assert.AreEqual(99, c.Field);
  1529. }
  1530. #if !SILVERLIGHT && !NETFX_CORE
  1531. [Test]
  1532. public void SerializeArrayAsArrayList()
  1533. {
  1534. string jsonText = @"[3, ""somestring"",[1,2,3],{}]";
  1535. ArrayList o = JsonConvert.DeserializeObject<ArrayList>(jsonText);
  1536. Assert.AreEqual(4, o.Count);
  1537. Assert.AreEqual(3, ((JArray)o[2]).Count);
  1538. Assert.AreEqual(0, ((JObject)o[3]).Count);
  1539. }
  1540. #endif
  1541. [Test]
  1542. public void SerializeMemberGenericList()
  1543. {
  1544. Name name = new Name("The Idiot in Next To Me");
  1545. PhoneNumber p1 = new PhoneNumber("555-1212");
  1546. PhoneNumber p2 = new PhoneNumber("444-1212");
  1547. name.pNumbers.Add(p1);
  1548. name.pNumbers.Add(p2);
  1549. string json = JsonConvert.SerializeObject(name, Formatting.Indented);
  1550. Assert.AreEqual(@"{
  1551. ""personsName"": ""The Idiot in Next To Me"",
  1552. ""pNumbers"": [
  1553. {
  1554. ""phoneNumber"": ""555-1212""
  1555. },
  1556. {
  1557. ""phoneNumber"": ""444-1212""
  1558. }
  1559. ]
  1560. }", json);
  1561. Name newName = JsonConvert.DeserializeObject<Name>(json);
  1562. Assert.AreEqual("The Idiot in Next To Me", newName.personsName);
  1563. // not passed in as part of the constructor but assigned to pNumbers property
  1564. Assert.AreEqual(2, newName.pNumbers.Count);
  1565. Assert.AreEqual("555-1212", newName.pNumbers[0].phoneNumber);
  1566. Assert.AreEqual("444-1212", newName.pNumbers[1].phoneNumber);
  1567. }
  1568. [Test]
  1569. public void ConstructorCaseSensitivity()
  1570. {
  1571. ConstructorCaseSensitivityClass c = new ConstructorCaseSensitivityClass("param1", "Param1", "Param2");
  1572. string json = JsonConvert.SerializeObject(c);
  1573. ConstructorCaseSensitivityClass deserialized = JsonConvert.DeserializeObject<ConstructorCaseSensitivityClass>(json);
  1574. Assert.AreEqual("param1", deserialized.param1);
  1575. Assert.AreEqual("Param1", deserialized.Param1);
  1576. Assert.AreEqual("Param2", deserialized.Param2);
  1577. }
  1578. [Test]
  1579. public void SerializerShouldUseClassConverter()
  1580. {
  1581. ConverterPrecedenceClass c1 = new ConverterPrecedenceClass("!Test!");
  1582. string json = JsonConvert.SerializeObject(c1);
  1583. Assert.AreEqual(@"[""Class"",""!Test!""]", json);
  1584. ConverterPrecedenceClass c2 = JsonConvert.DeserializeObject<ConverterPrecedenceClass>(json);
  1585. Assert.AreEqual("!Test!", c2.TestValue);
  1586. }
  1587. [Test]
  1588. public void SerializerShouldUseClassConverterOverArgumentConverter()
  1589. {
  1590. ConverterPrecedenceClass c1 = new ConverterPrecedenceClass("!Test!");
  1591. string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
  1592. Assert.AreEqual(@"[""Class"",""!Test!""]", json);
  1593. ConverterPrecedenceClass c2 = JsonConvert.DeserializeObject<ConverterPrecedenceClass>(json, new ArgumentConverterPrecedenceClassConverter());
  1594. Assert.AreEqual("!Test!", c2.TestValue);
  1595. }
  1596. [Test]
  1597. public void SerializerShouldUseMemberConverter_IsoDate()
  1598. {
  1599. DateTime testDate = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  1600. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  1601. string json = JsonConvert.SerializeObject(m1);
  1602. Assert.AreEqual(@"{""DefaultConverter"":""1970-01-01T00:00:00Z"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  1603. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
  1604. Assert.AreEqual(testDate, m2.DefaultConverter);
  1605. Assert.AreEqual(testDate, m2.MemberConverter);
  1606. }
  1607. [Test]
  1608. public void SerializerShouldUseMemberConverter_MsDate()
  1609. {
  1610. DateTime testDate = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  1611. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  1612. string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
  1613. {
  1614. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  1615. });
  1616. Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  1617. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
  1618. Assert.AreEqual(testDate, m2.DefaultConverter);
  1619. Assert.AreEqual(testDate, m2.MemberConverter);
  1620. }
  1621. [Test]
  1622. public void SerializerShouldUseMemberConverter_MsDate_DateParseNone()
  1623. {
  1624. DateTime testDate = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  1625. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  1626. string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
  1627. {
  1628. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
  1629. });
  1630. Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  1631. ExceptionAssert.Throws<JsonReaderException>(
  1632. "Could not convert string to DateTime: /Date(0)/. Path 'DefaultConverter', line 1, position 33.",
  1633. () =>
  1634. {
  1635. JsonConvert.DeserializeObject<MemberConverterClass>(json, new JsonSerializerSettings
  1636. {
  1637. DateParseHandling = DateParseHandling.None
  1638. });
  1639. });
  1640. }
  1641. [Test]
  1642. public void SerializerShouldUseMemberConverter_IsoDate_DateParseNone()
  1643. {
  1644. DateTime testDate = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  1645. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  1646. string json = JsonConvert.SerializeObject(m1, new JsonSerializerSettings
  1647. {
  1648. DateFormatHandling = DateFormatHandling.IsoDateFormat,
  1649. });
  1650. Assert.AreEqual(@"{""DefaultConverter"":""1970-01-01T00:00:00Z"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  1651. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json);
  1652. Assert.AreEqual(testDate, m2.DefaultConverter);
  1653. Assert.AreEqual(testDate, m2.MemberConverter);
  1654. }
  1655. [Test]
  1656. public void SerializerShouldUseMemberConverterOverArgumentConverter()
  1657. {
  1658. DateTime testDate = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
  1659. MemberConverterClass m1 = new MemberConverterClass { DefaultConverter = testDate, MemberConverter = testDate };
  1660. string json = JsonConvert.SerializeObject(m1, new JavaScriptDateTimeConverter());
  1661. Assert.AreEqual(@"{""DefaultConverter"":new Date(0),""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
  1662. MemberConverterClass m2 = JsonConvert.DeserializeObject<MemberConverterClass>(json, new JavaScriptDateTimeConverter());
  1663. Assert.AreEqual(testDate, m2.DefaultConverter);
  1664. Assert.AreEqual(testDate, m2.MemberConverter);
  1665. }
  1666. [Test]
  1667. public void ConverterAttributeExample()
  1668. {
  1669. DateTime date = Convert.ToDateTime("1970-01-01T00:00:00Z").ToUniversalTime();
  1670. MemberConverterClass c = new MemberConverterClass
  1671. {
  1672. DefaultConverter = date,
  1673. MemberConverter = date
  1674. };
  1675. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  1676. Console.WriteLine(json);
  1677. //{
  1678. // "DefaultConverter": "\/Date(0)\/",
  1679. // "MemberConverter": "1970-01-01T00:00:00Z"
  1680. //}
  1681. }
  1682. [Test]
  1683. public void SerializerShouldUseMemberConverterOverClassAndArgumentConverter()
  1684. {
  1685. ClassAndMemberConverterClass c1 = new ClassAndMemberConverterClass();
  1686. c1.DefaultConverter = new ConverterPrecedenceClass("DefaultConverterValue");
  1687. c1.MemberConverter = new ConverterPrecedenceClass("MemberConverterValue");
  1688. string json = JsonConvert.SerializeObject(c1, new ArgumentConverterPrecedenceClassConverter());
  1689. Assert.AreEqual(@"{""DefaultConverter"":[""Class"",""DefaultConverterValue""],""MemberConverter"":[""Member"",""MemberConverterValue""]}", json);
  1690. ClassAndMemberConverterClass c2 = JsonConvert.DeserializeObject<ClassAndMemberConverterClass>(json, new ArgumentConverterPrecedenceClassConverter());
  1691. Assert.AreEqual("DefaultConverterValue", c2.DefaultConverter.TestValue);
  1692. Assert.AreEqual("MemberConverterValue", c2.MemberConverter.TestValue);
  1693. }
  1694. [Test]
  1695. public void IncompatibleJsonAttributeShouldThrow()
  1696. {
  1697. ExceptionAssert.Throws<JsonSerializationException>(
  1698. "Unexpected value when converting date. Expected DateTime or DateTimeOffset, got Newtonsoft.Json.Tests.TestObjects.IncompatibleJsonAttributeClass.",
  1699. () =>
  1700. {
  1701. IncompatibleJsonAttributeClass c = new IncompatibleJsonAttributeClass();
  1702. JsonConvert.SerializeObject(c);
  1703. });
  1704. }
  1705. [Test]
  1706. public void GenericAbstractProperty()
  1707. {
  1708. string json = JsonConvert.SerializeObject(new GenericImpl());
  1709. Assert.AreEqual(@"{""Id"":0}", json);
  1710. }
  1711. [Test]
  1712. public void DeserializeNullable()
  1713. {
  1714. string json;
  1715. json = JsonConvert.SerializeObject((int?)null);
  1716. Assert.AreEqual("null", json);
  1717. json = JsonConvert.SerializeObject((int?)1);
  1718. Assert.AreEqual("1", json);
  1719. }
  1720. [Test]
  1721. public void SerializeJsonRaw()
  1722. {
  1723. PersonRaw personRaw = new PersonRaw
  1724. {
  1725. FirstName = "FirstNameValue",
  1726. RawContent = new JRaw("[1,2,3,4,5]"),
  1727. LastName = "LastNameValue"
  1728. };
  1729. string json;
  1730. json = JsonConvert.SerializeObject(personRaw);
  1731. Assert.AreEqual(@"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}", json);
  1732. }
  1733. [Test]
  1734. public void DeserializeJsonRaw()
  1735. {
  1736. string json = @"{""first_name"":""FirstNameValue"",""RawContent"":[1,2,3,4,5],""last_name"":""LastNameValue""}";
  1737. PersonRaw personRaw = JsonConvert.DeserializeObject<PersonRaw>(json);
  1738. Assert.AreEqual("FirstNameValue", personRaw.FirstName);
  1739. Assert.AreEqual("[1,2,3,4,5]", personRaw.RawContent.ToString());
  1740. Assert.AreEqual("LastNameValue", personRaw.LastName);
  1741. }
  1742. [Test]
  1743. public void DeserializeNullableMember()
  1744. {
  1745. UserNullable userNullablle = new UserNullable
  1746. {
  1747. Id = new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"),
  1748. FName = "FirstValue",
  1749. LName = "LastValue",
  1750. RoleId = 5,
  1751. NullableRoleId = 6,
  1752. NullRoleId = null,
  1753. Active = true
  1754. };
  1755. string json = JsonConvert.SerializeObject(userNullablle);
  1756. Assert.AreEqual(@"{""Id"":""ad6205e8-0df4-465d-aea6-8ba18e93a7e7"",""FName"":""FirstValue"",""LName"":""LastValue"",""RoleId"":5,""NullableRoleId"":6,""NullRoleId"":null,""Active"":true}", json);
  1757. UserNullable userNullablleDeserialized = JsonConvert.DeserializeObject<UserNullable>(json);
  1758. Assert.AreEqual(new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"), userNullablleDeserialized.Id);
  1759. Assert.AreEqual("FirstValue", userNullablleDeserialized.FName);
  1760. Assert.AreEqual("LastValue", userNullablleDeserialized.LName);
  1761. Assert.AreEqual(5, userNullablleDeserialized.RoleId);
  1762. Assert.AreEqual(6, userNullablleDeserialized.NullableRoleId);
  1763. Assert.AreEqual(null, userNullablleDeserialized.NullRoleId);
  1764. Assert.AreEqual(true, userNullablleDeserialized.Active);
  1765. }
  1766. [Test]
  1767. public void DeserializeInt64ToNullableDouble()
  1768. {
  1769. string json = @"{""Height"":1}";
  1770. DoubleClass c = JsonConvert.DeserializeObject<DoubleClass>(json);
  1771. Assert.AreEqual(1, c.Height);
  1772. }
  1773. [Test]
  1774. public void SerializeTypeProperty()
  1775. {
  1776. string boolRef = typeof(bool).AssemblyQualifiedName;
  1777. TypeClass typeClass = new TypeClass { TypeProperty = typeof(bool) };
  1778. string json = JsonConvert.SerializeObject(typeClass);
  1779. Assert.AreEqual(@"{""TypeProperty"":""" + boolRef + @"""}", json);
  1780. TypeClass typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
  1781. Assert.AreEqual(typeof(bool), typeClass2.TypeProperty);
  1782. string jsonSerializerTestRef = typeof(JsonSerializerTest).AssemblyQualifiedName;
  1783. typeClass = new TypeClass { TypeProperty = typeof(JsonSerializerTest) };
  1784. json = JsonConvert.SerializeObject(typeClass);
  1785. Assert.AreEqual(@"{""TypeProperty"":""" + jsonSerializerTestRef + @"""}", json);
  1786. typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
  1787. Assert.AreEqual(typeof(JsonSerializerTest), typeClass2.TypeProperty);
  1788. }
  1789. [Test]
  1790. public void RequiredMembersClass()
  1791. {
  1792. RequiredMembersClass c = new RequiredMembersClass()
  1793. {
  1794. BirthDate = new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc),
  1795. FirstName = "Bob",
  1796. LastName = "Smith",
  1797. MiddleName = "Cosmo"
  1798. };
  1799. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  1800. Assert.AreEqual(@"{
  1801. ""FirstName"": ""Bob"",
  1802. ""MiddleName"": ""Cosmo"",
  1803. ""LastName"": ""Smith"",
  1804. ""BirthDate"": ""2000-12-20T10:55:55Z""
  1805. }", json);
  1806. RequiredMembersClass c2 = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  1807. Assert.AreEqual("Bob", c2.FirstName);
  1808. Assert.AreEqual(new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc), c2.BirthDate);
  1809. }
  1810. [Test]
  1811. public void DeserializeRequiredMembersClassWithNullValues()
  1812. {
  1813. string json = @"{
  1814. ""FirstName"": ""I can't be null bro!"",
  1815. ""MiddleName"": null,
  1816. ""LastName"": null,
  1817. ""BirthDate"": ""\/Date(977309755000)\/""
  1818. }";
  1819. RequiredMembersClass c = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  1820. Assert.AreEqual("I can't be null bro!", c.FirstName);
  1821. Assert.AreEqual(null, c.MiddleName);
  1822. Assert.AreEqual(null, c.LastName);
  1823. }
  1824. [Test]
  1825. public void DeserializeRequiredMembersClassNullRequiredValueProperty()
  1826. {
  1827. ExceptionAssert.Throws<JsonSerializationException>(
  1828. "Required property 'FirstName' expects a value but got null. Path '', line 6, position 2.",
  1829. () =>
  1830. {
  1831. string json = @"{
  1832. ""FirstName"": null,
  1833. ""MiddleName"": null,
  1834. ""LastName"": null,
  1835. ""BirthDate"": ""\/Date(977309755000)\/""
  1836. }";
  1837. JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  1838. });
  1839. }
  1840. [Test]
  1841. public void SerializeRequiredMembersClassNullRequiredValueProperty()
  1842. {
  1843. ExceptionAssert.Throws<JsonSerializationException>(
  1844. "Cannot write a null value for property 'FirstName'. Property requires a value. Path ''.",
  1845. () =>
  1846. {
  1847. RequiredMembersClass requiredMembersClass = new RequiredMembersClass
  1848. {
  1849. FirstName = null,
  1850. BirthDate = new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc),
  1851. LastName = null,
  1852. MiddleName = null
  1853. };
  1854. string json = JsonConvert.SerializeObject(requiredMembersClass);
  1855. Console.WriteLine(json);
  1856. });
  1857. }
  1858. [Test]
  1859. public void RequiredMembersClassMissingRequiredProperty()
  1860. {
  1861. ExceptionAssert.Throws<JsonSerializationException>(
  1862. "Required property 'LastName' not found in JSON. Path '', line 3, position 2.",
  1863. () =>
  1864. {
  1865. string json = @"{
  1866. ""FirstName"": ""Bob""
  1867. }";
  1868. JsonConvert.DeserializeObject<RequiredMembersClass>(json);
  1869. });
  1870. }
  1871. [Test]
  1872. public void SerializeJaggedArray()
  1873. {
  1874. JaggedArray aa = new JaggedArray();
  1875. aa.Before = "Before!";
  1876. aa.After = "After!";
  1877. aa.Coordinates = new[] { new[] { 1, 1 }, new[] { 1, 2 }, new[] { 2, 1 }, new[] { 2, 2 } };
  1878. string json = JsonConvert.SerializeObject(aa);
  1879. Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}", json);
  1880. }
  1881. [Test]
  1882. public void DeserializeJaggedArray()
  1883. {
  1884. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}";
  1885. JaggedArray aa = JsonConvert.DeserializeObject<JaggedArray>(json);
  1886. Assert.AreEqual("Before!", aa.Before);
  1887. Assert.AreEqual("After!", aa.After);
  1888. Assert.AreEqual(4, aa.Coordinates.Length);
  1889. Assert.AreEqual(2, aa.Coordinates[0].Length);
  1890. Assert.AreEqual(1, aa.Coordinates[0][0]);
  1891. Assert.AreEqual(2, aa.Coordinates[1][1]);
  1892. string after = JsonConvert.SerializeObject(aa);
  1893. Assert.AreEqual(json, after);
  1894. }
  1895. [Test]
  1896. public void DeserializeGoogleGeoCode()
  1897. {
  1898. string json = @"{
  1899. ""name"": ""1600 Amphitheatre Parkway, Mountain View, CA, USA"",
  1900. ""Status"": {
  1901. ""code"": 200,
  1902. ""request"": ""geocode""
  1903. },
  1904. ""Placemark"": [
  1905. {
  1906. ""address"": ""1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"",
  1907. ""AddressDetails"": {
  1908. ""Country"": {
  1909. ""CountryNameCode"": ""US"",
  1910. ""AdministrativeArea"": {
  1911. ""AdministrativeAreaName"": ""CA"",
  1912. ""SubAdministrativeArea"": {
  1913. ""SubAdministrativeAreaName"": ""Santa Clara"",
  1914. ""Locality"": {
  1915. ""LocalityName"": ""Mountain View"",
  1916. ""Thoroughfare"": {
  1917. ""ThoroughfareName"": ""1600 Amphitheatre Pkwy""
  1918. },
  1919. ""PostalCode"": {
  1920. ""PostalCodeNumber"": ""94043""
  1921. }
  1922. }
  1923. }
  1924. }
  1925. },
  1926. ""Accuracy"": 8
  1927. },
  1928. ""Point"": {
  1929. ""coordinates"": [-122.083739, 37.423021, 0]
  1930. }
  1931. }
  1932. ]
  1933. }";
  1934. GoogleMapGeocoderStructure jsonGoogleMapGeocoder = JsonConvert.DeserializeObject<GoogleMapGeocoderStructure>(json);
  1935. }
  1936. [Test]
  1937. public void DeserializeInterfaceProperty()
  1938. {
  1939. InterfacePropertyTestClass testClass = new InterfacePropertyTestClass();
  1940. testClass.co = new Co();
  1941. String strFromTest = JsonConvert.SerializeObject(testClass);
  1942. ExceptionAssert.Throws<JsonSerializationException>(
  1943. @"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.",
  1944. () =>
  1945. {
  1946. InterfacePropertyTestClass testFromDe = (InterfacePropertyTestClass)JsonConvert.DeserializeObject(strFromTest, typeof(InterfacePropertyTestClass));
  1947. });
  1948. }
  1949. private Person GetPerson()
  1950. {
  1951. Person person = new Person
  1952. {
  1953. Name = "Mike Manager",
  1954. BirthDate = new DateTime(1983, 8, 3, 0, 0, 0, DateTimeKind.Utc),
  1955. Department = "IT",
  1956. LastModified = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc)
  1957. };
  1958. return person;
  1959. }
  1960. [Test]
  1961. public void WriteJsonDates()
  1962. {
  1963. LogEntry entry = new LogEntry
  1964. {
  1965. LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
  1966. Details = "Application started."
  1967. };
  1968. string defaultJson = JsonConvert.SerializeObject(entry);
  1969. // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}
  1970. string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
  1971. // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00.0000000Z"}
  1972. string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
  1973. // {"Details":"Application started.","LogDate":new Date(1234656000000)}
  1974. Console.WriteLine(defaultJson);
  1975. Console.WriteLine(isoJson);
  1976. Console.WriteLine(javascriptJson);
  1977. }
  1978. public void GenericListAndDictionaryInterfaceProperties()
  1979. {
  1980. GenericListAndDictionaryInterfaceProperties o = new GenericListAndDictionaryInterfaceProperties();
  1981. o.IDictionaryProperty = new Dictionary<string, int>
  1982. {
  1983. {"one", 1},
  1984. {"two", 2},
  1985. {"three", 3}
  1986. };
  1987. o.IListProperty = new List<int>
  1988. {
  1989. 1, 2, 3
  1990. };
  1991. o.IEnumerableProperty = new List<int>
  1992. {
  1993. 4, 5, 6
  1994. };
  1995. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  1996. Assert.AreEqual(@"{
  1997. ""IEnumerableProperty"": [
  1998. 4,
  1999. 5,
  2000. 6
  2001. ],
  2002. ""IListProperty"": [
  2003. 1,
  2004. 2,
  2005. 3
  2006. ],
  2007. ""IDictionaryProperty"": {
  2008. ""one"": 1,
  2009. ""two"": 2,
  2010. ""three"": 3
  2011. }
  2012. }", json);
  2013. GenericListAndDictionaryInterfaceProperties deserializedObject = JsonConvert.DeserializeObject<GenericListAndDictionaryInterfaceProperties>(json);
  2014. Assert.IsNotNull(deserializedObject);
  2015. CollectionAssert.AreEqual(o.IListProperty.ToArray(), deserializedObject.IListProperty.ToArray());
  2016. CollectionAssert.AreEqual(o.IEnumerableProperty.ToArray(), deserializedObject.IEnumerableProperty.ToArray());
  2017. CollectionAssert.AreEqual(o.IDictionaryProperty.ToArray(), deserializedObject.IDictionaryProperty.ToArray());
  2018. }
  2019. [Test]
  2020. public void DeserializeBestMatchPropertyCase()
  2021. {
  2022. string json = @"{
  2023. ""firstName"": ""firstName"",
  2024. ""FirstName"": ""FirstName"",
  2025. ""LastName"": ""LastName"",
  2026. ""lastName"": ""lastName"",
  2027. }";
  2028. PropertyCase o = JsonConvert.DeserializeObject<PropertyCase>(json);
  2029. Assert.IsNotNull(o);
  2030. Assert.AreEqual("firstName", o.firstName);
  2031. Assert.AreEqual("FirstName", o.FirstName);
  2032. Assert.AreEqual("LastName", o.LastName);
  2033. Assert.AreEqual("lastName", o.lastName);
  2034. }
  2035. public sealed class ConstructorAndDefaultValueAttributeTestClass
  2036. {
  2037. public ConstructorAndDefaultValueAttributeTestClass(string testProperty1)
  2038. {
  2039. this.TestProperty1 = testProperty1;
  2040. }
  2041. public string TestProperty1 { get; set; }
  2042. [DefaultValue(21)]
  2043. public int TestProperty2 { get; set; }
  2044. }
  2045. [Test]
  2046. public void PopulateDefaultValueWhenUsingConstructor()
  2047. {
  2048. string json = "{ 'testProperty1': 'value' }";
  2049. ConstructorAndDefaultValueAttributeTestClass c = JsonConvert.DeserializeObject<ConstructorAndDefaultValueAttributeTestClass>(json, new JsonSerializerSettings
  2050. {
  2051. DefaultValueHandling = DefaultValueHandling.Populate
  2052. });
  2053. Assert.AreEqual("value", c.TestProperty1);
  2054. Assert.AreEqual(21, c.TestProperty2);
  2055. c = JsonConvert.DeserializeObject<ConstructorAndDefaultValueAttributeTestClass>(json, new JsonSerializerSettings
  2056. {
  2057. DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate
  2058. });
  2059. Assert.AreEqual("value", c.TestProperty1);
  2060. Assert.AreEqual(21, c.TestProperty2);
  2061. }
  2062. public sealed class ConstructorAndRequiredTestClass
  2063. {
  2064. public ConstructorAndRequiredTestClass(string testProperty1)
  2065. {
  2066. this.TestProperty1 = testProperty1;
  2067. }
  2068. public string TestProperty1 { get; set; }
  2069. [JsonProperty(Required = Required.AllowNull)]
  2070. public int TestProperty2 { get; set; }
  2071. }
  2072. [Test]
  2073. public void RequiredWhenUsingConstructor()
  2074. {
  2075. string json = "{ 'testProperty1': 'value' }";
  2076. ExceptionAssert.Throws<JsonSerializationException>("Required property 'TestProperty2' not found in JSON. Path '', line 1, position 28.",
  2077. () => JsonConvert.DeserializeObject<ConstructorAndRequiredTestClass>(json));
  2078. }
  2079. [Test]
  2080. public void DeserializePropertiesOnToNonDefaultConstructor()
  2081. {
  2082. SubKlass i = new SubKlass("my subprop");
  2083. i.SuperProp = "overrided superprop";
  2084. string json = JsonConvert.SerializeObject(i);
  2085. Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", json);
  2086. SubKlass ii = JsonConvert.DeserializeObject<SubKlass>(json);
  2087. string newJson = JsonConvert.SerializeObject(ii);
  2088. Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", newJson);
  2089. }
  2090. [Test]
  2091. public void DeserializePropertiesOnToNonDefaultConstructorWithReferenceTracking()
  2092. {
  2093. SubKlass i = new SubKlass("my subprop");
  2094. i.SuperProp = "overrided superprop";
  2095. string json = JsonConvert.SerializeObject(i, new JsonSerializerSettings
  2096. {
  2097. PreserveReferencesHandling = PreserveReferencesHandling.Objects
  2098. });
  2099. Assert.AreEqual(@"{""$id"":""1"",""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", json);
  2100. SubKlass ii = JsonConvert.DeserializeObject<SubKlass>(json, new JsonSerializerSettings
  2101. {
  2102. PreserveReferencesHandling = PreserveReferencesHandling.Objects
  2103. });
  2104. string newJson = JsonConvert.SerializeObject(ii, new JsonSerializerSettings
  2105. {
  2106. PreserveReferencesHandling = PreserveReferencesHandling.Objects
  2107. });
  2108. Assert.AreEqual(@"{""$id"":""1"",""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", newJson);
  2109. }
  2110. [Test]
  2111. public void SerializeJsonPropertyWithHandlingValues()
  2112. {
  2113. JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
  2114. o.DefaultValueHandlingIgnoreProperty = "Default!";
  2115. o.DefaultValueHandlingIncludeProperty = "Default!";
  2116. o.DefaultValueHandlingPopulateProperty = "Default!";
  2117. o.DefaultValueHandlingIgnoreAndPopulateProperty = "Default!";
  2118. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  2119. Assert.AreEqual(@"{
  2120. ""DefaultValueHandlingIncludeProperty"": ""Default!"",
  2121. ""DefaultValueHandlingPopulateProperty"": ""Default!"",
  2122. ""NullValueHandlingIncludeProperty"": null,
  2123. ""ReferenceLoopHandlingErrorProperty"": null,
  2124. ""ReferenceLoopHandlingIgnoreProperty"": null,
  2125. ""ReferenceLoopHandlingSerializeProperty"": null
  2126. }", json);
  2127. json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
  2128. Assert.AreEqual(@"{
  2129. ""DefaultValueHandlingIncludeProperty"": ""Default!"",
  2130. ""DefaultValueHandlingPopulateProperty"": ""Default!"",
  2131. ""NullValueHandlingIncludeProperty"": null
  2132. }", json);
  2133. }
  2134. [Test]
  2135. public void DeserializeJsonPropertyWithHandlingValues()
  2136. {
  2137. string json = "{}";
  2138. JsonPropertyWithHandlingValues o = JsonConvert.DeserializeObject<JsonPropertyWithHandlingValues>(json);
  2139. Assert.AreEqual("Default!", o.DefaultValueHandlingIgnoreAndPopulateProperty);
  2140. Assert.AreEqual("Default!", o.DefaultValueHandlingPopulateProperty);
  2141. Assert.AreEqual(null, o.DefaultValueHandlingIgnoreProperty);
  2142. Assert.AreEqual(null, o.DefaultValueHandlingIncludeProperty);
  2143. }
  2144. [Test]
  2145. public void JsonPropertyWithHandlingValues_ReferenceLoopError()
  2146. {
  2147. string classRef = typeof(JsonPropertyWithHandlingValues).FullName;
  2148. ExceptionAssert.Throws<JsonSerializationException>(
  2149. "Self referencing loop detected for property 'ReferenceLoopHandlingErrorProperty' with type '" + classRef + "'. Path ''.",
  2150. () =>
  2151. {
  2152. JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
  2153. o.ReferenceLoopHandlingErrorProperty = o;
  2154. JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
  2155. });
  2156. }
  2157. [Test]
  2158. public void PartialClassDeserialize()
  2159. {
  2160. string json = @"{
  2161. ""request"": ""ux.settings.update"",
  2162. ""sid"": ""14c561bd-32a8-457e-b4e5-4bba0832897f"",
  2163. ""uid"": ""30c39065-0f31-de11-9442-001e3786a8ec"",
  2164. ""fidOrder"": [
  2165. ""id"",
  2166. ""andytest_name"",
  2167. ""andytest_age"",
  2168. ""andytest_address"",
  2169. ""andytest_phone"",
  2170. ""date"",
  2171. ""title"",
  2172. ""titleId""
  2173. ],
  2174. ""entityName"": ""Andy Test"",
  2175. ""setting"": ""entity.field.order""
  2176. }";
  2177. RequestOnly r = JsonConvert.DeserializeObject<RequestOnly>(json);
  2178. Assert.AreEqual("ux.settings.update", r.Request);
  2179. NonRequest n = JsonConvert.DeserializeObject<NonRequest>(json);
  2180. Assert.AreEqual(new Guid("14c561bd-32a8-457e-b4e5-4bba0832897f"), n.Sid);
  2181. Assert.AreEqual(new Guid("30c39065-0f31-de11-9442-001e3786a8ec"), n.Uid);
  2182. Assert.AreEqual(8, n.FidOrder.Count);
  2183. Assert.AreEqual("id", n.FidOrder[0]);
  2184. Assert.AreEqual("titleId", n.FidOrder[n.FidOrder.Count - 1]);
  2185. }
  2186. #if !(SILVERLIGHT || NET20 || NETFX_CORE || PORTABLE || PORTABLE40)
  2187. [MetadataType(typeof(OptInClassMetadata))]
  2188. public class OptInClass
  2189. {
  2190. [DataContract]
  2191. public class OptInClassMetadata
  2192. {
  2193. [DataMember]
  2194. public string Name { get; set; }
  2195. [DataMember]
  2196. public int Age { get; set; }
  2197. public string NotIncluded { get; set; }
  2198. }
  2199. public string Name { get; set; }
  2200. public int Age { get; set; }
  2201. public string NotIncluded { get; set; }
  2202. }
  2203. [Test]
  2204. public void OptInClassMetadataSerialization()
  2205. {
  2206. OptInClass optInClass = new OptInClass();
  2207. optInClass.Age = 26;
  2208. optInClass.Name = "James NK";
  2209. optInClass.NotIncluded = "Poor me :(";
  2210. string json = JsonConvert.SerializeObject(optInClass, Formatting.Indented);
  2211. Assert.AreEqual(@"{
  2212. ""Name"": ""James NK"",
  2213. ""Age"": 26
  2214. }", json);
  2215. OptInClass newOptInClass = JsonConvert.DeserializeObject<OptInClass>(@"{
  2216. ""Name"": ""James NK"",
  2217. ""NotIncluded"": ""Ignore me!"",
  2218. ""Age"": 26
  2219. }");
  2220. Assert.AreEqual(26, newOptInClass.Age);
  2221. Assert.AreEqual("James NK", newOptInClass.Name);
  2222. Assert.AreEqual(null, newOptInClass.NotIncluded);
  2223. }
  2224. #endif
  2225. #if !NET20
  2226. [DataContract]
  2227. public class DataContractPrivateMembers
  2228. {
  2229. public DataContractPrivateMembers()
  2230. {
  2231. }
  2232. public DataContractPrivateMembers(string name, int age, int rank, string title)
  2233. {
  2234. _name = name;
  2235. Age = age;
  2236. Rank = rank;
  2237. Title = title;
  2238. }
  2239. [DataMember]
  2240. private string _name;
  2241. [DataMember(Name = "_age")]
  2242. private int Age { get; set; }
  2243. [JsonProperty]
  2244. private int Rank { get; set; }
  2245. [JsonProperty(PropertyName = "JsonTitle")]
  2246. [DataMember(Name = "DataTitle")]
  2247. private string Title { get; set; }
  2248. public string NotIncluded { get; set; }
  2249. public override string ToString()
  2250. {
  2251. return "_name: " + _name + ", _age: " + Age + ", Rank: " + Rank + ", JsonTitle: " + Title;
  2252. }
  2253. }
  2254. [Test]
  2255. public void SerializeDataContractPrivateMembers()
  2256. {
  2257. DataContractPrivateMembers c = new DataContractPrivateMembers("Jeff", 26, 10, "Dr");
  2258. c.NotIncluded = "Hi";
  2259. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  2260. Assert.AreEqual(@"{
  2261. ""_name"": ""Jeff"",
  2262. ""_age"": 26,
  2263. ""Rank"": 10,
  2264. ""JsonTitle"": ""Dr""
  2265. }", json);
  2266. DataContractPrivateMembers cc = JsonConvert.DeserializeObject<DataContractPrivateMembers>(json);
  2267. Assert.AreEqual("_name: Jeff, _age: 26, Rank: 10, JsonTitle: Dr", cc.ToString());
  2268. }
  2269. #endif
  2270. [Test]
  2271. public void DeserializeDictionaryInterface()
  2272. {
  2273. string json = @"{
  2274. ""Name"": ""Name!"",
  2275. ""Dictionary"": {
  2276. ""Item"": 11
  2277. }
  2278. }";
  2279. DictionaryInterfaceClass c = JsonConvert.DeserializeObject<DictionaryInterfaceClass>(
  2280. json,
  2281. new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace });
  2282. Assert.AreEqual("Name!", c.Name);
  2283. Assert.AreEqual(1, c.Dictionary.Count);
  2284. Assert.AreEqual(11, c.Dictionary["Item"]);
  2285. }
  2286. [Test]
  2287. public void DeserializeDictionaryInterfaceWithExistingValues()
  2288. {
  2289. string json = @"{
  2290. ""Random"": {
  2291. ""blah"": 1
  2292. },
  2293. ""Name"": ""Name!"",
  2294. ""Dictionary"": {
  2295. ""Item"": 11,
  2296. ""Item1"": 12
  2297. },
  2298. ""Collection"": [
  2299. 999
  2300. ],
  2301. ""Employee"": {
  2302. ""Manager"": {
  2303. ""Name"": ""ManagerName!""
  2304. }
  2305. }
  2306. }";
  2307. DictionaryInterfaceClass c = JsonConvert.DeserializeObject<DictionaryInterfaceClass>(json,
  2308. new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Reuse });
  2309. Assert.AreEqual("Name!", c.Name);
  2310. Assert.AreEqual(3, c.Dictionary.Count);
  2311. Assert.AreEqual(11, c.Dictionary["Item"]);
  2312. Assert.AreEqual(1, c.Dictionary["existing"]);
  2313. Assert.AreEqual(4, c.Collection.Count);
  2314. Assert.AreEqual(1, c.Collection.ElementAt(0));
  2315. Assert.AreEqual(999, c.Collection.ElementAt(3));
  2316. Assert.AreEqual("EmployeeName!", c.Employee.Name);
  2317. Assert.AreEqual("ManagerName!", c.Employee.Manager.Name);
  2318. Assert.IsNotNull(c.Random);
  2319. }
  2320. [Test]
  2321. public void TypedObjectDeserializationWithComments()
  2322. {
  2323. string json = @"/*comment*/ { /*comment*/
  2324. ""Name"": /*comment*/ ""Apple"" /*comment*/, /*comment*/
  2325. ""ExpiryDate"": ""\/Date(1230422400000)\/"",
  2326. ""Price"": 3.99,
  2327. ""Sizes"": /*comment*/ [ /*comment*/
  2328. ""Small"", /*comment*/
  2329. ""Medium"" /*comment*/,
  2330. /*comment*/ ""Large""
  2331. /*comment*/ ] /*comment*/
  2332. } /*comment*/";
  2333. Product deserializedProduct = (Product)JsonConvert.DeserializeObject(json, typeof(Product));
  2334. Assert.AreEqual("Apple", deserializedProduct.Name);
  2335. Assert.AreEqual(new DateTime(2008, 12, 28, 0, 0, 0, DateTimeKind.Utc), deserializedProduct.ExpiryDate);
  2336. Assert.AreEqual(3.99m, deserializedProduct.Price);
  2337. Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
  2338. Assert.AreEqual("Medium", deserializedProduct.Sizes[1]);
  2339. Assert.AreEqual("Large", deserializedProduct.Sizes[2]);
  2340. }
  2341. [Test]
  2342. public void NestedInsideOuterObject()
  2343. {
  2344. string json = @"{
  2345. ""short"": {
  2346. ""original"": ""http://www.contrast.ie/blog/online&#45;marketing&#45;2009/"",
  2347. ""short"": ""m2sqc6"",
  2348. ""shortened"": ""http://short.ie/m2sqc6"",
  2349. ""error"": {
  2350. ""code"": 0,
  2351. ""msg"": ""No action taken""
  2352. }
  2353. }
  2354. }";
  2355. JObject o = JObject.Parse(json);
  2356. Shortie s = JsonConvert.DeserializeObject<Shortie>(o["short"].ToString());
  2357. Assert.IsNotNull(s);
  2358. Assert.AreEqual(s.Original, "http://www.contrast.ie/blog/online&#45;marketing&#45;2009/");
  2359. Assert.AreEqual(s.Short, "m2sqc6");
  2360. Assert.AreEqual(s.Shortened, "http://short.ie/m2sqc6");
  2361. }
  2362. [Test]
  2363. public void UriSerialization()
  2364. {
  2365. Uri uri = new Uri("http://codeplex.com");
  2366. string json = JsonConvert.SerializeObject(uri);
  2367. Assert.AreEqual("http://codeplex.com/", uri.ToString());
  2368. Uri newUri = JsonConvert.DeserializeObject<Uri>(json);
  2369. Assert.AreEqual(uri, newUri);
  2370. }
  2371. [Test]
  2372. public void AnonymousPlusLinqToSql()
  2373. {
  2374. var value = new
  2375. {
  2376. bar = new JObject(new JProperty("baz", 13))
  2377. };
  2378. string json = JsonConvert.SerializeObject(value);
  2379. Assert.AreEqual(@"{""bar"":{""baz"":13}}", json);
  2380. }
  2381. [Test]
  2382. public void SerializeEnumerableAsObject()
  2383. {
  2384. Content content = new Content
  2385. {
  2386. Text = "Blah, blah, blah",
  2387. Children = new List<Content>
  2388. {
  2389. new Content {Text = "First"},
  2390. new Content {Text = "Second"}
  2391. }
  2392. };
  2393. string json = JsonConvert.SerializeObject(content, Formatting.Indented);
  2394. Assert.AreEqual(@"{
  2395. ""Children"": [
  2396. {
  2397. ""Children"": null,
  2398. ""Text"": ""First""
  2399. },
  2400. {
  2401. ""Children"": null,
  2402. ""Text"": ""Second""
  2403. }
  2404. ],
  2405. ""Text"": ""Blah, blah, blah""
  2406. }", json);
  2407. }
  2408. [Test]
  2409. public void DeserializeEnumerableAsObject()
  2410. {
  2411. string json = @"{
  2412. ""Children"": [
  2413. {
  2414. ""Children"": null,
  2415. ""Text"": ""First""
  2416. },
  2417. {
  2418. ""Children"": null,
  2419. ""Text"": ""Second""
  2420. }
  2421. ],
  2422. ""Text"": ""Blah, blah, blah""
  2423. }";
  2424. Content content = JsonConvert.DeserializeObject<Content>(json);
  2425. Assert.AreEqual("Blah, blah, blah", content.Text);
  2426. Assert.AreEqual(2, content.Children.Count);
  2427. Assert.AreEqual("First", content.Children[0].Text);
  2428. Assert.AreEqual("Second", content.Children[1].Text);
  2429. }
  2430. [Test]
  2431. public void RoleTransferTest()
  2432. {
  2433. string json = @"{""Operation"":""1"",""RoleName"":""Admin"",""Direction"":""0""}";
  2434. RoleTransfer r = JsonConvert.DeserializeObject<RoleTransfer>(json);
  2435. Assert.AreEqual(RoleTransferOperation.Second, r.Operation);
  2436. Assert.AreEqual("Admin", r.RoleName);
  2437. Assert.AreEqual(RoleTransferDirection.First, r.Direction);
  2438. }
  2439. [Test]
  2440. public void PrimitiveValuesInObjectArray()
  2441. {
  2442. string json = @"{""action"":""Router"",""method"":""Navigate"",""data"":[""dashboard"",null],""type"":""rpc"",""tid"":2}";
  2443. ObjectArrayPropertyTest o = JsonConvert.DeserializeObject<ObjectArrayPropertyTest>(json);
  2444. Assert.AreEqual("Router", o.Action);
  2445. Assert.AreEqual("Navigate", o.Method);
  2446. Assert.AreEqual(2, o.Data.Length);
  2447. Assert.AreEqual("dashboard", o.Data[0]);
  2448. Assert.AreEqual(null, o.Data[1]);
  2449. }
  2450. [Test]
  2451. public void ComplexValuesInObjectArray()
  2452. {
  2453. string json = @"{""action"":""Router"",""method"":""Navigate"",""data"":[""dashboard"",[""id"", 1, ""teststring"", ""test""],{""one"":1}],""type"":""rpc"",""tid"":2}";
  2454. ObjectArrayPropertyTest o = JsonConvert.DeserializeObject<ObjectArrayPropertyTest>(json);
  2455. Assert.AreEqual("Router", o.Action);
  2456. Assert.AreEqual("Navigate", o.Method);
  2457. Assert.AreEqual(3, o.Data.Length);
  2458. Assert.AreEqual("dashboard", o.Data[0]);
  2459. CustomAssert.IsInstanceOfType(typeof(JArray), o.Data[1]);
  2460. Assert.AreEqual(4, ((JArray)o.Data[1]).Count);
  2461. CustomAssert.IsInstanceOfType(typeof(JObject), o.Data[2]);
  2462. Assert.AreEqual(1, ((JObject)o.Data[2]).Count);
  2463. Assert.AreEqual(1, (int)((JObject)o.Data[2])["one"]);
  2464. }
  2465. [Test]
  2466. public void DeserializeGenericDictionary()
  2467. {
  2468. string json = @"{""key1"":""value1"",""key2"":""value2""}";
  2469. Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  2470. Console.WriteLine(values.Count);
  2471. // 2
  2472. Console.WriteLine(values["key1"]);
  2473. // value1
  2474. Assert.AreEqual(2, values.Count);
  2475. Assert.AreEqual("value1", values["key1"]);
  2476. Assert.AreEqual("value2", values["key2"]);
  2477. }
  2478. [Test]
  2479. public void SerializeGenericList()
  2480. {
  2481. Product p1 = new Product
  2482. {
  2483. Name = "Product 1",
  2484. Price = 99.95m,
  2485. ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
  2486. };
  2487. Product p2 = new Product
  2488. {
  2489. Name = "Product 2",
  2490. Price = 12.50m,
  2491. ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
  2492. };
  2493. List<Product> products = new List<Product>();
  2494. products.Add(p1);
  2495. products.Add(p2);
  2496. string json = JsonConvert.SerializeObject(products, Formatting.Indented);
  2497. //[
  2498. // {
  2499. // "Name": "Product 1",
  2500. // "ExpiryDate": "\/Date(978048000000)\/",
  2501. // "Price": 99.95,
  2502. // "Sizes": null
  2503. // },
  2504. // {
  2505. // "Name": "Product 2",
  2506. // "ExpiryDate": "\/Date(1248998400000)\/",
  2507. // "Price": 12.50,
  2508. // "Sizes": null
  2509. // }
  2510. //]
  2511. Assert.AreEqual(@"[
  2512. {
  2513. ""Name"": ""Product 1"",
  2514. ""ExpiryDate"": ""2000-12-29T00:00:00Z"",
  2515. ""Price"": 99.95,
  2516. ""Sizes"": null
  2517. },
  2518. {
  2519. ""Name"": ""Product 2"",
  2520. ""ExpiryDate"": ""2009-07-31T00:00:00Z"",
  2521. ""Price"": 12.50,
  2522. ""Sizes"": null
  2523. }
  2524. ]", json);
  2525. }
  2526. [Test]
  2527. public void DeserializeGenericList()
  2528. {
  2529. string json = @"[
  2530. {
  2531. ""Name"": ""Product 1"",
  2532. ""ExpiryDate"": ""\/Date(978048000000)\/"",
  2533. ""Price"": 99.95,
  2534. ""Sizes"": null
  2535. },
  2536. {
  2537. ""Name"": ""Product 2"",
  2538. ""ExpiryDate"": ""\/Date(1248998400000)\/"",
  2539. ""Price"": 12.50,
  2540. ""Sizes"": null
  2541. }
  2542. ]";
  2543. List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);
  2544. Console.WriteLine(products.Count);
  2545. // 2
  2546. Product p1 = products[0];
  2547. Console.WriteLine(p1.Name);
  2548. // Product 1
  2549. Assert.AreEqual(2, products.Count);
  2550. Assert.AreEqual("Product 1", products[0].Name);
  2551. }
  2552. #if !NET20
  2553. [Test]
  2554. public void DeserializeEmptyStringToNullableDateTime()
  2555. {
  2556. string json = @"{""DateTimeField"":""""}";
  2557. NullableDateTimeTestClass c = JsonConvert.DeserializeObject<NullableDateTimeTestClass>(json);
  2558. Assert.AreEqual(null, c.DateTimeField);
  2559. }
  2560. #endif
  2561. [Test]
  2562. public void FailWhenClassWithNoDefaultConstructorHasMultipleConstructorsWithArguments()
  2563. {
  2564. 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)\/""}";
  2565. ExceptionAssert.Throws<JsonSerializationException>(
  2566. @"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.",
  2567. () =>
  2568. {
  2569. JsonConvert.DeserializeObject<TestObjects.Event>(json);
  2570. });
  2571. }
  2572. [Test]
  2573. public void DeserializeObjectSetOnlyProperty()
  2574. {
  2575. string json = @"{'SetOnlyProperty':[1,2,3,4,5]}";
  2576. SetOnlyPropertyClass2 setOnly = JsonConvert.DeserializeObject<SetOnlyPropertyClass2>(json);
  2577. JArray a = (JArray)setOnly.GetValue();
  2578. Assert.AreEqual(5, a.Count);
  2579. Assert.AreEqual(1, (int)a[0]);
  2580. Assert.AreEqual(5, (int)a[a.Count - 1]);
  2581. }
  2582. [Test]
  2583. public void DeserializeOptInClasses()
  2584. {
  2585. string json = @"{id: ""12"", name: ""test"", items: [{id: ""112"", name: ""testing""}]}";
  2586. ListTestClass l = JsonConvert.DeserializeObject<ListTestClass>(json);
  2587. }
  2588. [Test]
  2589. public void DeserializeNullableListWithNulls()
  2590. {
  2591. List<decimal?> l = JsonConvert.DeserializeObject<List<decimal?>>("[ 3.3, null, 1.1 ] ");
  2592. Assert.AreEqual(3, l.Count);
  2593. Assert.AreEqual(3.3m, l[0]);
  2594. Assert.AreEqual(null, l[1]);
  2595. Assert.AreEqual(1.1m, l[2]);
  2596. }
  2597. [Test]
  2598. public void CannotDeserializeArrayIntoObject()
  2599. {
  2600. string json = @"[]";
  2601. ExceptionAssert.Throws<JsonSerializationException>(
  2602. @"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.
  2603. 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.
  2604. Path '', line 1, position 1.",
  2605. () =>
  2606. {
  2607. JsonConvert.DeserializeObject<Person>(json);
  2608. });
  2609. }
  2610. [Test]
  2611. public void CannotDeserializeArrayIntoDictionary()
  2612. {
  2613. string json = @"[]";
  2614. ExceptionAssert.Throws<JsonSerializationException>(
  2615. @"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.
  2616. 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.
  2617. Path '', line 1, position 1.",
  2618. () =>
  2619. {
  2620. JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  2621. });
  2622. }
  2623. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  2624. [Test]
  2625. public void CannotDeserializeArrayIntoSerializable()
  2626. {
  2627. string json = @"[]";
  2628. ExceptionAssert.Throws<JsonSerializationException>(
  2629. @"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.
  2630. 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.
  2631. Path '', line 1, position 1.",
  2632. () =>
  2633. {
  2634. JsonConvert.DeserializeObject<Exception>(json);
  2635. });
  2636. }
  2637. #endif
  2638. [Test]
  2639. public void CannotDeserializeArrayIntoDouble()
  2640. {
  2641. string json = @"[]";
  2642. ExceptionAssert.Throws<JsonSerializationException>(
  2643. @"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.
  2644. 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.
  2645. Path '', line 1, position 1.",
  2646. () =>
  2647. {
  2648. JsonConvert.DeserializeObject<double>(json);
  2649. });
  2650. }
  2651. #if !(NET35 || NET20 || PORTABLE40)
  2652. [Test]
  2653. public void CannotDeserializeArrayIntoDynamic()
  2654. {
  2655. string json = @"[]";
  2656. ExceptionAssert.Throws<JsonSerializationException>(
  2657. @"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.
  2658. 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.
  2659. Path '', line 1, position 1.",
  2660. () =>
  2661. {
  2662. JsonConvert.DeserializeObject<DynamicDictionary>(json);
  2663. });
  2664. }
  2665. #endif
  2666. [Test]
  2667. public void CannotDeserializeArrayIntoLinqToJson()
  2668. {
  2669. string json = @"[]";
  2670. ExceptionAssert.Throws<InvalidCastException>(
  2671. @"Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.",
  2672. () =>
  2673. {
  2674. JsonConvert.DeserializeObject<JObject>(json);
  2675. });
  2676. }
  2677. [Test]
  2678. public void CannotDeserializeConstructorIntoObject()
  2679. {
  2680. string json = @"new Constructor(123)";
  2681. ExceptionAssert.Throws<JsonSerializationException>(
  2682. @"Error converting value ""Constructor"" to type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '', line 1, position 16.",
  2683. () =>
  2684. {
  2685. JsonConvert.DeserializeObject<Person>(json);
  2686. });
  2687. }
  2688. [Test]
  2689. public void CannotDeserializeConstructorIntoObjectNested()
  2690. {
  2691. string json = @"[new Constructor(123)]";
  2692. ExceptionAssert.Throws<JsonSerializationException>(
  2693. @"Error converting value ""Constructor"" to type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '[0]', line 1, position 17.",
  2694. () =>
  2695. {
  2696. JsonConvert.DeserializeObject<List<Person>>(json);
  2697. });
  2698. }
  2699. [Test]
  2700. public void CannotDeserializeObjectIntoArray()
  2701. {
  2702. string json = @"{}";
  2703. ExceptionAssert.Throws<JsonSerializationException>(
  2704. @"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.
  2705. 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.
  2706. Path '', line 1, position 2.",
  2707. () =>
  2708. {
  2709. JsonConvert.DeserializeObject<List<Person>>(json);
  2710. });
  2711. }
  2712. [Test]
  2713. public void CannotPopulateArrayIntoObject()
  2714. {
  2715. string json = @"[]";
  2716. ExceptionAssert.Throws<JsonSerializationException>(
  2717. @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '', line 1, position 1.",
  2718. () =>
  2719. {
  2720. JsonConvert.PopulateObject(json, new Person());
  2721. });
  2722. }
  2723. [Test]
  2724. public void CannotPopulateObjectIntoArray()
  2725. {
  2726. string json = @"{}";
  2727. ExceptionAssert.Throws<JsonSerializationException>(
  2728. @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Path '', line 1, position 2.",
  2729. () =>
  2730. {
  2731. JsonConvert.PopulateObject(json, new List<Person>());
  2732. });
  2733. }
  2734. [Test]
  2735. public void DeserializeEmptyString()
  2736. {
  2737. string json = @"{""Name"":""""}";
  2738. Person p = JsonConvert.DeserializeObject<Person>(json);
  2739. Assert.AreEqual("", p.Name);
  2740. }
  2741. [Test]
  2742. public void SerializePropertyGetError()
  2743. {
  2744. ExceptionAssert.Throws<JsonSerializationException>(
  2745. @"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.",
  2746. () =>
  2747. {
  2748. JsonConvert.SerializeObject(new MemoryStream(), new JsonSerializerSettings
  2749. {
  2750. ContractResolver = new DefaultContractResolver
  2751. {
  2752. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40)
  2753. IgnoreSerializableAttribute = true
  2754. #endif
  2755. }
  2756. });
  2757. });
  2758. }
  2759. [Test]
  2760. public void DeserializePropertySetError()
  2761. {
  2762. ExceptionAssert.Throws<JsonSerializationException>(
  2763. @"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'.",
  2764. () =>
  2765. {
  2766. JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:0}", new JsonSerializerSettings
  2767. {
  2768. ContractResolver = new DefaultContractResolver
  2769. {
  2770. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40)
  2771. IgnoreSerializableAttribute = true
  2772. #endif
  2773. }
  2774. });
  2775. });
  2776. }
  2777. [Test]
  2778. public void DeserializeEnsureTypeEmptyStringToIntError()
  2779. {
  2780. ExceptionAssert.Throws<JsonSerializationException>(
  2781. @"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 15.",
  2782. () =>
  2783. {
  2784. JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}", new JsonSerializerSettings
  2785. {
  2786. ContractResolver = new DefaultContractResolver
  2787. {
  2788. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40)
  2789. IgnoreSerializableAttribute = true
  2790. #endif
  2791. }
  2792. });
  2793. });
  2794. }
  2795. [Test]
  2796. public void DeserializeEnsureTypeNullToIntError()
  2797. {
  2798. ExceptionAssert.Throws<JsonSerializationException>(
  2799. @"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 17.",
  2800. () =>
  2801. {
  2802. JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}", new JsonSerializerSettings
  2803. {
  2804. ContractResolver = new DefaultContractResolver
  2805. {
  2806. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40)
  2807. IgnoreSerializableAttribute = true
  2808. #endif
  2809. }
  2810. });
  2811. });
  2812. }
  2813. [Test]
  2814. public void SerializeGenericListOfStrings()
  2815. {
  2816. List<String> strings = new List<String>();
  2817. strings.Add("str_1");
  2818. strings.Add("str_2");
  2819. strings.Add("str_3");
  2820. string json = JsonConvert.SerializeObject(strings);
  2821. Assert.AreEqual(@"[""str_1"",""str_2"",""str_3""]", json);
  2822. }
  2823. [Test]
  2824. public void ConstructorReadonlyFieldsTest()
  2825. {
  2826. ConstructorReadonlyFields c1 = new ConstructorReadonlyFields("String!", int.MaxValue);
  2827. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  2828. Assert.AreEqual(@"{
  2829. ""A"": ""String!"",
  2830. ""B"": 2147483647
  2831. }", json);
  2832. ConstructorReadonlyFields c2 = JsonConvert.DeserializeObject<ConstructorReadonlyFields>(json);
  2833. Assert.AreEqual("String!", c2.A);
  2834. Assert.AreEqual(int.MaxValue, c2.B);
  2835. }
  2836. [Test]
  2837. public void SerializeStruct()
  2838. {
  2839. StructTest structTest = new StructTest
  2840. {
  2841. StringProperty = "StringProperty!",
  2842. StringField = "StringField",
  2843. IntProperty = 5,
  2844. IntField = 10
  2845. };
  2846. string json = JsonConvert.SerializeObject(structTest, Formatting.Indented);
  2847. Console.WriteLine(json);
  2848. Assert.AreEqual(@"{
  2849. ""StringField"": ""StringField"",
  2850. ""IntField"": 10,
  2851. ""StringProperty"": ""StringProperty!"",
  2852. ""IntProperty"": 5
  2853. }", json);
  2854. StructTest deserialized = JsonConvert.DeserializeObject<StructTest>(json);
  2855. Assert.AreEqual(structTest.StringProperty, deserialized.StringProperty);
  2856. Assert.AreEqual(structTest.StringField, deserialized.StringField);
  2857. Assert.AreEqual(structTest.IntProperty, deserialized.IntProperty);
  2858. Assert.AreEqual(structTest.IntField, deserialized.IntField);
  2859. }
  2860. [Test]
  2861. public void SerializeListWithJsonConverter()
  2862. {
  2863. Foo f = new Foo();
  2864. f.Bars.Add(new Bar { Id = 0 });
  2865. f.Bars.Add(new Bar { Id = 1 });
  2866. f.Bars.Add(new Bar { Id = 2 });
  2867. string json = JsonConvert.SerializeObject(f, Formatting.Indented);
  2868. Assert.AreEqual(@"{
  2869. ""Bars"": [
  2870. 0,
  2871. 1,
  2872. 2
  2873. ]
  2874. }", json);
  2875. Foo newFoo = JsonConvert.DeserializeObject<Foo>(json);
  2876. Assert.AreEqual(3, newFoo.Bars.Count);
  2877. Assert.AreEqual(0, newFoo.Bars[0].Id);
  2878. Assert.AreEqual(1, newFoo.Bars[1].Id);
  2879. Assert.AreEqual(2, newFoo.Bars[2].Id);
  2880. }
  2881. [Test]
  2882. public void SerializeGuidKeyedDictionary()
  2883. {
  2884. Dictionary<Guid, int> dictionary = new Dictionary<Guid, int>();
  2885. dictionary.Add(new Guid("F60EAEE0-AE47-488E-B330-59527B742D77"), 1);
  2886. dictionary.Add(new Guid("C2594C02-EBA1-426A-AA87-8DD8871350B0"), 2);
  2887. string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
  2888. Assert.AreEqual(@"{
  2889. ""f60eaee0-ae47-488e-b330-59527b742d77"": 1,
  2890. ""c2594c02-eba1-426a-aa87-8dd8871350b0"": 2
  2891. }", json);
  2892. }
  2893. [Test]
  2894. public void SerializePersonKeyedDictionary()
  2895. {
  2896. Dictionary<Person, int> dictionary = new Dictionary<Person, int>();
  2897. dictionary.Add(new Person { Name = "p1" }, 1);
  2898. dictionary.Add(new Person { Name = "p2" }, 2);
  2899. string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
  2900. Assert.AreEqual(@"{
  2901. ""Newtonsoft.Json.Tests.TestObjects.Person"": 1,
  2902. ""Newtonsoft.Json.Tests.TestObjects.Person"": 2
  2903. }", json);
  2904. }
  2905. [Test]
  2906. public void DeserializePersonKeyedDictionary()
  2907. {
  2908. 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.",
  2909. () =>
  2910. {
  2911. string json =
  2912. @"{
  2913. ""Newtonsoft.Json.Tests.TestObjects.Person"": 1,
  2914. ""Newtonsoft.Json.Tests.TestObjects.Person"": 2
  2915. }";
  2916. JsonConvert.DeserializeObject<Dictionary<Person, int>>(json);
  2917. });
  2918. }
  2919. [Test]
  2920. public void SerializeFragment()
  2921. {
  2922. string googleSearchText = @"{
  2923. ""responseData"": {
  2924. ""results"": [
  2925. {
  2926. ""GsearchResultClass"": ""GwebSearch"",
  2927. ""unescapedUrl"": ""http://en.wikipedia.org/wiki/Paris_Hilton"",
  2928. ""url"": ""http://en.wikipedia.org/wiki/Paris_Hilton"",
  2929. ""visibleUrl"": ""en.wikipedia.org"",
  2930. ""cacheUrl"": ""http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org"",
  2931. ""title"": ""<b>Paris Hilton</b> - Wikipedia, the free encyclopedia"",
  2932. ""titleNoFormatting"": ""Paris Hilton - Wikipedia, the free encyclopedia"",
  2933. ""content"": ""[1] In 2006, she released her debut album...""
  2934. },
  2935. {
  2936. ""GsearchResultClass"": ""GwebSearch"",
  2937. ""unescapedUrl"": ""http://www.imdb.com/name/nm0385296/"",
  2938. ""url"": ""http://www.imdb.com/name/nm0385296/"",
  2939. ""visibleUrl"": ""www.imdb.com"",
  2940. ""cacheUrl"": ""http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com"",
  2941. ""title"": ""<b>Paris Hilton</b>"",
  2942. ""titleNoFormatting"": ""Paris Hilton"",
  2943. ""content"": ""Self: Zoolander. Socialite <b>Paris Hilton</b>...""
  2944. }
  2945. ],
  2946. ""cursor"": {
  2947. ""pages"": [
  2948. {
  2949. ""start"": ""0"",
  2950. ""label"": 1
  2951. },
  2952. {
  2953. ""start"": ""4"",
  2954. ""label"": 2
  2955. },
  2956. {
  2957. ""start"": ""8"",
  2958. ""label"": 3
  2959. },
  2960. {
  2961. ""start"": ""12"",
  2962. ""label"": 4
  2963. }
  2964. ],
  2965. ""estimatedResultCount"": ""59600000"",
  2966. ""currentPageIndex"": 0,
  2967. ""moreResultsUrl"": ""http://www.google.com/search?oe=utf8&ie=utf8...""
  2968. }
  2969. },
  2970. ""responseDetails"": null,
  2971. ""responseStatus"": 200
  2972. }";
  2973. JObject googleSearch = JObject.Parse(googleSearchText);
  2974. // get JSON result objects into a list
  2975. IList<JToken> results = googleSearch["responseData"]["results"].Children().ToList();
  2976. // serialize JSON results into .NET objects
  2977. IList<SearchResult> searchResults = new List<SearchResult>();
  2978. foreach (JToken result in results)
  2979. {
  2980. SearchResult searchResult = JsonConvert.DeserializeObject<SearchResult>(result.ToString());
  2981. searchResults.Add(searchResult);
  2982. }
  2983. // Title = <b>Paris Hilton</b> - Wikipedia, the free encyclopedia
  2984. // Content = [1] In 2006, she released her debut album...
  2985. // Url = http://en.wikipedia.org/wiki/Paris_Hilton
  2986. // Title = <b>Paris Hilton</b>
  2987. // Content = Self: Zoolander. Socialite <b>Paris Hilton</b>...
  2988. // Url = http://www.imdb.com/name/nm0385296/
  2989. Assert.AreEqual(2, searchResults.Count);
  2990. Assert.AreEqual("<b>Paris Hilton</b> - Wikipedia, the free encyclopedia", searchResults[0].Title);
  2991. Assert.AreEqual("<b>Paris Hilton</b>", searchResults[1].Title);
  2992. }
  2993. [Test]
  2994. public void DeserializeBaseReferenceWithDerivedValue()
  2995. {
  2996. PersonPropertyClass personPropertyClass = new PersonPropertyClass();
  2997. WagePerson wagePerson = (WagePerson)personPropertyClass.Person;
  2998. wagePerson.BirthDate = new DateTime(2000, 11, 29, 23, 59, 59, DateTimeKind.Utc);
  2999. wagePerson.Department = "McDees";
  3000. wagePerson.HourlyWage = 12.50m;
  3001. wagePerson.LastModified = new DateTime(2000, 11, 29, 23, 59, 59, DateTimeKind.Utc);
  3002. wagePerson.Name = "Jim Bob";
  3003. string json = JsonConvert.SerializeObject(personPropertyClass, Formatting.Indented);
  3004. Assert.AreEqual(
  3005. @"{
  3006. ""Person"": {
  3007. ""HourlyWage"": 12.50,
  3008. ""Name"": ""Jim Bob"",
  3009. ""BirthDate"": ""2000-11-29T23:59:59Z"",
  3010. ""LastModified"": ""2000-11-29T23:59:59Z""
  3011. }
  3012. }",
  3013. json);
  3014. PersonPropertyClass newPersonPropertyClass = JsonConvert.DeserializeObject<PersonPropertyClass>(json);
  3015. Assert.AreEqual(wagePerson.HourlyWage, ((WagePerson)newPersonPropertyClass.Person).HourlyWage);
  3016. }
  3017. public class ExistingValueClass
  3018. {
  3019. public Dictionary<string, string> Dictionary { get; set; }
  3020. public List<string> List { get; set; }
  3021. public ExistingValueClass()
  3022. {
  3023. Dictionary = new Dictionary<string, string>
  3024. {
  3025. {"existing", "yup"}
  3026. };
  3027. List = new List<string>
  3028. {
  3029. "existing"
  3030. };
  3031. }
  3032. }
  3033. [Test]
  3034. public void DeserializePopulateDictionaryAndList()
  3035. {
  3036. ExistingValueClass d = JsonConvert.DeserializeObject<ExistingValueClass>(@"{'Dictionary':{appended:'appended',existing:'new'}}");
  3037. Assert.IsNotNull(d);
  3038. Assert.IsNotNull(d.Dictionary);
  3039. Assert.AreEqual(typeof(Dictionary<string, string>), d.Dictionary.GetType());
  3040. Assert.AreEqual(typeof(List<string>), d.List.GetType());
  3041. Assert.AreEqual(2, d.Dictionary.Count);
  3042. Assert.AreEqual("new", d.Dictionary["existing"]);
  3043. Assert.AreEqual("appended", d.Dictionary["appended"]);
  3044. Assert.AreEqual(1, d.List.Count);
  3045. Assert.AreEqual("existing", d.List[0]);
  3046. }
  3047. public interface IKeyValueId
  3048. {
  3049. int Id { get; set; }
  3050. string Key { get; set; }
  3051. string Value { get; set; }
  3052. }
  3053. public class KeyValueId : IKeyValueId
  3054. {
  3055. public int Id { get; set; }
  3056. public string Key { get; set; }
  3057. public string Value { get; set; }
  3058. }
  3059. public class ThisGenericTest<T> where T : IKeyValueId
  3060. {
  3061. private Dictionary<string, T> _dict1 = new Dictionary<string, T>();
  3062. public string MyProperty { get; set; }
  3063. public void Add(T item)
  3064. {
  3065. this._dict1.Add(item.Key, item);
  3066. }
  3067. public T this[string key]
  3068. {
  3069. get { return this._dict1[key]; }
  3070. set { this._dict1[key] = value; }
  3071. }
  3072. public T this[int id]
  3073. {
  3074. get { return this._dict1.Values.FirstOrDefault(x => x.Id == id); }
  3075. set
  3076. {
  3077. var item = this[id];
  3078. if (item == null)
  3079. this.Add(value);
  3080. else
  3081. this._dict1[item.Key] = value;
  3082. }
  3083. }
  3084. public string ToJson()
  3085. {
  3086. return JsonConvert.SerializeObject(this, Formatting.Indented);
  3087. }
  3088. public T[] TheItems
  3089. {
  3090. get { return this._dict1.Values.ToArray<T>(); }
  3091. set
  3092. {
  3093. foreach (var item in value)
  3094. this.Add(item);
  3095. }
  3096. }
  3097. }
  3098. [Test]
  3099. public void IgnoreIndexedProperties()
  3100. {
  3101. ThisGenericTest<KeyValueId> g = new ThisGenericTest<KeyValueId>();
  3102. g.Add(new KeyValueId { Id = 1, Key = "key1", Value = "value1" });
  3103. g.Add(new KeyValueId { Id = 2, Key = "key2", Value = "value2" });
  3104. g.MyProperty = "some value";
  3105. string json = g.ToJson();
  3106. Assert.AreEqual(@"{
  3107. ""MyProperty"": ""some value"",
  3108. ""TheItems"": [
  3109. {
  3110. ""Id"": 1,
  3111. ""Key"": ""key1"",
  3112. ""Value"": ""value1""
  3113. },
  3114. {
  3115. ""Id"": 2,
  3116. ""Key"": ""key2"",
  3117. ""Value"": ""value2""
  3118. }
  3119. ]
  3120. }", json);
  3121. ThisGenericTest<KeyValueId> gen = JsonConvert.DeserializeObject<ThisGenericTest<KeyValueId>>(json);
  3122. Assert.AreEqual("some value", gen.MyProperty);
  3123. }
  3124. public class JRawValueTestObject
  3125. {
  3126. public JRaw Value { get; set; }
  3127. }
  3128. [Test]
  3129. public void JRawValue()
  3130. {
  3131. JRawValueTestObject deserialized = JsonConvert.DeserializeObject<JRawValueTestObject>("{value:3}");
  3132. Assert.AreEqual("3", deserialized.Value.ToString());
  3133. deserialized = JsonConvert.DeserializeObject<JRawValueTestObject>("{value:'3'}");
  3134. Assert.AreEqual(@"""3""", deserialized.Value.ToString());
  3135. }
  3136. [Test]
  3137. public void DeserializeDictionaryWithNoDefaultConstructor()
  3138. {
  3139. string json = "{key1:'value1',key2:'value2',key3:'value3'}";
  3140. var dic = JsonConvert.DeserializeObject<DictionaryWithNoDefaultConstructor>(json);
  3141. Assert.AreEqual(3, dic.Count);
  3142. Assert.AreEqual("value1", dic["key1"]);
  3143. Assert.AreEqual("value2", dic["key2"]);
  3144. Assert.AreEqual("value3", dic["key3"]);
  3145. }
  3146. [Test]
  3147. public void DeserializeDictionaryWithNoDefaultConstructor_PreserveReferences()
  3148. {
  3149. string json = "{'$id':'1',key1:'value1',key2:'value2',key3:'value3'}";
  3150. ExceptionAssert.Throws<JsonSerializationException>("Cannot preserve reference to readonly dictionary, or dictionary created from a non-default constructor: Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Path 'key1', line 1, position 16.",
  3151. () => JsonConvert.DeserializeObject<DictionaryWithNoDefaultConstructor>(json, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All }));
  3152. }
  3153. public class DictionaryWithNoDefaultConstructor : Dictionary<string, string>
  3154. {
  3155. public DictionaryWithNoDefaultConstructor(IEnumerable<KeyValuePair<string, string>> initial)
  3156. {
  3157. foreach (KeyValuePair<string, string> pair in initial)
  3158. {
  3159. Add(pair.Key, pair.Value);
  3160. }
  3161. }
  3162. }
  3163. [JsonObject(MemberSerialization.OptIn)]
  3164. public class A
  3165. {
  3166. [JsonProperty("A1")]
  3167. private string _A1;
  3168. public string A1
  3169. {
  3170. get { return _A1; }
  3171. set { _A1 = value; }
  3172. }
  3173. [JsonProperty("A2")]
  3174. private string A2 { get; set; }
  3175. }
  3176. [JsonObject(MemberSerialization.OptIn)]
  3177. public class B : A
  3178. {
  3179. public string B1 { get; set; }
  3180. [JsonProperty("B2")]
  3181. private string _B2;
  3182. public string B2
  3183. {
  3184. get { return _B2; }
  3185. set { _B2 = value; }
  3186. }
  3187. [JsonProperty("B3")]
  3188. private string B3 { get; set; }
  3189. }
  3190. [Test]
  3191. public void SerializeNonPublicBaseJsonProperties()
  3192. {
  3193. B value = new B();
  3194. string json = JsonConvert.SerializeObject(value, Formatting.Indented);
  3195. Assert.AreEqual(@"{
  3196. ""B2"": null,
  3197. ""A1"": null,
  3198. ""B3"": null,
  3199. ""A2"": null
  3200. }", json);
  3201. }
  3202. public class TestClass
  3203. {
  3204. public string Key { get; set; }
  3205. public object Value { get; set; }
  3206. }
  3207. [Test]
  3208. public void DeserializeToObjectProperty()
  3209. {
  3210. var json = "{ Key: 'abc', Value: 123 }";
  3211. var item = JsonConvert.DeserializeObject<TestClass>(json);
  3212. Assert.AreEqual(123L, item.Value);
  3213. }
  3214. public abstract class Animal
  3215. {
  3216. public abstract string Name { get; }
  3217. }
  3218. public class Human : Animal
  3219. {
  3220. public override string Name
  3221. {
  3222. get { return typeof(Human).Name; }
  3223. }
  3224. public string Ethnicity { get; set; }
  3225. }
  3226. #if !NET20
  3227. public class DataContractJsonSerializerTestClass
  3228. {
  3229. public TimeSpan TimeSpanProperty { get; set; }
  3230. public Guid GuidProperty { get; set; }
  3231. public Animal AnimalProperty { get; set; }
  3232. public Exception ExceptionProperty { get; set; }
  3233. }
  3234. [Test]
  3235. public void DataContractJsonSerializerTest()
  3236. {
  3237. Exception ex = new Exception("Blah blah blah");
  3238. DataContractJsonSerializerTestClass c = new DataContractJsonSerializerTestClass();
  3239. c.TimeSpanProperty = new TimeSpan(200, 20, 59, 30, 900);
  3240. c.GuidProperty = new Guid("66143115-BE2A-4a59-AF0A-348E1EA15B1E");
  3241. c.AnimalProperty = new Human() { Ethnicity = "European" };
  3242. c.ExceptionProperty = ex;
  3243. MemoryStream ms = new MemoryStream();
  3244. DataContractJsonSerializer serializer = new DataContractJsonSerializer(
  3245. typeof(DataContractJsonSerializerTestClass),
  3246. new Type[] { typeof(Human) });
  3247. serializer.WriteObject(ms, c);
  3248. byte[] jsonBytes = ms.ToArray();
  3249. string json = Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length);
  3250. //Console.WriteLine(JObject.Parse(json).ToString());
  3251. //Console.WriteLine();
  3252. //Console.WriteLine(JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings
  3253. // {
  3254. // // TypeNameHandling = TypeNameHandling.Objects
  3255. // }));
  3256. }
  3257. #endif
  3258. public class ModelStateDictionary<T> : IDictionary<string, T>
  3259. {
  3260. private readonly Dictionary<string, T> _innerDictionary = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
  3261. public ModelStateDictionary()
  3262. {
  3263. }
  3264. public ModelStateDictionary(ModelStateDictionary<T> dictionary)
  3265. {
  3266. if (dictionary == null)
  3267. {
  3268. throw new ArgumentNullException("dictionary");
  3269. }
  3270. foreach (var entry in dictionary)
  3271. {
  3272. _innerDictionary.Add(entry.Key, entry.Value);
  3273. }
  3274. }
  3275. public int Count
  3276. {
  3277. get { return _innerDictionary.Count; }
  3278. }
  3279. public bool IsReadOnly
  3280. {
  3281. get { return ((IDictionary<string, T>)_innerDictionary).IsReadOnly; }
  3282. }
  3283. public ICollection<string> Keys
  3284. {
  3285. get { return _innerDictionary.Keys; }
  3286. }
  3287. public T this[string key]
  3288. {
  3289. get
  3290. {
  3291. T value;
  3292. _innerDictionary.TryGetValue(key, out value);
  3293. return value;
  3294. }
  3295. set { _innerDictionary[key] = value; }
  3296. }
  3297. public ICollection<T> Values
  3298. {
  3299. get { return _innerDictionary.Values; }
  3300. }
  3301. public void Add(KeyValuePair<string, T> item)
  3302. {
  3303. ((IDictionary<string, T>)_innerDictionary).Add(item);
  3304. }
  3305. public void Add(string key, T value)
  3306. {
  3307. _innerDictionary.Add(key, value);
  3308. }
  3309. public void Clear()
  3310. {
  3311. _innerDictionary.Clear();
  3312. }
  3313. public bool Contains(KeyValuePair<string, T> item)
  3314. {
  3315. return ((IDictionary<string, T>)_innerDictionary).Contains(item);
  3316. }
  3317. public bool ContainsKey(string key)
  3318. {
  3319. return _innerDictionary.ContainsKey(key);
  3320. }
  3321. public void CopyTo(KeyValuePair<string, T>[] array, int arrayIndex)
  3322. {
  3323. ((IDictionary<string, T>)_innerDictionary).CopyTo(array, arrayIndex);
  3324. }
  3325. public IEnumerator<KeyValuePair<string, T>> GetEnumerator()
  3326. {
  3327. return _innerDictionary.GetEnumerator();
  3328. }
  3329. public void Merge(ModelStateDictionary<T> dictionary)
  3330. {
  3331. if (dictionary == null)
  3332. {
  3333. return;
  3334. }
  3335. foreach (var entry in dictionary)
  3336. {
  3337. this[entry.Key] = entry.Value;
  3338. }
  3339. }
  3340. public bool Remove(KeyValuePair<string, T> item)
  3341. {
  3342. return ((IDictionary<string, T>)_innerDictionary).Remove(item);
  3343. }
  3344. public bool Remove(string key)
  3345. {
  3346. return _innerDictionary.Remove(key);
  3347. }
  3348. public bool TryGetValue(string key, out T value)
  3349. {
  3350. return _innerDictionary.TryGetValue(key, out value);
  3351. }
  3352. IEnumerator IEnumerable.GetEnumerator()
  3353. {
  3354. return ((IEnumerable)_innerDictionary).GetEnumerator();
  3355. }
  3356. }
  3357. [Test]
  3358. public void SerializeNonIDictionary()
  3359. {
  3360. ModelStateDictionary<string> modelStateDictionary = new ModelStateDictionary<string>();
  3361. modelStateDictionary.Add("key", "value");
  3362. string json = JsonConvert.SerializeObject(modelStateDictionary);
  3363. Assert.AreEqual(@"{""key"":""value""}", json);
  3364. ModelStateDictionary<string> newModelStateDictionary = JsonConvert.DeserializeObject<ModelStateDictionary<string>>(json);
  3365. Assert.AreEqual(1, newModelStateDictionary.Count);
  3366. Assert.AreEqual("value", newModelStateDictionary["key"]);
  3367. }
  3368. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40)
  3369. public class ISerializableTestObject : ISerializable
  3370. {
  3371. internal string _stringValue;
  3372. internal int _intValue;
  3373. internal DateTimeOffset _dateTimeOffsetValue;
  3374. internal Person _personValue;
  3375. internal Person _nullPersonValue;
  3376. internal int? _nullableInt;
  3377. internal bool _booleanValue;
  3378. internal byte _byteValue;
  3379. internal char _charValue;
  3380. internal DateTime _dateTimeValue;
  3381. internal decimal _decimalValue;
  3382. internal short _shortValue;
  3383. internal long _longValue;
  3384. internal sbyte _sbyteValue;
  3385. internal float _floatValue;
  3386. internal ushort _ushortValue;
  3387. internal uint _uintValue;
  3388. internal ulong _ulongValue;
  3389. public ISerializableTestObject(string stringValue, int intValue, DateTimeOffset dateTimeOffset, Person personValue)
  3390. {
  3391. _stringValue = stringValue;
  3392. _intValue = intValue;
  3393. _dateTimeOffsetValue = dateTimeOffset;
  3394. _personValue = personValue;
  3395. _dateTimeValue = new DateTime(0, DateTimeKind.Utc);
  3396. }
  3397. protected ISerializableTestObject(SerializationInfo info, StreamingContext context)
  3398. {
  3399. _stringValue = info.GetString("stringValue");
  3400. _intValue = info.GetInt32("intValue");
  3401. _dateTimeOffsetValue = (DateTimeOffset)info.GetValue("dateTimeOffsetValue", typeof(DateTimeOffset));
  3402. _personValue = (Person)info.GetValue("personValue", typeof(Person));
  3403. _nullPersonValue = (Person)info.GetValue("nullPersonValue", typeof(Person));
  3404. _nullableInt = (int?)info.GetValue("nullableInt", typeof(int?));
  3405. _booleanValue = info.GetBoolean("booleanValue");
  3406. _byteValue = info.GetByte("byteValue");
  3407. _charValue = info.GetChar("charValue");
  3408. _dateTimeValue = info.GetDateTime("dateTimeValue");
  3409. _decimalValue = info.GetDecimal("decimalValue");
  3410. _shortValue = info.GetInt16("shortValue");
  3411. _longValue = info.GetInt64("longValue");
  3412. _sbyteValue = info.GetSByte("sbyteValue");
  3413. _floatValue = info.GetSingle("floatValue");
  3414. _ushortValue = info.GetUInt16("ushortValue");
  3415. _uintValue = info.GetUInt32("uintValue");
  3416. _ulongValue = info.GetUInt64("ulongValue");
  3417. }
  3418. public void GetObjectData(SerializationInfo info, StreamingContext context)
  3419. {
  3420. info.AddValue("stringValue", _stringValue);
  3421. info.AddValue("intValue", _intValue);
  3422. info.AddValue("dateTimeOffsetValue", _dateTimeOffsetValue);
  3423. info.AddValue("personValue", _personValue);
  3424. info.AddValue("nullPersonValue", _nullPersonValue);
  3425. info.AddValue("nullableInt", null);
  3426. info.AddValue("booleanValue", _booleanValue);
  3427. info.AddValue("byteValue", _byteValue);
  3428. info.AddValue("charValue", _charValue);
  3429. info.AddValue("dateTimeValue", _dateTimeValue);
  3430. info.AddValue("decimalValue", _decimalValue);
  3431. info.AddValue("shortValue", _shortValue);
  3432. info.AddValue("longValue", _longValue);
  3433. info.AddValue("sbyteValue", _sbyteValue);
  3434. info.AddValue("floatValue", _floatValue);
  3435. info.AddValue("ushortValue", _ushortValue);
  3436. info.AddValue("uintValue", _uintValue);
  3437. info.AddValue("ulongValue", _ulongValue);
  3438. }
  3439. }
  3440. #if DEBUG
  3441. [Test]
  3442. public void SerializeISerializableInPartialTrustWithIgnoreInterface()
  3443. {
  3444. try
  3445. {
  3446. JsonTypeReflector.SetFullyTrusted(false);
  3447. ISerializableTestObject value = new ISerializableTestObject("string!", 0, default(DateTimeOffset), null);
  3448. string json = JsonConvert.SerializeObject(value, new JsonSerializerSettings
  3449. {
  3450. ContractResolver = new DefaultContractResolver(false)
  3451. {
  3452. IgnoreSerializableInterface = true
  3453. }
  3454. });
  3455. Assert.AreEqual("{}", json);
  3456. value = JsonConvert.DeserializeObject<ISerializableTestObject>("{booleanValue:true}", new JsonSerializerSettings
  3457. {
  3458. ContractResolver = new DefaultContractResolver(false)
  3459. {
  3460. IgnoreSerializableInterface = true
  3461. }
  3462. });
  3463. Assert.IsNotNull(value);
  3464. Assert.AreEqual(false, value._booleanValue);
  3465. }
  3466. finally
  3467. {
  3468. JsonTypeReflector.SetFullyTrusted(true);
  3469. }
  3470. }
  3471. [Test]
  3472. public void SerializeISerializableInPartialTrust()
  3473. {
  3474. try
  3475. {
  3476. ExceptionAssert.Throws<JsonSerializationException>(
  3477. @"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.
  3478. 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.
  3479. Path 'booleanValue', line 1, position 14.",
  3480. () =>
  3481. {
  3482. JsonTypeReflector.SetFullyTrusted(false);
  3483. JsonConvert.DeserializeObject<ISerializableTestObject>("{booleanValue:true}");
  3484. });
  3485. }
  3486. finally
  3487. {
  3488. JsonTypeReflector.SetFullyTrusted(true);
  3489. }
  3490. }
  3491. [Test]
  3492. public void DeserializeISerializableInPartialTrust()
  3493. {
  3494. try
  3495. {
  3496. ExceptionAssert.Throws<JsonSerializationException>(
  3497. @"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.
  3498. 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 ''.",
  3499. () =>
  3500. {
  3501. JsonTypeReflector.SetFullyTrusted(false);
  3502. ISerializableTestObject value = new ISerializableTestObject("string!", 0, default(DateTimeOffset), null);
  3503. JsonConvert.SerializeObject(value);
  3504. });
  3505. }
  3506. finally
  3507. {
  3508. JsonTypeReflector.SetFullyTrusted(true);
  3509. }
  3510. }
  3511. #endif
  3512. [Test]
  3513. public void SerializeISerializableTestObject_IsoDate()
  3514. {
  3515. Person person = new Person();
  3516. person.BirthDate = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
  3517. person.LastModified = person.BirthDate;
  3518. person.Department = "Department!";
  3519. person.Name = "Name!";
  3520. DateTimeOffset dateTimeOffset = new DateTimeOffset(2000, 12, 20, 22, 59, 59, TimeSpan.FromHours(2));
  3521. string dateTimeOffsetText;
  3522. #if !NET20
  3523. dateTimeOffsetText = @"2000-12-20T22:59:59+02:00";
  3524. #else
  3525. dateTimeOffsetText = @"12/20/2000 22:59:59 +02:00";
  3526. #endif
  3527. ISerializableTestObject o = new ISerializableTestObject("String!", int.MinValue, dateTimeOffset, person);
  3528. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  3529. Assert.AreEqual(@"{
  3530. ""stringValue"": ""String!"",
  3531. ""intValue"": -2147483648,
  3532. ""dateTimeOffsetValue"": """ + dateTimeOffsetText + @""",
  3533. ""personValue"": {
  3534. ""Name"": ""Name!"",
  3535. ""BirthDate"": ""2000-01-01T01:01:01Z"",
  3536. ""LastModified"": ""2000-01-01T01:01:01Z""
  3537. },
  3538. ""nullPersonValue"": null,
  3539. ""nullableInt"": null,
  3540. ""booleanValue"": false,
  3541. ""byteValue"": 0,
  3542. ""charValue"": ""\u0000"",
  3543. ""dateTimeValue"": ""0001-01-01T00:00:00Z"",
  3544. ""decimalValue"": 0.0,
  3545. ""shortValue"": 0,
  3546. ""longValue"": 0,
  3547. ""sbyteValue"": 0,
  3548. ""floatValue"": 0.0,
  3549. ""ushortValue"": 0,
  3550. ""uintValue"": 0,
  3551. ""ulongValue"": 0
  3552. }", json);
  3553. ISerializableTestObject o2 = JsonConvert.DeserializeObject<ISerializableTestObject>(json);
  3554. Assert.AreEqual("String!", o2._stringValue);
  3555. Assert.AreEqual(int.MinValue, o2._intValue);
  3556. Assert.AreEqual(dateTimeOffset, o2._dateTimeOffsetValue);
  3557. Assert.AreEqual("Name!", o2._personValue.Name);
  3558. Assert.AreEqual(null, o2._nullPersonValue);
  3559. Assert.AreEqual(null, o2._nullableInt);
  3560. }
  3561. [Test]
  3562. public void SerializeISerializableTestObject_MsAjax()
  3563. {
  3564. Person person = new Person();
  3565. person.BirthDate = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
  3566. person.LastModified = person.BirthDate;
  3567. person.Department = "Department!";
  3568. person.Name = "Name!";
  3569. DateTimeOffset dateTimeOffset = new DateTimeOffset(2000, 12, 20, 22, 59, 59, TimeSpan.FromHours(2));
  3570. string dateTimeOffsetText;
  3571. #if !NET20
  3572. dateTimeOffsetText = @"\/Date(977345999000+0200)\/";
  3573. #else
  3574. dateTimeOffsetText = @"12/20/2000 22:59:59 +02:00";
  3575. #endif
  3576. ISerializableTestObject o = new ISerializableTestObject("String!", int.MinValue, dateTimeOffset, person);
  3577. string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
  3578. {
  3579. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  3580. });
  3581. Assert.AreEqual(@"{
  3582. ""stringValue"": ""String!"",
  3583. ""intValue"": -2147483648,
  3584. ""dateTimeOffsetValue"": """ + dateTimeOffsetText + @""",
  3585. ""personValue"": {
  3586. ""Name"": ""Name!"",
  3587. ""BirthDate"": ""\/Date(946688461000)\/"",
  3588. ""LastModified"": ""\/Date(946688461000)\/""
  3589. },
  3590. ""nullPersonValue"": null,
  3591. ""nullableInt"": null,
  3592. ""booleanValue"": false,
  3593. ""byteValue"": 0,
  3594. ""charValue"": ""\u0000"",
  3595. ""dateTimeValue"": ""\/Date(-62135596800000)\/"",
  3596. ""decimalValue"": 0.0,
  3597. ""shortValue"": 0,
  3598. ""longValue"": 0,
  3599. ""sbyteValue"": 0,
  3600. ""floatValue"": 0.0,
  3601. ""ushortValue"": 0,
  3602. ""uintValue"": 0,
  3603. ""ulongValue"": 0
  3604. }", json);
  3605. ISerializableTestObject o2 = JsonConvert.DeserializeObject<ISerializableTestObject>(json);
  3606. Assert.AreEqual("String!", o2._stringValue);
  3607. Assert.AreEqual(int.MinValue, o2._intValue);
  3608. Assert.AreEqual(dateTimeOffset, o2._dateTimeOffsetValue);
  3609. Assert.AreEqual("Name!", o2._personValue.Name);
  3610. Assert.AreEqual(null, o2._nullPersonValue);
  3611. Assert.AreEqual(null, o2._nullableInt);
  3612. }
  3613. #endif
  3614. public class KVPair<TKey, TValue>
  3615. {
  3616. public TKey Key { get; set; }
  3617. public TValue Value { get; set; }
  3618. public KVPair(TKey k, TValue v)
  3619. {
  3620. Key = k;
  3621. Value = v;
  3622. }
  3623. }
  3624. [Test]
  3625. public void DeserializeUsingNonDefaultConstructorWithLeftOverValues()
  3626. {
  3627. List<KVPair<string, string>> kvPairs =
  3628. JsonConvert.DeserializeObject<List<KVPair<string, string>>>(
  3629. "[{\"Key\":\"Two\",\"Value\":\"2\"},{\"Key\":\"One\",\"Value\":\"1\"}]");
  3630. Assert.AreEqual(2, kvPairs.Count);
  3631. Assert.AreEqual("Two", kvPairs[0].Key);
  3632. Assert.AreEqual("2", kvPairs[0].Value);
  3633. Assert.AreEqual("One", kvPairs[1].Key);
  3634. Assert.AreEqual("1", kvPairs[1].Value);
  3635. }
  3636. [Test]
  3637. public void SerializeClassWithInheritedProtectedMember()
  3638. {
  3639. AA myA = new AA(2);
  3640. string json = JsonConvert.SerializeObject(myA, Formatting.Indented);
  3641. Assert.AreEqual(@"{
  3642. ""AA_field1"": 2,
  3643. ""AA_property1"": 2,
  3644. ""AA_property2"": 2,
  3645. ""AA_property3"": 2,
  3646. ""AA_property4"": 2
  3647. }", json);
  3648. BB myB = new BB(3, 4);
  3649. json = JsonConvert.SerializeObject(myB, Formatting.Indented);
  3650. Assert.AreEqual(@"{
  3651. ""BB_field1"": 4,
  3652. ""BB_field2"": 4,
  3653. ""AA_field1"": 3,
  3654. ""BB_property1"": 4,
  3655. ""BB_property2"": 4,
  3656. ""BB_property3"": 4,
  3657. ""BB_property4"": 4,
  3658. ""BB_property5"": 4,
  3659. ""BB_property7"": 4,
  3660. ""AA_property1"": 3,
  3661. ""AA_property2"": 3,
  3662. ""AA_property3"": 3,
  3663. ""AA_property4"": 3
  3664. }", json);
  3665. }
  3666. #if !PORTABLE
  3667. [Test]
  3668. public void DeserializeClassWithInheritedProtectedMember()
  3669. {
  3670. AA myA = JsonConvert.DeserializeObject<AA>(
  3671. @"{
  3672. ""AA_field1"": 2,
  3673. ""AA_field2"": 2,
  3674. ""AA_property1"": 2,
  3675. ""AA_property2"": 2,
  3676. ""AA_property3"": 2,
  3677. ""AA_property4"": 2,
  3678. ""AA_property5"": 2,
  3679. ""AA_property6"": 2
  3680. }");
  3681. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field1", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  3682. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field2", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  3683. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property1", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  3684. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property2", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  3685. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property3", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  3686. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property4", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  3687. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property5", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  3688. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property6", BindingFlags.Instance | BindingFlags.NonPublic), myA));
  3689. BB myB = JsonConvert.DeserializeObject<BB>(
  3690. @"{
  3691. ""BB_field1"": 4,
  3692. ""BB_field2"": 4,
  3693. ""AA_field1"": 3,
  3694. ""AA_field2"": 3,
  3695. ""AA_property1"": 2,
  3696. ""AA_property2"": 2,
  3697. ""AA_property3"": 2,
  3698. ""AA_property4"": 2,
  3699. ""AA_property5"": 2,
  3700. ""AA_property6"": 2,
  3701. ""BB_property1"": 3,
  3702. ""BB_property2"": 3,
  3703. ""BB_property3"": 3,
  3704. ""BB_property4"": 3,
  3705. ""BB_property5"": 3,
  3706. ""BB_property6"": 3,
  3707. ""BB_property7"": 3,
  3708. ""BB_property8"": 3
  3709. }");
  3710. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field1", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  3711. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetField("AA_field2", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  3712. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property1", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  3713. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property2", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  3714. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property3", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  3715. Assert.AreEqual(2, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property4", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  3716. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property5", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  3717. Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(AA).GetProperty("AA_property6", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  3718. Assert.AreEqual(4, myB.BB_field1);
  3719. Assert.AreEqual(4, myB.BB_field2);
  3720. Assert.AreEqual(3, myB.BB_property1);
  3721. Assert.AreEqual(3, myB.BB_property2);
  3722. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property3", BindingFlags.Instance | BindingFlags.Public), myB));
  3723. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property4", BindingFlags.Instance | BindingFlags.NonPublic), myB));
  3724. Assert.AreEqual(0, myB.BB_property5);
  3725. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property6", BindingFlags.Instance | BindingFlags.Public), myB));
  3726. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property7", BindingFlags.Instance | BindingFlags.Public), myB));
  3727. Assert.AreEqual(3, ReflectionUtils.GetMemberValue(typeof(BB).GetProperty("BB_property8", BindingFlags.Instance | BindingFlags.Public), myB));
  3728. }
  3729. #endif
  3730. public class AA
  3731. {
  3732. [JsonProperty]
  3733. protected int AA_field1;
  3734. protected int AA_field2;
  3735. [JsonProperty]
  3736. protected int AA_property1 { get; set; }
  3737. [JsonProperty]
  3738. protected int AA_property2 { get; private set; }
  3739. [JsonProperty]
  3740. protected int AA_property3 { private get; set; }
  3741. [JsonProperty]
  3742. private int AA_property4 { get; set; }
  3743. protected int AA_property5 { get; private set; }
  3744. protected int AA_property6 { private get; set; }
  3745. public AA()
  3746. {
  3747. }
  3748. public AA(int f)
  3749. {
  3750. AA_field1 = f;
  3751. AA_field2 = f;
  3752. AA_property1 = f;
  3753. AA_property2 = f;
  3754. AA_property3 = f;
  3755. AA_property4 = f;
  3756. AA_property5 = f;
  3757. AA_property6 = f;
  3758. }
  3759. }
  3760. public class BB : AA
  3761. {
  3762. [JsonProperty]
  3763. public int BB_field1;
  3764. public int BB_field2;
  3765. [JsonProperty]
  3766. public int BB_property1 { get; set; }
  3767. [JsonProperty]
  3768. public int BB_property2 { get; private set; }
  3769. [JsonProperty]
  3770. public int BB_property3 { private get; set; }
  3771. [JsonProperty]
  3772. private int BB_property4 { get; set; }
  3773. public int BB_property5 { get; private set; }
  3774. public int BB_property6 { private get; set; }
  3775. [JsonProperty]
  3776. public int BB_property7 { protected get; set; }
  3777. public int BB_property8 { protected get; set; }
  3778. public BB()
  3779. {
  3780. }
  3781. public BB(int f, int g)
  3782. : base(f)
  3783. {
  3784. BB_field1 = g;
  3785. BB_field2 = g;
  3786. BB_property1 = g;
  3787. BB_property2 = g;
  3788. BB_property3 = g;
  3789. BB_property4 = g;
  3790. BB_property5 = g;
  3791. BB_property6 = g;
  3792. BB_property7 = g;
  3793. BB_property8 = g;
  3794. }
  3795. }
  3796. #if !NET20 && !SILVERLIGHT
  3797. public class XNodeTestObject
  3798. {
  3799. public XDocument Document { get; set; }
  3800. public XElement Element { get; set; }
  3801. }
  3802. #endif
  3803. #if !SILVERLIGHT && !NETFX_CORE
  3804. public class XmlNodeTestObject
  3805. {
  3806. public XmlDocument Document { get; set; }
  3807. }
  3808. #endif
  3809. #if !(NET20 || SILVERLIGHT || PORTABLE40)
  3810. [Test]
  3811. public void SerializeDeserializeXNodeProperties()
  3812. {
  3813. XNodeTestObject testObject = new XNodeTestObject();
  3814. testObject.Document = XDocument.Parse("<root>hehe, root</root>");
  3815. testObject.Element = XElement.Parse(@"<fifth xmlns:json=""http://json.org"" json:Awesome=""true"">element</fifth>");
  3816. string json = JsonConvert.SerializeObject(testObject, Formatting.Indented);
  3817. string expected = @"{
  3818. ""Document"": {
  3819. ""root"": ""hehe, root""
  3820. },
  3821. ""Element"": {
  3822. ""fifth"": {
  3823. ""@xmlns:json"": ""http://json.org"",
  3824. ""@json:Awesome"": ""true"",
  3825. ""#text"": ""element""
  3826. }
  3827. }
  3828. }";
  3829. Assert.AreEqual(expected, json);
  3830. XNodeTestObject newTestObject = JsonConvert.DeserializeObject<XNodeTestObject>(json);
  3831. Assert.AreEqual(testObject.Document.ToString(), newTestObject.Document.ToString());
  3832. Assert.AreEqual(testObject.Element.ToString(), newTestObject.Element.ToString());
  3833. Assert.IsNull(newTestObject.Element.Parent);
  3834. }
  3835. #endif
  3836. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40)
  3837. [Test]
  3838. public void SerializeDeserializeXmlNodeProperties()
  3839. {
  3840. XmlNodeTestObject testObject = new XmlNodeTestObject();
  3841. XmlDocument document = new XmlDocument();
  3842. document.LoadXml("<root>hehe, root</root>");
  3843. testObject.Document = document;
  3844. string json = JsonConvert.SerializeObject(testObject, Formatting.Indented);
  3845. string expected = @"{
  3846. ""Document"": {
  3847. ""root"": ""hehe, root""
  3848. }
  3849. }";
  3850. Assert.AreEqual(expected, json);
  3851. XmlNodeTestObject newTestObject = JsonConvert.DeserializeObject<XmlNodeTestObject>(json);
  3852. Assert.AreEqual(testObject.Document.InnerXml, newTestObject.Document.InnerXml);
  3853. }
  3854. #endif
  3855. [Test]
  3856. public void FullClientMapSerialization()
  3857. {
  3858. ClientMap source = new ClientMap()
  3859. {
  3860. position = new Pos() { X = 100, Y = 200 },
  3861. center = new PosDouble() { X = 251.6, Y = 361.3 }
  3862. };
  3863. string json = JsonConvert.SerializeObject(source, new PosConverter(), new PosDoubleConverter());
  3864. Assert.AreEqual("{\"position\":new Pos(100,200),\"center\":new PosD(251.6,361.3)}", json);
  3865. }
  3866. public class ClientMap
  3867. {
  3868. public Pos position { get; set; }
  3869. public PosDouble center { get; set; }
  3870. }
  3871. public class Pos
  3872. {
  3873. public int X { get; set; }
  3874. public int Y { get; set; }
  3875. }
  3876. public class PosDouble
  3877. {
  3878. public double X { get; set; }
  3879. public double Y { get; set; }
  3880. }
  3881. public class PosConverter : JsonConverter
  3882. {
  3883. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  3884. {
  3885. Pos p = (Pos)value;
  3886. if (p != null)
  3887. writer.WriteRawValue(String.Format("new Pos({0},{1})", p.X, p.Y));
  3888. else
  3889. writer.WriteNull();
  3890. }
  3891. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  3892. {
  3893. throw new NotImplementedException();
  3894. }
  3895. public override bool CanConvert(Type objectType)
  3896. {
  3897. return objectType.IsAssignableFrom(typeof(Pos));
  3898. }
  3899. }
  3900. public class PosDoubleConverter : JsonConverter
  3901. {
  3902. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  3903. {
  3904. PosDouble p = (PosDouble)value;
  3905. if (p != null)
  3906. writer.WriteRawValue(String.Format(CultureInfo.InvariantCulture, "new PosD({0},{1})", p.X, p.Y));
  3907. else
  3908. writer.WriteNull();
  3909. }
  3910. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  3911. {
  3912. throw new NotImplementedException();
  3913. }
  3914. public override bool CanConvert(Type objectType)
  3915. {
  3916. return objectType.IsAssignableFrom(typeof(PosDouble));
  3917. }
  3918. }
  3919. [Test]
  3920. public void TestEscapeDictionaryStrings()
  3921. {
  3922. const string s = @"host\user";
  3923. string serialized = JsonConvert.SerializeObject(s);
  3924. Assert.AreEqual(@"""host\\user""", serialized);
  3925. Dictionary<int, object> d1 = new Dictionary<int, object>();
  3926. d1.Add(5, s);
  3927. Assert.AreEqual(@"{""5"":""host\\user""}", JsonConvert.SerializeObject(d1));
  3928. Dictionary<string, object> d2 = new Dictionary<string, object>();
  3929. d2.Add(s, 5);
  3930. Assert.AreEqual(@"{""host\\user"":5}", JsonConvert.SerializeObject(d2));
  3931. }
  3932. public class GenericListTestClass
  3933. {
  3934. public List<string> GenericList { get; set; }
  3935. public GenericListTestClass()
  3936. {
  3937. GenericList = new List<string>();
  3938. }
  3939. }
  3940. [Test]
  3941. public void DeserializeExistingGenericList()
  3942. {
  3943. GenericListTestClass c = new GenericListTestClass();
  3944. c.GenericList.Add("1");
  3945. c.GenericList.Add("2");
  3946. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  3947. GenericListTestClass newValue = JsonConvert.DeserializeObject<GenericListTestClass>(json);
  3948. Assert.AreEqual(2, newValue.GenericList.Count);
  3949. Assert.AreEqual(typeof(List<string>), newValue.GenericList.GetType());
  3950. }
  3951. [Test]
  3952. public void DeserializeSimpleKeyValuePair()
  3953. {
  3954. List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
  3955. list.Add(new KeyValuePair<string, string>("key1", "value1"));
  3956. list.Add(new KeyValuePair<string, string>("key2", "value2"));
  3957. string json = JsonConvert.SerializeObject(list);
  3958. Assert.AreEqual(@"[{""Key"":""key1"",""Value"":""value1""},{""Key"":""key2"",""Value"":""value2""}]", json);
  3959. List<KeyValuePair<string, string>> result = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(json);
  3960. Assert.AreEqual(2, result.Count);
  3961. Assert.AreEqual("key1", result[0].Key);
  3962. Assert.AreEqual("value1", result[0].Value);
  3963. Assert.AreEqual("key2", result[1].Key);
  3964. Assert.AreEqual("value2", result[1].Value);
  3965. }
  3966. [Test]
  3967. public void DeserializeComplexKeyValuePair()
  3968. {
  3969. DateTime dateTime = new DateTime(2000, 12, 1, 23, 1, 1, DateTimeKind.Utc);
  3970. List<KeyValuePair<string, WagePerson>> list = new List<KeyValuePair<string, WagePerson>>();
  3971. list.Add(new KeyValuePair<string, WagePerson>("key1", new WagePerson
  3972. {
  3973. BirthDate = dateTime,
  3974. Department = "Department1",
  3975. LastModified = dateTime,
  3976. HourlyWage = 1
  3977. }));
  3978. list.Add(new KeyValuePair<string, WagePerson>("key2", new WagePerson
  3979. {
  3980. BirthDate = dateTime,
  3981. Department = "Department2",
  3982. LastModified = dateTime,
  3983. HourlyWage = 2
  3984. }));
  3985. string json = JsonConvert.SerializeObject(list, Formatting.Indented);
  3986. Assert.AreEqual(@"[
  3987. {
  3988. ""Key"": ""key1"",
  3989. ""Value"": {
  3990. ""HourlyWage"": 1.0,
  3991. ""Name"": null,
  3992. ""BirthDate"": ""2000-12-01T23:01:01Z"",
  3993. ""LastModified"": ""2000-12-01T23:01:01Z""
  3994. }
  3995. },
  3996. {
  3997. ""Key"": ""key2"",
  3998. ""Value"": {
  3999. ""HourlyWage"": 2.0,
  4000. ""Name"": null,
  4001. ""BirthDate"": ""2000-12-01T23:01:01Z"",
  4002. ""LastModified"": ""2000-12-01T23:01:01Z""
  4003. }
  4004. }
  4005. ]", json);
  4006. List<KeyValuePair<string, WagePerson>> result = JsonConvert.DeserializeObject<List<KeyValuePair<string, WagePerson>>>(json);
  4007. Assert.AreEqual(2, result.Count);
  4008. Assert.AreEqual("key1", result[0].Key);
  4009. Assert.AreEqual(1, result[0].Value.HourlyWage);
  4010. Assert.AreEqual("key2", result[1].Key);
  4011. Assert.AreEqual(2, result[1].Value.HourlyWage);
  4012. }
  4013. public class StringListAppenderConverter : JsonConverter
  4014. {
  4015. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  4016. {
  4017. writer.WriteValue(value);
  4018. }
  4019. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  4020. {
  4021. List<string> existingStrings = (List<string>)existingValue;
  4022. List<string> newStrings = new List<string>(existingStrings);
  4023. reader.Read();
  4024. while (reader.TokenType != JsonToken.EndArray)
  4025. {
  4026. string s = (string)reader.Value;
  4027. newStrings.Add(s);
  4028. reader.Read();
  4029. }
  4030. return newStrings;
  4031. }
  4032. public override bool CanConvert(Type objectType)
  4033. {
  4034. return (objectType == typeof(List<string>));
  4035. }
  4036. }
  4037. [Test]
  4038. public void StringListAppenderConverterTest()
  4039. {
  4040. Movie p = new Movie();
  4041. p.ReleaseCountries = new List<string> { "Existing" };
  4042. JsonConvert.PopulateObject("{'ReleaseCountries':['Appended']}", p, new JsonSerializerSettings
  4043. {
  4044. Converters = new List<JsonConverter> { new StringListAppenderConverter() }
  4045. });
  4046. Assert.AreEqual(2, p.ReleaseCountries.Count);
  4047. Assert.AreEqual("Existing", p.ReleaseCountries[0]);
  4048. Assert.AreEqual("Appended", p.ReleaseCountries[1]);
  4049. }
  4050. public class StringAppenderConverter : JsonConverter
  4051. {
  4052. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  4053. {
  4054. writer.WriteValue(value);
  4055. }
  4056. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  4057. {
  4058. string existingString = (string)existingValue;
  4059. string newString = existingString + (string)reader.Value;
  4060. return newString;
  4061. }
  4062. public override bool CanConvert(Type objectType)
  4063. {
  4064. return (objectType == typeof(string));
  4065. }
  4066. }
  4067. [Test]
  4068. public void StringAppenderConverterTest()
  4069. {
  4070. Movie p = new Movie();
  4071. p.Name = "Existing,";
  4072. JsonConvert.PopulateObject("{'Name':'Appended'}", p, new JsonSerializerSettings
  4073. {
  4074. Converters = new List<JsonConverter> { new StringAppenderConverter() }
  4075. });
  4076. Assert.AreEqual("Existing,Appended", p.Name);
  4077. }
  4078. [Test]
  4079. public void SerializeRefAdditionalContent()
  4080. {
  4081. //Additional text found in JSON string after finishing deserializing object.
  4082. //Test 1
  4083. var reference = new Dictionary<string, object>();
  4084. reference.Add("$ref", "Persons");
  4085. reference.Add("$id", 1);
  4086. var child = new Dictionary<string, object>();
  4087. child.Add("_id", 2);
  4088. child.Add("Name", "Isabell");
  4089. child.Add("Father", reference);
  4090. var json = JsonConvert.SerializeObject(child, Formatting.Indented);
  4091. ExceptionAssert.Throws<JsonSerializationException>(
  4092. "Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Path 'Father.$id', line 6, position 11.",
  4093. () =>
  4094. {
  4095. JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  4096. });
  4097. }
  4098. [Test]
  4099. public void SerializeRefBadType()
  4100. {
  4101. ExceptionAssert.Throws<JsonSerializationException>(
  4102. "JSON reference $ref property must have a string or null value. Path 'Father.$ref', line 5, position 14.",
  4103. () =>
  4104. {
  4105. //Additional text found in JSON string after finishing deserializing object.
  4106. //Test 1
  4107. var reference = new Dictionary<string, object>();
  4108. reference.Add("$ref", 1);
  4109. reference.Add("$id", 1);
  4110. var child = new Dictionary<string, object>();
  4111. child.Add("_id", 2);
  4112. child.Add("Name", "Isabell");
  4113. child.Add("Father", reference);
  4114. var json = JsonConvert.SerializeObject(child, Formatting.Indented);
  4115. JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  4116. });
  4117. }
  4118. [Test]
  4119. public void SerializeRefNull()
  4120. {
  4121. var reference = new Dictionary<string, object>();
  4122. reference.Add("$ref", null);
  4123. reference.Add("$id", null);
  4124. reference.Add("blah", "blah!");
  4125. var child = new Dictionary<string, object>();
  4126. child.Add("_id", 2);
  4127. child.Add("Name", "Isabell");
  4128. child.Add("Father", reference);
  4129. var json = JsonConvert.SerializeObject(child);
  4130. Dictionary<string, object> result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  4131. Assert.AreEqual(3, result.Count);
  4132. Assert.AreEqual(1, ((JObject)result["Father"]).Count);
  4133. Assert.AreEqual("blah!", (string)((JObject)result["Father"])["blah"]);
  4134. }
  4135. public class ConstructorCompexIgnoredProperty
  4136. {
  4137. [JsonIgnore]
  4138. public Product Ignored { get; set; }
  4139. public string First { get; set; }
  4140. public int Second { get; set; }
  4141. public ConstructorCompexIgnoredProperty(string first, int second)
  4142. {
  4143. First = first;
  4144. Second = second;
  4145. }
  4146. }
  4147. [Test]
  4148. public void DeserializeIgnoredPropertyInConstructor()
  4149. {
  4150. string json = @"{""First"":""First"",""Second"":2,""Ignored"":{""Name"":""James""},""AdditionalContent"":{""LOL"":true}}";
  4151. ConstructorCompexIgnoredProperty cc = JsonConvert.DeserializeObject<ConstructorCompexIgnoredProperty>(json);
  4152. Assert.AreEqual("First", cc.First);
  4153. Assert.AreEqual(2, cc.Second);
  4154. Assert.AreEqual(null, cc.Ignored);
  4155. }
  4156. [Test]
  4157. public void DeserializeFloatAsDecimal()
  4158. {
  4159. string json = @"{'value':9.9}";
  4160. var dic = JsonConvert.DeserializeObject<IDictionary<string, object>>(
  4161. json, new JsonSerializerSettings
  4162. {
  4163. FloatParseHandling = FloatParseHandling.Decimal
  4164. });
  4165. Assert.AreEqual(typeof(decimal), dic["value"].GetType());
  4166. Assert.AreEqual(9.9m, dic["value"]);
  4167. }
  4168. [Test]
  4169. public void ShouldSerializeTest()
  4170. {
  4171. ShouldSerializeTestClass c = new ShouldSerializeTestClass();
  4172. c.Name = "James";
  4173. c.Age = 27;
  4174. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  4175. Assert.AreEqual(@"{
  4176. ""Age"": 27
  4177. }", json);
  4178. c._shouldSerializeName = true;
  4179. json = JsonConvert.SerializeObject(c, Formatting.Indented);
  4180. Assert.AreEqual(@"{
  4181. ""Name"": ""James"",
  4182. ""Age"": 27
  4183. }", json);
  4184. ShouldSerializeTestClass deserialized = JsonConvert.DeserializeObject<ShouldSerializeTestClass>(json);
  4185. Assert.AreEqual("James", deserialized.Name);
  4186. Assert.AreEqual(27, deserialized.Age);
  4187. }
  4188. public class Employee
  4189. {
  4190. public string Name { get; set; }
  4191. public Employee Manager { get; set; }
  4192. public bool ShouldSerializeManager()
  4193. {
  4194. return (Manager != this);
  4195. }
  4196. }
  4197. [Test]
  4198. public void ShouldSerializeExample()
  4199. {
  4200. Employee joe = new Employee();
  4201. joe.Name = "Joe Employee";
  4202. Employee mike = new Employee();
  4203. mike.Name = "Mike Manager";
  4204. joe.Manager = mike;
  4205. mike.Manager = mike;
  4206. string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented);
  4207. // [
  4208. // {
  4209. // "Name": "Joe Employee",
  4210. // "Manager": {
  4211. // "Name": "Mike Manager"
  4212. // }
  4213. // },
  4214. // {
  4215. // "Name": "Mike Manager"
  4216. // }
  4217. // ]
  4218. Console.WriteLine(json);
  4219. }
  4220. [Test]
  4221. public void SpecifiedTest()
  4222. {
  4223. SpecifiedTestClass c = new SpecifiedTestClass();
  4224. c.Name = "James";
  4225. c.Age = 27;
  4226. c.NameSpecified = false;
  4227. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  4228. Assert.AreEqual(@"{
  4229. ""Age"": 27
  4230. }", json);
  4231. SpecifiedTestClass deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json);
  4232. Assert.IsNull(deserialized.Name);
  4233. Assert.IsFalse(deserialized.NameSpecified);
  4234. Assert.IsFalse(deserialized.WeightSpecified);
  4235. Assert.IsFalse(deserialized.HeightSpecified);
  4236. Assert.IsFalse(deserialized.FavoriteNumberSpecified);
  4237. Assert.AreEqual(27, deserialized.Age);
  4238. c.NameSpecified = true;
  4239. c.WeightSpecified = true;
  4240. c.HeightSpecified = true;
  4241. c.FavoriteNumber = 23;
  4242. json = JsonConvert.SerializeObject(c, Formatting.Indented);
  4243. Assert.AreEqual(@"{
  4244. ""Name"": ""James"",
  4245. ""Age"": 27,
  4246. ""Weight"": 0,
  4247. ""Height"": 0,
  4248. ""FavoriteNumber"": 23
  4249. }", json);
  4250. deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json);
  4251. Assert.AreEqual("James", deserialized.Name);
  4252. Assert.IsTrue(deserialized.NameSpecified);
  4253. Assert.IsTrue(deserialized.WeightSpecified);
  4254. Assert.IsTrue(deserialized.HeightSpecified);
  4255. Assert.IsTrue(deserialized.FavoriteNumberSpecified);
  4256. Assert.AreEqual(27, deserialized.Age);
  4257. Assert.AreEqual(23, deserialized.FavoriteNumber);
  4258. }
  4259. // [Test]
  4260. // public void XmlSerializerSpecifiedTrueTest()
  4261. // {
  4262. // XmlSerializer s = new XmlSerializer(typeof(OptionalOrder));
  4263. // StringWriter sw = new StringWriter();
  4264. // s.Serialize(sw, new OptionalOrder() { FirstOrder = "First", FirstOrderSpecified = true });
  4265. // Console.WriteLine(sw.ToString());
  4266. // string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
  4267. //<OptionalOrder xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  4268. // <FirstOrder>First</FirstOrder>
  4269. //</OptionalOrder>";
  4270. // OptionalOrder o = (OptionalOrder)s.Deserialize(new StringReader(xml));
  4271. // Console.WriteLine(o.FirstOrder);
  4272. // Console.WriteLine(o.FirstOrderSpecified);
  4273. // }
  4274. // [Test]
  4275. // public void XmlSerializerSpecifiedFalseTest()
  4276. // {
  4277. // XmlSerializer s = new XmlSerializer(typeof(OptionalOrder));
  4278. // StringWriter sw = new StringWriter();
  4279. // s.Serialize(sw, new OptionalOrder() { FirstOrder = "First", FirstOrderSpecified = false });
  4280. // Console.WriteLine(sw.ToString());
  4281. // // string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
  4282. // //<OptionalOrder xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  4283. // // <FirstOrder>First</FirstOrder>
  4284. // //</OptionalOrder>";
  4285. // // OptionalOrder o = (OptionalOrder)s.Deserialize(new StringReader(xml));
  4286. // // Console.WriteLine(o.FirstOrder);
  4287. // // Console.WriteLine(o.FirstOrderSpecified);
  4288. // }
  4289. public class OptionalOrder
  4290. {
  4291. // This field shouldn't be serialized
  4292. // if it is uninitialized.
  4293. public string FirstOrder;
  4294. // Use the XmlIgnoreAttribute to ignore the
  4295. // special field named "FirstOrderSpecified".
  4296. [System.Xml.Serialization.XmlIgnoreAttribute]
  4297. public bool FirstOrderSpecified;
  4298. }
  4299. public class FamilyDetails
  4300. {
  4301. public string Name { get; set; }
  4302. public int NumberOfChildren { get; set; }
  4303. [JsonIgnore]
  4304. public bool NumberOfChildrenSpecified { get; set; }
  4305. }
  4306. [Test]
  4307. public void SpecifiedExample()
  4308. {
  4309. FamilyDetails joe = new FamilyDetails();
  4310. joe.Name = "Joe Family Details";
  4311. joe.NumberOfChildren = 4;
  4312. joe.NumberOfChildrenSpecified = true;
  4313. FamilyDetails martha = new FamilyDetails();
  4314. martha.Name = "Martha Family Details";
  4315. martha.NumberOfChildren = 3;
  4316. martha.NumberOfChildrenSpecified = false;
  4317. string json = JsonConvert.SerializeObject(new[] { joe, martha }, Formatting.Indented);
  4318. //[
  4319. // {
  4320. // "Name": "Joe Family Details",
  4321. // "NumberOfChildren": 4
  4322. // },
  4323. // {
  4324. // "Name": "Martha Family Details"
  4325. // }
  4326. //]
  4327. Console.WriteLine(json);
  4328. string mikeString = "{\"Name\": \"Mike Person\"}";
  4329. FamilyDetails mike = JsonConvert.DeserializeObject<FamilyDetails>(mikeString);
  4330. Console.WriteLine("mikeString specifies number of children: {0}", mike.NumberOfChildrenSpecified);
  4331. string mikeFullDisclosureString = "{\"Name\": \"Mike Person\", \"NumberOfChildren\": \"0\"}";
  4332. mike = JsonConvert.DeserializeObject<FamilyDetails>(mikeFullDisclosureString);
  4333. Console.WriteLine("mikeString specifies number of children: {0}", mike.NumberOfChildrenSpecified);
  4334. }
  4335. public class DictionaryKey
  4336. {
  4337. public string Value { get; set; }
  4338. public override string ToString()
  4339. {
  4340. return Value;
  4341. }
  4342. public static implicit operator DictionaryKey(string value)
  4343. {
  4344. return new DictionaryKey() { Value = value };
  4345. }
  4346. }
  4347. [Test]
  4348. public void SerializeDeserializeDictionaryKey()
  4349. {
  4350. Dictionary<DictionaryKey, string> dictionary = new Dictionary<DictionaryKey, string>();
  4351. dictionary.Add(new DictionaryKey() { Value = "First!" }, "First");
  4352. dictionary.Add(new DictionaryKey() { Value = "Second!" }, "Second");
  4353. string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
  4354. Assert.AreEqual(@"{
  4355. ""First!"": ""First"",
  4356. ""Second!"": ""Second""
  4357. }", json);
  4358. Dictionary<DictionaryKey, string> newDictionary =
  4359. JsonConvert.DeserializeObject<Dictionary<DictionaryKey, string>>(json);
  4360. Assert.AreEqual(2, newDictionary.Count);
  4361. }
  4362. [Test]
  4363. public void SerializeNullableArray()
  4364. {
  4365. string jsonText = JsonConvert.SerializeObject(new double?[] { 2.4, 4.3, null }, Formatting.Indented);
  4366. Assert.AreEqual(@"[
  4367. 2.4,
  4368. 4.3,
  4369. null
  4370. ]", jsonText);
  4371. }
  4372. [Test]
  4373. public void DeserializeNullableArray()
  4374. {
  4375. double?[] d = (double?[])JsonConvert.DeserializeObject(@"[
  4376. 2.4,
  4377. 4.3,
  4378. null
  4379. ]", typeof(double?[]));
  4380. Assert.AreEqual(3, d.Length);
  4381. Assert.AreEqual(2.4, d[0]);
  4382. Assert.AreEqual(4.3, d[1]);
  4383. Assert.AreEqual(null, d[2]);
  4384. }
  4385. #if !SILVERLIGHT && !NET20
  4386. [Test]
  4387. public void SerializeHashSet()
  4388. {
  4389. string jsonText = JsonConvert.SerializeObject(new HashSet<string>()
  4390. {
  4391. "One",
  4392. "2",
  4393. "III"
  4394. }, Formatting.Indented);
  4395. Assert.AreEqual(@"[
  4396. ""One"",
  4397. ""2"",
  4398. ""III""
  4399. ]", jsonText);
  4400. HashSet<string> d = JsonConvert.DeserializeObject<HashSet<string>>(jsonText);
  4401. Assert.AreEqual(3, d.Count);
  4402. Assert.IsTrue(d.Contains("One"));
  4403. Assert.IsTrue(d.Contains("2"));
  4404. Assert.IsTrue(d.Contains("III"));
  4405. }
  4406. #endif
  4407. private class MyClass
  4408. {
  4409. public byte[] Prop1 { get; set; }
  4410. public MyClass()
  4411. {
  4412. Prop1 = new byte[0];
  4413. }
  4414. }
  4415. [Test]
  4416. public void DeserializeByteArray()
  4417. {
  4418. JsonSerializer serializer1 = new JsonSerializer();
  4419. serializer1.Converters.Add(new IsoDateTimeConverter());
  4420. serializer1.NullValueHandling = NullValueHandling.Ignore;
  4421. string json = @"[{""Prop1"":""""},{""Prop1"":""""}]";
  4422. JsonTextReader reader = new JsonTextReader(new StringReader(json));
  4423. MyClass[] z = (MyClass[])serializer1.Deserialize(reader, typeof(MyClass[]));
  4424. Assert.AreEqual(2, z.Length);
  4425. Assert.AreEqual(0, z[0].Prop1.Length);
  4426. Assert.AreEqual(0, z[1].Prop1.Length);
  4427. }
  4428. #if !NET20 && !SILVERLIGHT && !NETFX_CORE
  4429. public class StringDictionaryTestClass
  4430. {
  4431. public StringDictionary StringDictionaryProperty { get; set; }
  4432. }
  4433. [Test]
  4434. public void StringDictionaryTest()
  4435. {
  4436. string classRef = typeof(StringDictionary).FullName;
  4437. StringDictionaryTestClass s1 = new StringDictionaryTestClass()
  4438. {
  4439. StringDictionaryProperty = new StringDictionary()
  4440. {
  4441. {"1", "One"},
  4442. {"2", "II"},
  4443. {"3", "3"}
  4444. }
  4445. };
  4446. string json = JsonConvert.SerializeObject(s1, Formatting.Indented);
  4447. ExceptionAssert.Throws<JsonSerializationException>(
  4448. "Cannot create and populate list type " + classRef + ". Path 'StringDictionaryProperty', line 2, position 32.",
  4449. () =>
  4450. {
  4451. JsonConvert.DeserializeObject<StringDictionaryTestClass>(json);
  4452. });
  4453. }
  4454. #endif
  4455. [JsonObject(MemberSerialization.OptIn)]
  4456. public struct StructWithAttribute
  4457. {
  4458. public string MyString { get; set; }
  4459. [JsonProperty]
  4460. public int MyInt { get; set; }
  4461. }
  4462. [Test]
  4463. public void SerializeStructWithJsonObjectAttribute()
  4464. {
  4465. StructWithAttribute testStruct = new StructWithAttribute
  4466. {
  4467. MyInt = int.MaxValue
  4468. };
  4469. string json = JsonConvert.SerializeObject(testStruct, Formatting.Indented);
  4470. Assert.AreEqual(@"{
  4471. ""MyInt"": 2147483647
  4472. }", json);
  4473. StructWithAttribute newStruct = JsonConvert.DeserializeObject<StructWithAttribute>(json);
  4474. Assert.AreEqual(int.MaxValue, newStruct.MyInt);
  4475. }
  4476. public class TimeZoneOffsetObject
  4477. {
  4478. public DateTimeOffset Offset { get; set; }
  4479. }
  4480. #if !NET20
  4481. [Test]
  4482. public void ReadWriteTimeZoneOffsetIso()
  4483. {
  4484. var serializeObject = JsonConvert.SerializeObject(new TimeZoneOffsetObject
  4485. {
  4486. Offset = new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6))
  4487. });
  4488. Assert.AreEqual("{\"Offset\":\"2000-01-01T00:00:00+06:00\"}", serializeObject);
  4489. var deserializeObject = JsonConvert.DeserializeObject<TimeZoneOffsetObject>(serializeObject);
  4490. Assert.AreEqual(TimeSpan.FromHours(6), deserializeObject.Offset.Offset);
  4491. Assert.AreEqual(new DateTime(2000, 1, 1), deserializeObject.Offset.Date);
  4492. }
  4493. [Test]
  4494. public void DeserializePropertyNullableDateTimeOffsetExactIso()
  4495. {
  4496. NullableDateTimeTestClass d = JsonConvert.DeserializeObject<NullableDateTimeTestClass>("{\"DateTimeOffsetField\":\"2000-01-01T00:00:00+06:00\"}");
  4497. Assert.AreEqual(new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6)), d.DateTimeOffsetField);
  4498. }
  4499. [Test]
  4500. public void ReadWriteTimeZoneOffsetMsAjax()
  4501. {
  4502. var serializeObject = JsonConvert.SerializeObject(new TimeZoneOffsetObject
  4503. {
  4504. Offset = new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6))
  4505. }, Formatting.None, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
  4506. Assert.AreEqual("{\"Offset\":\"\\/Date(946663200000+0600)\\/\"}", serializeObject);
  4507. var deserializeObject = JsonConvert.DeserializeObject<TimeZoneOffsetObject>(serializeObject);
  4508. Assert.AreEqual(TimeSpan.FromHours(6), deserializeObject.Offset.Offset);
  4509. Assert.AreEqual(new DateTime(2000, 1, 1), deserializeObject.Offset.Date);
  4510. }
  4511. [Test]
  4512. public void DeserializePropertyNullableDateTimeOffsetExactMsAjax()
  4513. {
  4514. NullableDateTimeTestClass d = JsonConvert.DeserializeObject<NullableDateTimeTestClass>("{\"DateTimeOffsetField\":\"\\/Date(946663200000+0600)\\/\"}");
  4515. Assert.AreEqual(new DateTimeOffset(new DateTime(2000, 1, 1), TimeSpan.FromHours(6)), d.DateTimeOffsetField);
  4516. }
  4517. #endif
  4518. public abstract class LogEvent
  4519. {
  4520. [JsonProperty("event")]
  4521. public abstract string EventName { get; }
  4522. }
  4523. public class DerivedEvent : LogEvent
  4524. {
  4525. public override string EventName
  4526. {
  4527. get { return "derived"; }
  4528. }
  4529. }
  4530. [Test]
  4531. public void OverridenPropertyMembers()
  4532. {
  4533. string json = JsonConvert.SerializeObject(new DerivedEvent(), Formatting.Indented);
  4534. Assert.AreEqual(@"{
  4535. ""event"": ""derived""
  4536. }", json);
  4537. }
  4538. #if !(NET35 || NET20 || PORTABLE40)
  4539. [Test]
  4540. public void SerializeExpandoObject()
  4541. {
  4542. dynamic expando = new ExpandoObject();
  4543. expando.Int = 1;
  4544. expando.Decimal = 99.9d;
  4545. expando.Complex = new ExpandoObject();
  4546. expando.Complex.String = "I am a string";
  4547. expando.Complex.DateTime = new DateTime(2000, 12, 20, 18, 55, 0, DateTimeKind.Utc);
  4548. string json = JsonConvert.SerializeObject(expando, Formatting.Indented);
  4549. Assert.AreEqual(@"{
  4550. ""Int"": 1,
  4551. ""Decimal"": 99.9,
  4552. ""Complex"": {
  4553. ""String"": ""I am a string"",
  4554. ""DateTime"": ""2000-12-20T18:55:00Z""
  4555. }
  4556. }", json);
  4557. IDictionary<string, object> newExpando = JsonConvert.DeserializeObject<ExpandoObject>(json);
  4558. CustomAssert.IsInstanceOfType(typeof(long), newExpando["Int"]);
  4559. Assert.AreEqual((long)expando.Int, newExpando["Int"]);
  4560. CustomAssert.IsInstanceOfType(typeof(double), newExpando["Decimal"]);
  4561. Assert.AreEqual(expando.Decimal, newExpando["Decimal"]);
  4562. CustomAssert.IsInstanceOfType(typeof(ExpandoObject), newExpando["Complex"]);
  4563. IDictionary<string, object> o = (ExpandoObject)newExpando["Complex"];
  4564. CustomAssert.IsInstanceOfType(typeof(string), o["String"]);
  4565. Assert.AreEqual(expando.Complex.String, o["String"]);
  4566. CustomAssert.IsInstanceOfType(typeof(DateTime), o["DateTime"]);
  4567. Assert.AreEqual(expando.Complex.DateTime, o["DateTime"]);
  4568. }
  4569. #endif
  4570. [Test]
  4571. public void DeserializeDecimalExact()
  4572. {
  4573. decimal d = JsonConvert.DeserializeObject<decimal>("123456789876543.21");
  4574. Assert.AreEqual(123456789876543.21m, d);
  4575. }
  4576. [Test]
  4577. public void DeserializeNullableDecimalExact()
  4578. {
  4579. decimal? d = JsonConvert.DeserializeObject<decimal?>("123456789876543.21");
  4580. Assert.AreEqual(123456789876543.21m, d);
  4581. }
  4582. [Test]
  4583. public void DeserializeDecimalPropertyExact()
  4584. {
  4585. string json = "{Amount:123456789876543.21}";
  4586. Invoice i = JsonConvert.DeserializeObject<Invoice>(json);
  4587. Assert.AreEqual(123456789876543.21m, i.Amount);
  4588. }
  4589. [Test]
  4590. public void DeserializeDecimalArrayExact()
  4591. {
  4592. string json = "[123456789876543.21]";
  4593. IList<decimal> a = JsonConvert.DeserializeObject<IList<decimal>>(json);
  4594. Assert.AreEqual(123456789876543.21m, a[0]);
  4595. }
  4596. [Test]
  4597. public void DeserializeDecimalDictionaryExact()
  4598. {
  4599. string json = "{'Value':123456789876543.21}";
  4600. IDictionary<string, decimal> d = JsonConvert.DeserializeObject<IDictionary<string, decimal>>(json);
  4601. Assert.AreEqual(123456789876543.21m, d["Value"]);
  4602. }
  4603. public struct Vector
  4604. {
  4605. public float X;
  4606. public float Y;
  4607. public float Z;
  4608. public override string ToString()
  4609. {
  4610. return string.Format("({0},{1},{2})", X, Y, Z);
  4611. }
  4612. }
  4613. public class VectorParent
  4614. {
  4615. public Vector Position;
  4616. }
  4617. [Test]
  4618. public void DeserializeStructProperty()
  4619. {
  4620. VectorParent obj = new VectorParent();
  4621. obj.Position = new Vector { X = 1, Y = 2, Z = 3 };
  4622. string str = JsonConvert.SerializeObject(obj);
  4623. obj = JsonConvert.DeserializeObject<VectorParent>(str);
  4624. Assert.AreEqual(1, obj.Position.X);
  4625. Assert.AreEqual(2, obj.Position.Y);
  4626. Assert.AreEqual(3, obj.Position.Z);
  4627. }
  4628. [JsonObject(MemberSerialization.OptIn)]
  4629. public class Derived : Base
  4630. {
  4631. [JsonProperty]
  4632. public string IDoWork { get; private set; }
  4633. private Derived()
  4634. {
  4635. }
  4636. internal Derived(string dontWork, string doWork)
  4637. : base(dontWork)
  4638. {
  4639. IDoWork = doWork;
  4640. }
  4641. }
  4642. [JsonObject(MemberSerialization.OptIn)]
  4643. public class Base
  4644. {
  4645. [JsonProperty]
  4646. public string IDontWork { get; private set; }
  4647. protected Base()
  4648. {
  4649. }
  4650. internal Base(string dontWork)
  4651. {
  4652. IDontWork = dontWork;
  4653. }
  4654. }
  4655. [Test]
  4656. public void PrivateSetterOnBaseClassProperty()
  4657. {
  4658. var derived = new Derived("meh", "woo");
  4659. var settings = new JsonSerializerSettings
  4660. {
  4661. TypeNameHandling = TypeNameHandling.Objects,
  4662. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
  4663. };
  4664. string json = JsonConvert.SerializeObject(derived, Formatting.Indented, settings);
  4665. var meh = JsonConvert.DeserializeObject<Base>(json, settings);
  4666. Assert.AreEqual(((Derived)meh).IDoWork, "woo");
  4667. Assert.AreEqual(meh.IDontWork, "meh");
  4668. }
  4669. #if !(SILVERLIGHT || NET20 || NETFX_CORE)
  4670. [DataContract]
  4671. public struct StructISerializable : ISerializable
  4672. {
  4673. private string _name;
  4674. public StructISerializable(SerializationInfo info, StreamingContext context)
  4675. {
  4676. _name = info.GetString("Name");
  4677. }
  4678. [DataMember]
  4679. public string Name
  4680. {
  4681. get { return _name; }
  4682. set { _name = value; }
  4683. }
  4684. public void GetObjectData(SerializationInfo info, StreamingContext context)
  4685. {
  4686. info.AddValue("Name", _name);
  4687. }
  4688. }
  4689. [DataContract]
  4690. public class NullableStructPropertyClass
  4691. {
  4692. private StructISerializable _foo1;
  4693. private StructISerializable? _foo2;
  4694. [DataMember]
  4695. public StructISerializable Foo1
  4696. {
  4697. get { return _foo1; }
  4698. set { _foo1 = value; }
  4699. }
  4700. [DataMember]
  4701. public StructISerializable? Foo2
  4702. {
  4703. get { return _foo2; }
  4704. set { _foo2 = value; }
  4705. }
  4706. }
  4707. [Test]
  4708. public void DeserializeNullableStruct()
  4709. {
  4710. NullableStructPropertyClass nullableStructPropertyClass = new NullableStructPropertyClass();
  4711. nullableStructPropertyClass.Foo1 = new StructISerializable() { Name = "foo 1" };
  4712. nullableStructPropertyClass.Foo2 = new StructISerializable() { Name = "foo 2" };
  4713. NullableStructPropertyClass barWithNull = new NullableStructPropertyClass();
  4714. barWithNull.Foo1 = new StructISerializable() { Name = "foo 1" };
  4715. barWithNull.Foo2 = null;
  4716. //throws error on deserialization because bar1.Foo2 is of type Foo?
  4717. string s = JsonConvert.SerializeObject(nullableStructPropertyClass);
  4718. NullableStructPropertyClass deserialized = deserialize(s);
  4719. Assert.AreEqual(deserialized.Foo1.Name, "foo 1");
  4720. Assert.AreEqual(deserialized.Foo2.Value.Name, "foo 2");
  4721. //no error Foo2 is null
  4722. s = JsonConvert.SerializeObject(barWithNull);
  4723. deserialized = deserialize(s);
  4724. Assert.AreEqual(deserialized.Foo1.Name, "foo 1");
  4725. Assert.AreEqual(deserialized.Foo2, null);
  4726. }
  4727. private static NullableStructPropertyClass deserialize(string serStr)
  4728. {
  4729. return JsonConvert.DeserializeObject<NullableStructPropertyClass>(
  4730. serStr,
  4731. new JsonSerializerSettings
  4732. {
  4733. NullValueHandling = NullValueHandling.Ignore,
  4734. MissingMemberHandling = MissingMemberHandling.Ignore
  4735. });
  4736. }
  4737. #endif
  4738. public class Response
  4739. {
  4740. public string Name { get; set; }
  4741. public JToken Data { get; set; }
  4742. }
  4743. [Test]
  4744. public void DeserializeJToken()
  4745. {
  4746. Response response = new Response
  4747. {
  4748. Name = "Success",
  4749. Data = new JObject(new JProperty("First", "Value1"), new JProperty("Second", "Value2"))
  4750. };
  4751. string json = JsonConvert.SerializeObject(response, Formatting.Indented);
  4752. Response deserializedResponse = JsonConvert.DeserializeObject<Response>(json);
  4753. Assert.AreEqual("Success", deserializedResponse.Name);
  4754. Assert.IsTrue(deserializedResponse.Data.DeepEquals(response.Data));
  4755. }
  4756. public abstract class Test<T>
  4757. {
  4758. public abstract T Value { get; set; }
  4759. }
  4760. [JsonObject(MemberSerialization.OptIn)]
  4761. public class DecimalTest : Test<decimal>
  4762. {
  4763. protected DecimalTest()
  4764. {
  4765. }
  4766. public DecimalTest(decimal val)
  4767. {
  4768. Value = val;
  4769. }
  4770. [JsonProperty]
  4771. public override decimal Value { get; set; }
  4772. }
  4773. [Test]
  4774. public void OnError()
  4775. {
  4776. var data = new DecimalTest(decimal.MinValue);
  4777. var json = JsonConvert.SerializeObject(data);
  4778. var obj = JsonConvert.DeserializeObject<DecimalTest>(json);
  4779. Assert.AreEqual(decimal.MinValue, obj.Value);
  4780. }
  4781. public class NonPublicConstructorWithJsonConstructor
  4782. {
  4783. public string Value { get; private set; }
  4784. public string Constructor { get; private set; }
  4785. [JsonConstructor]
  4786. private NonPublicConstructorWithJsonConstructor()
  4787. {
  4788. Constructor = "NonPublic";
  4789. }
  4790. public NonPublicConstructorWithJsonConstructor(string value)
  4791. {
  4792. Value = value;
  4793. Constructor = "Public Paramatized";
  4794. }
  4795. }
  4796. [Test]
  4797. public void NonPublicConstructorWithJsonConstructorTest()
  4798. {
  4799. NonPublicConstructorWithJsonConstructor c = JsonConvert.DeserializeObject<NonPublicConstructorWithJsonConstructor>("{}");
  4800. Assert.AreEqual("NonPublic", c.Constructor);
  4801. }
  4802. public class PublicConstructorOverridenByJsonConstructor
  4803. {
  4804. public string Value { get; private set; }
  4805. public string Constructor { get; private set; }
  4806. public PublicConstructorOverridenByJsonConstructor()
  4807. {
  4808. Constructor = "NonPublic";
  4809. }
  4810. [JsonConstructor]
  4811. public PublicConstructorOverridenByJsonConstructor(string value)
  4812. {
  4813. Value = value;
  4814. Constructor = "Public Paramatized";
  4815. }
  4816. }
  4817. [Test]
  4818. public void PublicConstructorOverridenByJsonConstructorTest()
  4819. {
  4820. PublicConstructorOverridenByJsonConstructor c = JsonConvert.DeserializeObject<PublicConstructorOverridenByJsonConstructor>("{Value:'value!'}");
  4821. Assert.AreEqual("Public Paramatized", c.Constructor);
  4822. Assert.AreEqual("value!", c.Value);
  4823. }
  4824. public class MultipleParamatrizedConstructorsJsonConstructor
  4825. {
  4826. public string Value { get; private set; }
  4827. public int Age { get; private set; }
  4828. public string Constructor { get; private set; }
  4829. public MultipleParamatrizedConstructorsJsonConstructor(string value)
  4830. {
  4831. Value = value;
  4832. Constructor = "Public Paramatized 1";
  4833. }
  4834. [JsonConstructor]
  4835. public MultipleParamatrizedConstructorsJsonConstructor(string value, int age)
  4836. {
  4837. Value = value;
  4838. Age = age;
  4839. Constructor = "Public Paramatized 2";
  4840. }
  4841. }
  4842. [Test]
  4843. public void MultipleParamatrizedConstructorsJsonConstructorTest()
  4844. {
  4845. MultipleParamatrizedConstructorsJsonConstructor c = JsonConvert.DeserializeObject<MultipleParamatrizedConstructorsJsonConstructor>("{Value:'value!', Age:1}");
  4846. Assert.AreEqual("Public Paramatized 2", c.Constructor);
  4847. Assert.AreEqual("value!", c.Value);
  4848. Assert.AreEqual(1, c.Age);
  4849. }
  4850. public class EnumerableClass
  4851. {
  4852. public IEnumerable<string> Enumerable { get; set; }
  4853. }
  4854. [Test]
  4855. public void DeserializeEnumerable()
  4856. {
  4857. EnumerableClass c = new EnumerableClass
  4858. {
  4859. Enumerable = new List<string> { "One", "Two", "Three" }
  4860. };
  4861. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  4862. Assert.AreEqual(@"{
  4863. ""Enumerable"": [
  4864. ""One"",
  4865. ""Two"",
  4866. ""Three""
  4867. ]
  4868. }", json);
  4869. EnumerableClass c2 = JsonConvert.DeserializeObject<EnumerableClass>(json);
  4870. Assert.AreEqual("One", c2.Enumerable.ElementAt(0));
  4871. Assert.AreEqual("Two", c2.Enumerable.ElementAt(1));
  4872. Assert.AreEqual("Three", c2.Enumerable.ElementAt(2));
  4873. }
  4874. [JsonObject(MemberSerialization.OptIn)]
  4875. public class ItemBase
  4876. {
  4877. [JsonProperty]
  4878. public string Name { get; set; }
  4879. }
  4880. public class ComplexItem : ItemBase
  4881. {
  4882. public Stream Source { get; set; }
  4883. }
  4884. [Test]
  4885. public void SerializeAttributesOnBase()
  4886. {
  4887. ComplexItem i = new ComplexItem();
  4888. string json = JsonConvert.SerializeObject(i, Formatting.Indented);
  4889. Assert.AreEqual(@"{
  4890. ""Name"": null
  4891. }", json);
  4892. }
  4893. public class DeserializeStringConvert
  4894. {
  4895. public string Name { get; set; }
  4896. public int Age { get; set; }
  4897. public double Height { get; set; }
  4898. public decimal Price { get; set; }
  4899. }
  4900. [Test]
  4901. public void DeserializeStringEnglish()
  4902. {
  4903. string json = @"{
  4904. 'Name': 'James Hughes',
  4905. 'Age': '40',
  4906. 'Height': '44.4',
  4907. 'Price': '4'
  4908. }";
  4909. DeserializeStringConvert p = JsonConvert.DeserializeObject<DeserializeStringConvert>(json);
  4910. Assert.AreEqual(40, p.Age);
  4911. Assert.AreEqual(44.4, p.Height);
  4912. Assert.AreEqual(4m, p.Price);
  4913. }
  4914. [Test]
  4915. public void DeserializeNullDateTimeValueTest()
  4916. {
  4917. ExceptionAssert.Throws<JsonSerializationException>(
  4918. "Error converting value {null} to type 'System.DateTime'. Path '', line 1, position 4.",
  4919. () =>
  4920. {
  4921. JsonConvert.DeserializeObject("null", typeof(DateTime));
  4922. });
  4923. }
  4924. [Test]
  4925. public void DeserializeNullNullableDateTimeValueTest()
  4926. {
  4927. object dateTime = JsonConvert.DeserializeObject("null", typeof(DateTime?));
  4928. Assert.IsNull(dateTime);
  4929. }
  4930. [Test]
  4931. public void MultiIndexSuperTest()
  4932. {
  4933. MultiIndexSuper e = new MultiIndexSuper();
  4934. string json = JsonConvert.SerializeObject(e, Formatting.Indented);
  4935. Assert.AreEqual(@"{}", json);
  4936. }
  4937. public class MultiIndexSuper : MultiIndexBase
  4938. {
  4939. }
  4940. public abstract class MultiIndexBase
  4941. {
  4942. protected internal object this[string propertyName]
  4943. {
  4944. get { return null; }
  4945. set { }
  4946. }
  4947. protected internal object this[object property]
  4948. {
  4949. get { return null; }
  4950. set { }
  4951. }
  4952. }
  4953. public class CommentTestClass
  4954. {
  4955. public bool Indexed { get; set; }
  4956. public int StartYear { get; set; }
  4957. public IList<decimal> Values { get; set; }
  4958. }
  4959. [Test]
  4960. public void CommentTestClassTest()
  4961. {
  4962. string json = @"{""indexed"":true, ""startYear"":1939, ""values"":
  4963. [ 3000, /* 1940-1949 */
  4964. 3000, 3600, 3600, 3600, 3600, 4200, 4200, 4200, 4200, 4800, /* 1950-1959 */
  4965. 4800, 4800, 4800, 4800, 4800, 4800, 6600, 6600, 7800, 7800, /* 1960-1969 */
  4966. 7800, 7800, 9000, 10800, 13200, 14100, 15300, 16500, 17700, 22900, /* 1970-1979 */
  4967. 25900, 29700, 32400, 35700, 37800, 39600, 42000, 43800, 45000, 48000, /* 1980-1989 */
  4968. 51300, 53400, 55500, 57600, 60600, 61200, 62700, 65400, 68400, 72600, /* 1990-1999 */
  4969. 76200, 80400, 84900, 87000, 87900, 90000, 94200, 97500, 102000, 106800, /* 2000-2009 */
  4970. 106800, 106800] /* 2010-2011 */
  4971. }";
  4972. CommentTestClass commentTestClass = JsonConvert.DeserializeObject<CommentTestClass>(json);
  4973. Assert.AreEqual(true, commentTestClass.Indexed);
  4974. Assert.AreEqual(1939, commentTestClass.StartYear);
  4975. Assert.AreEqual(63, commentTestClass.Values.Count);
  4976. }
  4977. private class DTOWithParameterisedConstructor
  4978. {
  4979. public DTOWithParameterisedConstructor(string A)
  4980. {
  4981. this.A = A;
  4982. B = 2;
  4983. }
  4984. public string A { get; set; }
  4985. public int? B { get; set; }
  4986. }
  4987. private class DTOWithoutParameterisedConstructor
  4988. {
  4989. public DTOWithoutParameterisedConstructor()
  4990. {
  4991. B = 2;
  4992. }
  4993. public string A { get; set; }
  4994. public int? B { get; set; }
  4995. }
  4996. [Test]
  4997. public void PopulationBehaviourForOmittedPropertiesIsTheSameForParameterisedConstructorAsForDefaultConstructor()
  4998. {
  4999. string json = @"{A:""Test""}";
  5000. var withoutParameterisedConstructor = JsonConvert.DeserializeObject<DTOWithoutParameterisedConstructor>(json);
  5001. var withParameterisedConstructor = JsonConvert.DeserializeObject<DTOWithParameterisedConstructor>(json);
  5002. Assert.AreEqual(withoutParameterisedConstructor.B, withParameterisedConstructor.B);
  5003. }
  5004. public class EnumerableArrayPropertyClass
  5005. {
  5006. public IEnumerable<int> Numbers
  5007. {
  5008. get
  5009. {
  5010. return new[] { 1, 2, 3 }; //fails
  5011. //return new List<int>(new[] { 1, 2, 3 }); //works
  5012. }
  5013. }
  5014. }
  5015. [Test]
  5016. public void SkipPopulatingArrayPropertyClass()
  5017. {
  5018. string json = JsonConvert.SerializeObject(new EnumerableArrayPropertyClass());
  5019. JsonConvert.DeserializeObject<EnumerableArrayPropertyClass>(json);
  5020. }
  5021. #if !(NET20 || SILVERLIGHT)
  5022. [DataContract]
  5023. public class BaseDataContract
  5024. {
  5025. [DataMember(Name = "virtualMember")]
  5026. public virtual string VirtualMember { get; set; }
  5027. [DataMember(Name = "nonVirtualMember")]
  5028. public string NonVirtualMember { get; set; }
  5029. }
  5030. public class ChildDataContract : BaseDataContract
  5031. {
  5032. public override string VirtualMember { get; set; }
  5033. public string NewMember { get; set; }
  5034. }
  5035. [Test]
  5036. public void ChildDataContractTest()
  5037. {
  5038. ChildDataContract cc = new ChildDataContract
  5039. {
  5040. VirtualMember = "VirtualMember!",
  5041. NonVirtualMember = "NonVirtualMember!"
  5042. };
  5043. string result = JsonConvert.SerializeObject(cc, Formatting.Indented);
  5044. // Assert.AreEqual(@"{
  5045. // ""VirtualMember"": ""VirtualMember!"",
  5046. // ""NewMember"": null,
  5047. // ""nonVirtualMember"": ""NonVirtualMember!""
  5048. //}", result);
  5049. Console.WriteLine(result);
  5050. }
  5051. [Test]
  5052. public void ChildDataContractTestWithDataContractSerializer()
  5053. {
  5054. ChildDataContract cc = new ChildDataContract
  5055. {
  5056. VirtualMember = "VirtualMember!",
  5057. NonVirtualMember = "NonVirtualMember!"
  5058. };
  5059. DataContractSerializer serializer = new DataContractSerializer(typeof(ChildDataContract));
  5060. MemoryStream ms = new MemoryStream();
  5061. serializer.WriteObject(ms, cc);
  5062. string xml = Encoding.UTF8.GetString(ms.ToArray(), 0, Convert.ToInt32(ms.Length));
  5063. Console.WriteLine(xml);
  5064. }
  5065. #endif
  5066. [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
  5067. public class BaseObject
  5068. {
  5069. [JsonProperty(PropertyName = "virtualMember")]
  5070. public virtual string VirtualMember { get; set; }
  5071. [JsonProperty(PropertyName = "nonVirtualMember")]
  5072. public string NonVirtualMember { get; set; }
  5073. }
  5074. public class ChildObject : BaseObject
  5075. {
  5076. public override string VirtualMember { get; set; }
  5077. public string NewMember { get; set; }
  5078. }
  5079. public class ChildWithDifferentOverrideObject : BaseObject
  5080. {
  5081. [JsonProperty(PropertyName = "differentVirtualMember")]
  5082. public override string VirtualMember { get; set; }
  5083. }
  5084. [Test]
  5085. public void ChildObjectTest()
  5086. {
  5087. ChildObject cc = new ChildObject
  5088. {
  5089. VirtualMember = "VirtualMember!",
  5090. NonVirtualMember = "NonVirtualMember!"
  5091. };
  5092. string result = JsonConvert.SerializeObject(cc);
  5093. Assert.AreEqual(@"{""virtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  5094. }
  5095. [Test]
  5096. public void ChildWithDifferentOverrideObjectTest()
  5097. {
  5098. ChildWithDifferentOverrideObject cc = new ChildWithDifferentOverrideObject
  5099. {
  5100. VirtualMember = "VirtualMember!",
  5101. NonVirtualMember = "NonVirtualMember!"
  5102. };
  5103. string result = JsonConvert.SerializeObject(cc);
  5104. Console.WriteLine(result);
  5105. Assert.AreEqual(@"{""differentVirtualMember"":""VirtualMember!"",""nonVirtualMember"":""NonVirtualMember!""}", result);
  5106. }
  5107. [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
  5108. public interface IInterfaceObject
  5109. {
  5110. [JsonProperty(PropertyName = "virtualMember")]
  5111. [JsonConverter(typeof(IsoDateTimeConverter))]
  5112. DateTime InterfaceMember { get; set; }
  5113. }
  5114. public class ImplementInterfaceObject : IInterfaceObject
  5115. {
  5116. public DateTime InterfaceMember { get; set; }
  5117. public string NewMember { get; set; }
  5118. [JsonProperty(PropertyName = "newMemberWithProperty")]
  5119. public string NewMemberWithProperty { get; set; }
  5120. }
  5121. [Test]
  5122. public void ImplementInterfaceObjectTest()
  5123. {
  5124. ImplementInterfaceObject cc = new ImplementInterfaceObject
  5125. {
  5126. InterfaceMember = new DateTime(2010, 12, 31, 0, 0, 0, DateTimeKind.Utc),
  5127. NewMember = "NewMember!"
  5128. };
  5129. string result = JsonConvert.SerializeObject(cc, Formatting.Indented);
  5130. Assert.AreEqual(@"{
  5131. ""virtualMember"": ""2010-12-31T00:00:00Z"",
  5132. ""newMemberWithProperty"": null
  5133. }", result);
  5134. }
  5135. public class NonDefaultConstructorWithReadOnlyCollectionProperty
  5136. {
  5137. public string Title { get; set; }
  5138. public IList<string> Categories { get; private set; }
  5139. public NonDefaultConstructorWithReadOnlyCollectionProperty(string title)
  5140. {
  5141. Title = title;
  5142. Categories = new List<string>();
  5143. }
  5144. }
  5145. [Test]
  5146. public void NonDefaultConstructorWithReadOnlyCollectionPropertyTest()
  5147. {
  5148. NonDefaultConstructorWithReadOnlyCollectionProperty c1 = new NonDefaultConstructorWithReadOnlyCollectionProperty("blah");
  5149. c1.Categories.Add("one");
  5150. c1.Categories.Add("two");
  5151. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  5152. Assert.AreEqual(@"{
  5153. ""Title"": ""blah"",
  5154. ""Categories"": [
  5155. ""one"",
  5156. ""two""
  5157. ]
  5158. }", json);
  5159. NonDefaultConstructorWithReadOnlyCollectionProperty c2 = JsonConvert.DeserializeObject<NonDefaultConstructorWithReadOnlyCollectionProperty>(json);
  5160. Assert.AreEqual(c1.Title, c2.Title);
  5161. Assert.AreEqual(c1.Categories.Count, c2.Categories.Count);
  5162. Assert.AreEqual("one", c2.Categories[0]);
  5163. Assert.AreEqual("two", c2.Categories[1]);
  5164. }
  5165. public class NonDefaultConstructorWithReadOnlyDictionaryProperty
  5166. {
  5167. public string Title { get; set; }
  5168. public IDictionary<string, int> Categories { get; private set; }
  5169. public NonDefaultConstructorWithReadOnlyDictionaryProperty(string title)
  5170. {
  5171. Title = title;
  5172. Categories = new Dictionary<string, int>();
  5173. }
  5174. }
  5175. [Test]
  5176. public void NonDefaultConstructorWithReadOnlyDictionaryPropertyTest()
  5177. {
  5178. NonDefaultConstructorWithReadOnlyDictionaryProperty c1 = new NonDefaultConstructorWithReadOnlyDictionaryProperty("blah");
  5179. c1.Categories.Add("one", 1);
  5180. c1.Categories.Add("two", 2);
  5181. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  5182. Assert.AreEqual(@"{
  5183. ""Title"": ""blah"",
  5184. ""Categories"": {
  5185. ""one"": 1,
  5186. ""two"": 2
  5187. }
  5188. }", json);
  5189. NonDefaultConstructorWithReadOnlyDictionaryProperty c2 = JsonConvert.DeserializeObject<NonDefaultConstructorWithReadOnlyDictionaryProperty>(json);
  5190. Assert.AreEqual(c1.Title, c2.Title);
  5191. Assert.AreEqual(c1.Categories.Count, c2.Categories.Count);
  5192. Assert.AreEqual(1, c2.Categories["one"]);
  5193. Assert.AreEqual(2, c2.Categories["two"]);
  5194. }
  5195. [JsonObject(MemberSerialization.OptIn)]
  5196. public class ClassAttributeBase
  5197. {
  5198. [JsonProperty]
  5199. public string BaseClassValue { get; set; }
  5200. }
  5201. public class ClassAttributeDerived : ClassAttributeBase
  5202. {
  5203. [JsonProperty]
  5204. public string DerivedClassValue { get; set; }
  5205. public string NonSerialized { get; set; }
  5206. }
  5207. public class CollectionClassAttributeDerived : ClassAttributeBase, ICollection<object>
  5208. {
  5209. [JsonProperty]
  5210. public string CollectionDerivedClassValue { get; set; }
  5211. public void Add(object item)
  5212. {
  5213. throw new NotImplementedException();
  5214. }
  5215. public void Clear()
  5216. {
  5217. throw new NotImplementedException();
  5218. }
  5219. public bool Contains(object item)
  5220. {
  5221. throw new NotImplementedException();
  5222. }
  5223. public void CopyTo(object[] array, int arrayIndex)
  5224. {
  5225. throw new NotImplementedException();
  5226. }
  5227. public int Count
  5228. {
  5229. get { throw new NotImplementedException(); }
  5230. }
  5231. public bool IsReadOnly
  5232. {
  5233. get { throw new NotImplementedException(); }
  5234. }
  5235. public bool Remove(object item)
  5236. {
  5237. throw new NotImplementedException();
  5238. }
  5239. public IEnumerator<object> GetEnumerator()
  5240. {
  5241. throw new NotImplementedException();
  5242. }
  5243. IEnumerator IEnumerable.GetEnumerator()
  5244. {
  5245. throw new NotImplementedException();
  5246. }
  5247. }
  5248. [Test]
  5249. public void ClassAttributesInheritance()
  5250. {
  5251. string json = JsonConvert.SerializeObject(new ClassAttributeDerived
  5252. {
  5253. BaseClassValue = "BaseClassValue!",
  5254. DerivedClassValue = "DerivedClassValue!",
  5255. NonSerialized = "NonSerialized!"
  5256. }, Formatting.Indented);
  5257. Assert.AreEqual(@"{
  5258. ""DerivedClassValue"": ""DerivedClassValue!"",
  5259. ""BaseClassValue"": ""BaseClassValue!""
  5260. }", json);
  5261. json = JsonConvert.SerializeObject(new CollectionClassAttributeDerived
  5262. {
  5263. BaseClassValue = "BaseClassValue!",
  5264. CollectionDerivedClassValue = "CollectionDerivedClassValue!"
  5265. }, Formatting.Indented);
  5266. Assert.AreEqual(@"{
  5267. ""CollectionDerivedClassValue"": ""CollectionDerivedClassValue!"",
  5268. ""BaseClassValue"": ""BaseClassValue!""
  5269. }", json);
  5270. }
  5271. public class PrivateMembersClassWithAttributes
  5272. {
  5273. public PrivateMembersClassWithAttributes(string privateString, string internalString, string readonlyString)
  5274. {
  5275. _privateString = privateString;
  5276. _readonlyString = readonlyString;
  5277. _internalString = internalString;
  5278. }
  5279. public PrivateMembersClassWithAttributes()
  5280. {
  5281. _readonlyString = "default!";
  5282. }
  5283. [JsonProperty]
  5284. private string _privateString;
  5285. [JsonProperty]
  5286. private readonly string _readonlyString;
  5287. [JsonProperty]
  5288. internal string _internalString;
  5289. public string UseValue()
  5290. {
  5291. return _readonlyString;
  5292. }
  5293. }
  5294. [Test]
  5295. public void PrivateMembersClassWithAttributesTest()
  5296. {
  5297. PrivateMembersClassWithAttributes c1 = new PrivateMembersClassWithAttributes("privateString!", "internalString!", "readonlyString!");
  5298. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  5299. Assert.AreEqual(@"{
  5300. ""_privateString"": ""privateString!"",
  5301. ""_readonlyString"": ""readonlyString!"",
  5302. ""_internalString"": ""internalString!""
  5303. }", json);
  5304. PrivateMembersClassWithAttributes c2 = JsonConvert.DeserializeObject<PrivateMembersClassWithAttributes>(json);
  5305. Assert.AreEqual("readonlyString!", c2.UseValue());
  5306. }
  5307. public partial class BusRun
  5308. {
  5309. public IEnumerable<Nullable<DateTime>> Departures { get; set; }
  5310. public Boolean WheelchairAccessible { get; set; }
  5311. }
  5312. [Test]
  5313. public void DeserializeGenericEnumerableProperty()
  5314. {
  5315. BusRun r = JsonConvert.DeserializeObject<BusRun>("{\"Departures\":[\"\\/Date(1309874148734-0400)\\/\",\"\\/Date(1309874148739-0400)\\/\",null],\"WheelchairAccessible\":true}");
  5316. Assert.AreEqual(typeof(List<DateTime?>), r.Departures.GetType());
  5317. Assert.AreEqual(3, r.Departures.Count());
  5318. Assert.IsNotNull(r.Departures.ElementAt(0));
  5319. Assert.IsNotNull(r.Departures.ElementAt(1));
  5320. Assert.IsNull(r.Departures.ElementAt(2));
  5321. }
  5322. #if !(NET20)
  5323. [DataContract]
  5324. public class BaseType
  5325. {
  5326. [DataMember]
  5327. public string zebra;
  5328. }
  5329. [DataContract]
  5330. public class DerivedType : BaseType
  5331. {
  5332. [DataMember(Order = 0)]
  5333. public string bird;
  5334. [DataMember(Order = 1)]
  5335. public string parrot;
  5336. [DataMember]
  5337. public string dog;
  5338. [DataMember(Order = 3)]
  5339. public string antelope;
  5340. [DataMember]
  5341. public string cat;
  5342. [JsonProperty(Order = 1)]
  5343. public string albatross;
  5344. [JsonProperty(Order = -2)]
  5345. public string dinosaur;
  5346. }
  5347. [Test]
  5348. public void JsonPropertyDataMemberOrder()
  5349. {
  5350. DerivedType d = new DerivedType();
  5351. string json = JsonConvert.SerializeObject(d, Formatting.Indented);
  5352. Assert.AreEqual(@"{
  5353. ""dinosaur"": null,
  5354. ""dog"": null,
  5355. ""cat"": null,
  5356. ""zebra"": null,
  5357. ""bird"": null,
  5358. ""parrot"": null,
  5359. ""albatross"": null,
  5360. ""antelope"": null
  5361. }", json);
  5362. }
  5363. #endif
  5364. public class ClassWithException
  5365. {
  5366. public IList<Exception> Exceptions { get; set; }
  5367. public ClassWithException()
  5368. {
  5369. Exceptions = new List<Exception>();
  5370. }
  5371. }
  5372. #if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE || PORTABLE40)
  5373. [Test]
  5374. public void SerializeException1()
  5375. {
  5376. ClassWithException classWithException = new ClassWithException();
  5377. try
  5378. {
  5379. throw new Exception("Test Exception");
  5380. }
  5381. catch (Exception ex)
  5382. {
  5383. classWithException.Exceptions.Add(ex);
  5384. }
  5385. string sex = JsonConvert.SerializeObject(classWithException);
  5386. ClassWithException dex = JsonConvert.DeserializeObject<ClassWithException>(sex);
  5387. Assert.AreEqual(dex.Exceptions[0].ToString(), dex.Exceptions[0].ToString());
  5388. sex = JsonConvert.SerializeObject(classWithException, Formatting.Indented);
  5389. dex = JsonConvert.DeserializeObject<ClassWithException>(sex); // this fails!
  5390. Assert.AreEqual(dex.Exceptions[0].ToString(), dex.Exceptions[0].ToString());
  5391. }
  5392. #endif
  5393. public void DeserializeIDictionary()
  5394. {
  5395. IDictionary dictionary = JsonConvert.DeserializeObject<IDictionary>("{'name':'value!'}");
  5396. Assert.AreEqual(1, dictionary.Count);
  5397. Assert.AreEqual("value!", dictionary["name"]);
  5398. }
  5399. public void DeserializeIList()
  5400. {
  5401. IList list = JsonConvert.DeserializeObject<IList>("['1', 'two', 'III']");
  5402. Assert.AreEqual(3, list.Count);
  5403. }
  5404. public void UriGuidTimeSpanTestClassEmptyTest()
  5405. {
  5406. UriGuidTimeSpanTestClass c1 = new UriGuidTimeSpanTestClass();
  5407. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  5408. Assert.AreEqual(@"{
  5409. ""Guid"": ""00000000-0000-0000-0000-000000000000"",
  5410. ""NullableGuid"": null,
  5411. ""TimeSpan"": ""00:00:00"",
  5412. ""NullableTimeSpan"": null,
  5413. ""Uri"": null
  5414. }", json);
  5415. UriGuidTimeSpanTestClass c2 = JsonConvert.DeserializeObject<UriGuidTimeSpanTestClass>(json);
  5416. Assert.AreEqual(c1.Guid, c2.Guid);
  5417. Assert.AreEqual(c1.NullableGuid, c2.NullableGuid);
  5418. Assert.AreEqual(c1.TimeSpan, c2.TimeSpan);
  5419. Assert.AreEqual(c1.NullableTimeSpan, c2.NullableTimeSpan);
  5420. Assert.AreEqual(c1.Uri, c2.Uri);
  5421. }
  5422. public void UriGuidTimeSpanTestClassValuesTest()
  5423. {
  5424. UriGuidTimeSpanTestClass c1 = new UriGuidTimeSpanTestClass
  5425. {
  5426. Guid = new Guid("1924129C-F7E0-40F3-9607-9939C531395A"),
  5427. NullableGuid = new Guid("9E9F3ADF-E017-4F72-91E0-617EBE85967D"),
  5428. TimeSpan = TimeSpan.FromDays(1),
  5429. NullableTimeSpan = TimeSpan.FromHours(1),
  5430. Uri = new Uri("http://testuri.com")
  5431. };
  5432. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  5433. Assert.AreEqual(@"{
  5434. ""Guid"": ""1924129c-f7e0-40f3-9607-9939c531395a"",
  5435. ""NullableGuid"": ""9e9f3adf-e017-4f72-91e0-617ebe85967d"",
  5436. ""TimeSpan"": ""1.00:00:00"",
  5437. ""NullableTimeSpan"": ""01:00:00"",
  5438. ""Uri"": ""http://testuri.com/""
  5439. }", json);
  5440. UriGuidTimeSpanTestClass c2 = JsonConvert.DeserializeObject<UriGuidTimeSpanTestClass>(json);
  5441. Assert.AreEqual(c1.Guid, c2.Guid);
  5442. Assert.AreEqual(c1.NullableGuid, c2.NullableGuid);
  5443. Assert.AreEqual(c1.TimeSpan, c2.TimeSpan);
  5444. Assert.AreEqual(c1.NullableTimeSpan, c2.NullableTimeSpan);
  5445. Assert.AreEqual(c1.Uri, c2.Uri);
  5446. }
  5447. [Test]
  5448. public void NullableValueGenericDictionary()
  5449. {
  5450. IDictionary<string, int?> v1 = new Dictionary<string, int?>
  5451. {
  5452. {"First", 1},
  5453. {"Second", null},
  5454. {"Third", 3}
  5455. };
  5456. string json = JsonConvert.SerializeObject(v1, Formatting.Indented);
  5457. Assert.AreEqual(@"{
  5458. ""First"": 1,
  5459. ""Second"": null,
  5460. ""Third"": 3
  5461. }", json);
  5462. IDictionary<string, int?> v2 = JsonConvert.DeserializeObject<IDictionary<string, int?>>(json);
  5463. Assert.AreEqual(3, v2.Count);
  5464. Assert.AreEqual(1, v2["First"]);
  5465. Assert.AreEqual(null, v2["Second"]);
  5466. Assert.AreEqual(3, v2["Third"]);
  5467. }
  5468. [Test]
  5469. public void UsingJsonTextWriter()
  5470. {
  5471. // The property of the object has to be a number for the cast exception to occure
  5472. object o = new { p = 1 };
  5473. var json = JObject.FromObject(o);
  5474. using (var sw = new StringWriter())
  5475. using (var jw = new JsonTextWriter(sw))
  5476. {
  5477. jw.WriteToken(json.CreateReader());
  5478. jw.Flush();
  5479. string result = sw.ToString();
  5480. Assert.AreEqual(@"{""p"":1}", result);
  5481. }
  5482. }
  5483. #if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE || PORTABLE40)
  5484. [Test]
  5485. public void DeserializeConcurrentDictionary()
  5486. {
  5487. IDictionary<string, Component> components = new Dictionary<string, Component>
  5488. {
  5489. {"Key!", new Component()}
  5490. };
  5491. GameObject go = new GameObject
  5492. {
  5493. Components = new ConcurrentDictionary<string, Component>(components),
  5494. Id = "Id!",
  5495. Name = "Name!"
  5496. };
  5497. string originalJson = JsonConvert.SerializeObject(go, Formatting.Indented);
  5498. Assert.AreEqual(@"{
  5499. ""Components"": {
  5500. ""Key!"": {}
  5501. },
  5502. ""Id"": ""Id!"",
  5503. ""Name"": ""Name!""
  5504. }", originalJson);
  5505. GameObject newObject = JsonConvert.DeserializeObject<GameObject>(originalJson);
  5506. Assert.AreEqual(1, newObject.Components.Count);
  5507. Assert.AreEqual("Id!", newObject.Id);
  5508. Assert.AreEqual("Name!", newObject.Name);
  5509. }
  5510. #endif
  5511. [Test]
  5512. public void DeserializeKeyValuePairArray()
  5513. {
  5514. string json = @"[ { ""Value"": [ ""1"", ""2"" ], ""Key"": ""aaa"", ""BadContent"": [ 0 ] }, { ""Value"": [ ""3"", ""4"" ], ""Key"": ""bbb"" } ]";
  5515. IList<KeyValuePair<string, IList<string>>> values = JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json);
  5516. Assert.AreEqual(2, values.Count);
  5517. Assert.AreEqual("aaa", values[0].Key);
  5518. Assert.AreEqual(2, values[0].Value.Count);
  5519. Assert.AreEqual("1", values[0].Value[0]);
  5520. Assert.AreEqual("2", values[0].Value[1]);
  5521. Assert.AreEqual("bbb", values[1].Key);
  5522. Assert.AreEqual(2, values[1].Value.Count);
  5523. Assert.AreEqual("3", values[1].Value[0]);
  5524. Assert.AreEqual("4", values[1].Value[1]);
  5525. }
  5526. [Test]
  5527. public void DeserializeNullableKeyValuePairArray()
  5528. {
  5529. string json = @"[ { ""Value"": [ ""1"", ""2"" ], ""Key"": ""aaa"", ""BadContent"": [ 0 ] }, null, { ""Value"": [ ""3"", ""4"" ], ""Key"": ""bbb"" } ]";
  5530. IList<KeyValuePair<string, IList<string>>?> values = JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>?>>(json);
  5531. Assert.AreEqual(3, values.Count);
  5532. Assert.AreEqual("aaa", values[0].Value.Key);
  5533. Assert.AreEqual(2, values[0].Value.Value.Count);
  5534. Assert.AreEqual("1", values[0].Value.Value[0]);
  5535. Assert.AreEqual("2", values[0].Value.Value[1]);
  5536. Assert.AreEqual(null, values[1]);
  5537. Assert.AreEqual("bbb", values[2].Value.Key);
  5538. Assert.AreEqual(2, values[2].Value.Value.Count);
  5539. Assert.AreEqual("3", values[2].Value.Value[0]);
  5540. Assert.AreEqual("4", values[2].Value.Value[1]);
  5541. }
  5542. [Test]
  5543. public void DeserializeNullToNonNullableKeyValuePairArray()
  5544. {
  5545. string json = @"[ null ]";
  5546. ExceptionAssert.Throws<JsonSerializationException>(
  5547. "Cannot convert null value to KeyValuePair. Path '[0]', line 1, position 6.",
  5548. () =>
  5549. {
  5550. JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json);
  5551. });
  5552. }
  5553. [Test]
  5554. public void SerializeUriWithQuotes()
  5555. {
  5556. string input = "http://test.com/%22foo+bar%22";
  5557. Uri uri = new Uri(input);
  5558. string json = JsonConvert.SerializeObject(uri);
  5559. Uri output = JsonConvert.DeserializeObject<Uri>(json);
  5560. Assert.AreEqual(uri, output);
  5561. }
  5562. [Test]
  5563. public void SerializeUriWithSlashes()
  5564. {
  5565. string input = @"http://tes/?a=b\\c&d=e\";
  5566. Uri uri = new Uri(input);
  5567. string json = JsonConvert.SerializeObject(uri);
  5568. Uri output = JsonConvert.DeserializeObject<Uri>(json);
  5569. Assert.AreEqual(uri, output);
  5570. }
  5571. [Test]
  5572. public void DeserializeByteArrayWithTypeNameHandling()
  5573. {
  5574. TestObject test = new TestObject("Test", new byte[] { 72, 63, 62, 71, 92, 55 });
  5575. JsonSerializer serializer = new JsonSerializer();
  5576. serializer.TypeNameHandling = TypeNameHandling.All;
  5577. byte[] objectBytes;
  5578. using (MemoryStream bsonStream = new MemoryStream())
  5579. using (JsonWriter bsonWriter = new JsonTextWriter(new StreamWriter(bsonStream)))
  5580. {
  5581. serializer.Serialize(bsonWriter, test);
  5582. bsonWriter.Flush();
  5583. objectBytes = bsonStream.ToArray();
  5584. }
  5585. using (MemoryStream bsonStream = new MemoryStream(objectBytes))
  5586. using (JsonReader bsonReader = new JsonTextReader(new StreamReader(bsonStream)))
  5587. {
  5588. // Get exception here
  5589. TestObject newObject = (TestObject)serializer.Deserialize(bsonReader);
  5590. Assert.AreEqual("Test", newObject.Name);
  5591. CollectionAssert.AreEquivalent(new byte[] { 72, 63, 62, 71, 92, 55 }, newObject.Data);
  5592. }
  5593. }
  5594. #if !(SILVERLIGHT || WINDOWS_PHONE || NET20 || NETFX_CORE)
  5595. [Test]
  5596. public void DeserializeDecimalsWithCulture()
  5597. {
  5598. CultureInfo initialCulture = Thread.CurrentThread.CurrentCulture;
  5599. try
  5600. {
  5601. CultureInfo testCulture = CultureInfo.CreateSpecificCulture("nb-NO");
  5602. Thread.CurrentThread.CurrentCulture = testCulture;
  5603. Thread.CurrentThread.CurrentUICulture = testCulture;
  5604. string json = @"{ 'Quantity': '1.5', 'OptionalQuantity': '2.2' }";
  5605. DecimalTestClass c = JsonConvert.DeserializeObject<DecimalTestClass>(json);
  5606. Assert.AreEqual(1.5m, c.Quantity);
  5607. Assert.AreEqual(2.2d, c.OptionalQuantity);
  5608. }
  5609. finally
  5610. {
  5611. Thread.CurrentThread.CurrentCulture = initialCulture;
  5612. Thread.CurrentThread.CurrentUICulture = initialCulture;
  5613. }
  5614. }
  5615. #endif
  5616. [Test]
  5617. public void ReadForTypeHackFixDecimal()
  5618. {
  5619. IList<decimal> d1 = new List<decimal> { 1.1m };
  5620. string json = JsonConvert.SerializeObject(d1);
  5621. IList<decimal> d2 = JsonConvert.DeserializeObject<IList<decimal>>(json);
  5622. Assert.AreEqual(d1.Count, d2.Count);
  5623. Assert.AreEqual(d1[0], d2[0]);
  5624. }
  5625. [Test]
  5626. public void ReadForTypeHackFixDateTimeOffset()
  5627. {
  5628. IList<DateTimeOffset?> d1 = new List<DateTimeOffset?> { null };
  5629. string json = JsonConvert.SerializeObject(d1);
  5630. IList<DateTimeOffset?> d2 = JsonConvert.DeserializeObject<IList<DateTimeOffset?>>(json);
  5631. Assert.AreEqual(d1.Count, d2.Count);
  5632. Assert.AreEqual(d1[0], d2[0]);
  5633. }
  5634. [Test]
  5635. public void ReadForTypeHackFixByteArray()
  5636. {
  5637. IList<byte[]> d1 = new List<byte[]> { null };
  5638. string json = JsonConvert.SerializeObject(d1);
  5639. IList<byte[]> d2 = JsonConvert.DeserializeObject<IList<byte[]>>(json);
  5640. Assert.AreEqual(d1.Count, d2.Count);
  5641. Assert.AreEqual(d1[0], d2[0]);
  5642. }
  5643. [Test]
  5644. public void SerializeInheritanceHierarchyWithDuplicateProperty()
  5645. {
  5646. Bb b = new Bb();
  5647. b.no = true;
  5648. Aa a = b;
  5649. a.no = int.MaxValue;
  5650. string json = JsonConvert.SerializeObject(b);
  5651. Assert.AreEqual(@"{""no"":true}", json);
  5652. Bb b2 = JsonConvert.DeserializeObject<Bb>(json);
  5653. Assert.AreEqual(true, b2.no);
  5654. }
  5655. [Test]
  5656. public void DeserializeNullInt()
  5657. {
  5658. string json = @"[
  5659. 1,
  5660. 2,
  5661. 3,
  5662. null
  5663. ]";
  5664. ExceptionAssert.Throws<JsonSerializationException>(
  5665. "Error converting value {null} to type 'System.Int32'. Path '[3]', line 5, position 7.",
  5666. () =>
  5667. {
  5668. List<int> numbers = JsonConvert.DeserializeObject<List<int>>(json);
  5669. });
  5670. }
  5671. #if !(PORTABLE || NETFX_CORE)
  5672. public class ConvertableIntTestClass
  5673. {
  5674. public ConvertibleInt Integer { get; set; }
  5675. public ConvertibleInt? NullableInteger1 { get; set; }
  5676. public ConvertibleInt? NullableInteger2 { get; set; }
  5677. }
  5678. [Test]
  5679. public void SerializeIConvertible()
  5680. {
  5681. ConvertableIntTestClass c = new ConvertableIntTestClass
  5682. {
  5683. Integer = new ConvertibleInt(1),
  5684. NullableInteger1 = new ConvertibleInt(2),
  5685. NullableInteger2 = null
  5686. };
  5687. string json = JsonConvert.SerializeObject(c, Formatting.Indented);
  5688. Assert.AreEqual(@"{
  5689. ""Integer"": 1,
  5690. ""NullableInteger1"": 2,
  5691. ""NullableInteger2"": null
  5692. }", json);
  5693. }
  5694. [Test]
  5695. public void DeserializeIConvertible()
  5696. {
  5697. string json = @"{
  5698. ""Integer"": 1,
  5699. ""NullableInteger1"": 2,
  5700. ""NullableInteger2"": null
  5701. }";
  5702. ExceptionAssert.Throws<JsonSerializationException>(
  5703. "Error converting value 1 to type 'Newtonsoft.Json.Tests.ConvertibleInt'. Path 'Integer', line 2, position 15.",
  5704. () => JsonConvert.DeserializeObject<ConvertableIntTestClass>(json));
  5705. }
  5706. #endif
  5707. [Test]
  5708. public void SerializeNullableWidgetStruct()
  5709. {
  5710. Widget widget = new Widget { Id = new WidgetId { Value = "id" } };
  5711. string json = JsonConvert.SerializeObject(widget);
  5712. Assert.AreEqual(@"{""Id"":{""Value"":""id""}}", json);
  5713. }
  5714. [Test]
  5715. public void DeserializeNullableWidgetStruct()
  5716. {
  5717. string json = @"{""Id"":{""Value"":""id""}}";
  5718. Widget w = JsonConvert.DeserializeObject<Widget>(json);
  5719. Assert.AreEqual(new WidgetId { Value = "id" }, w.Id);
  5720. Assert.AreEqual(new WidgetId { Value = "id" }, w.Id.Value);
  5721. Assert.AreEqual("id", w.Id.Value.Value);
  5722. }
  5723. [Test]
  5724. public void DeserializeBoolInt()
  5725. {
  5726. ExceptionAssert.Throws<JsonReaderException>(
  5727. "Error reading integer. Unexpected token: Boolean. Path 'PreProperty', line 2, position 22.",
  5728. () =>
  5729. {
  5730. string json = @"{
  5731. ""PreProperty"": true,
  5732. ""PostProperty"": ""-1""
  5733. }";
  5734. JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
  5735. });
  5736. }
  5737. [Test]
  5738. public void DeserializeUnexpectedEndInt()
  5739. {
  5740. ExceptionAssert.Throws<JsonSerializationException>(
  5741. "Unexpected end when setting PreProperty's value. Path 'PreProperty', line 2, position 18.",
  5742. () =>
  5743. {
  5744. string json = @"{
  5745. ""PreProperty"": ";
  5746. JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
  5747. });
  5748. }
  5749. [Test]
  5750. public void DeserializeNullableGuid()
  5751. {
  5752. string json = @"{""Id"":null}";
  5753. var c = JsonConvert.DeserializeObject<NullableGuid>(json);
  5754. Assert.AreEqual(null, c.Id);
  5755. json = @"{""Id"":""d8220a4b-75b1-4b7a-8112-b7bdae956a45""}";
  5756. c = JsonConvert.DeserializeObject<NullableGuid>(json);
  5757. Assert.AreEqual(new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"), c.Id);
  5758. }
  5759. [Test]
  5760. public void DeserializeGuid()
  5761. {
  5762. Item expected = new Item()
  5763. {
  5764. SourceTypeID = new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"),
  5765. BrokerID = new Guid("951663c4-924e-4c86-a57a-7ed737501dbd"),
  5766. Latitude = 33.657145,
  5767. Longitude = -117.766684,
  5768. TimeStamp = new DateTime(2000, 3, 1, 23, 59, 59, DateTimeKind.Utc),
  5769. Payload = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
  5770. };
  5771. string jsonString = JsonConvert.SerializeObject(expected, Formatting.Indented);
  5772. Assert.AreEqual(@"{
  5773. ""SourceTypeID"": ""d8220a4b-75b1-4b7a-8112-b7bdae956a45"",
  5774. ""BrokerID"": ""951663c4-924e-4c86-a57a-7ed737501dbd"",
  5775. ""Latitude"": 33.657145,
  5776. ""Longitude"": -117.766684,
  5777. ""TimeStamp"": ""2000-03-01T23:59:59Z"",
  5778. ""Payload"": {
  5779. ""$type"": ""System.Byte[], mscorlib"",
  5780. ""$value"": ""AAECAwQFBgcICQ==""
  5781. }
  5782. }", jsonString);
  5783. Item actual = JsonConvert.DeserializeObject<Item>(jsonString);
  5784. Assert.AreEqual(new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"), actual.SourceTypeID);
  5785. Assert.AreEqual(new Guid("951663c4-924e-4c86-a57a-7ed737501dbd"), actual.BrokerID);
  5786. byte[] bytes = (byte[])actual.Payload;
  5787. CollectionAssert.AreEquivalent((new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }).ToList(), bytes.ToList());
  5788. }
  5789. [Test]
  5790. public void DeserializeObjectDictionary()
  5791. {
  5792. var serializer = JsonSerializer.Create(new JsonSerializerSettings());
  5793. var dict = serializer.Deserialize<Dictionary<string, string>>(new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}")));
  5794. Assert.AreEqual("", dict["k1"]);
  5795. Assert.AreEqual("v2", dict["k2"]);
  5796. }
  5797. [Test]
  5798. public void DeserializeNullableEnum()
  5799. {
  5800. string json = JsonConvert.SerializeObject(new WithEnums
  5801. {
  5802. Id = 7,
  5803. NullableEnum = null
  5804. });
  5805. Assert.AreEqual(@"{""Id"":7,""NullableEnum"":null}", json);
  5806. WithEnums e = JsonConvert.DeserializeObject<WithEnums>(json);
  5807. Assert.AreEqual(null, e.NullableEnum);
  5808. json = JsonConvert.SerializeObject(new WithEnums
  5809. {
  5810. Id = 7,
  5811. NullableEnum = MyEnum.Value2
  5812. });
  5813. Assert.AreEqual(@"{""Id"":7,""NullableEnum"":1}", json);
  5814. e = JsonConvert.DeserializeObject<WithEnums>(json);
  5815. Assert.AreEqual(MyEnum.Value2, e.NullableEnum);
  5816. }
  5817. [Test]
  5818. public void NullableStructWithConverter()
  5819. {
  5820. string json = JsonConvert.SerializeObject(new Widget1 { Id = new WidgetId1 { Value = 1234 } });
  5821. Assert.AreEqual(@"{""Id"":""1234""}", json);
  5822. Widget1 w = JsonConvert.DeserializeObject<Widget1>(@"{""Id"":""1234""}");
  5823. Assert.AreEqual(new WidgetId1 { Value = 1234 }, w.Id);
  5824. }
  5825. [Test]
  5826. public void SerializeDictionaryStringStringAndStringObject()
  5827. {
  5828. var serializer = JsonSerializer.Create(new JsonSerializerSettings());
  5829. var dict = serializer.Deserialize<Dictionary<string, string>>(new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}")));
  5830. var reader = new JsonTextReader(new StringReader("{'k1':'','k2':'v2'}"));
  5831. var dict2 = serializer.Deserialize<Dictionary<string, object>>(reader);
  5832. Assert.AreEqual(dict["k1"], dict2["k1"]);
  5833. }
  5834. [Test]
  5835. public void DeserializeEmptyStrings()
  5836. {
  5837. object v = JsonConvert.DeserializeObject<double?>("");
  5838. Assert.IsNull(v);
  5839. v = JsonConvert.DeserializeObject<char?>("");
  5840. Assert.IsNull(v);
  5841. v = JsonConvert.DeserializeObject<int?>("");
  5842. Assert.IsNull(v);
  5843. v = JsonConvert.DeserializeObject<decimal?>("");
  5844. Assert.IsNull(v);
  5845. v = JsonConvert.DeserializeObject<DateTime?>("");
  5846. Assert.IsNull(v);
  5847. v = JsonConvert.DeserializeObject<DateTimeOffset?>("");
  5848. Assert.IsNull(v);
  5849. v = JsonConvert.DeserializeObject<byte[]>("");
  5850. Assert.IsNull(v);
  5851. }
  5852. public class Sdfsdf
  5853. {
  5854. public double Id { get; set; }
  5855. }
  5856. [Test]
  5857. public void DeserializeDoubleFromEmptyString()
  5858. {
  5859. ExceptionAssert.Throws<JsonSerializationException>(
  5860. "No JSON content found and type 'System.Double' is not nullable. Path '', line 0, position 0.",
  5861. () =>
  5862. {
  5863. JsonConvert.DeserializeObject<double>("");
  5864. });
  5865. }
  5866. [Test]
  5867. public void DeserializeEnumFromEmptyString()
  5868. {
  5869. ExceptionAssert.Throws<JsonSerializationException>(
  5870. "No JSON content found and type 'System.StringComparison' is not nullable. Path '', line 0, position 0.",
  5871. () =>
  5872. {
  5873. JsonConvert.DeserializeObject<StringComparison>("");
  5874. });
  5875. }
  5876. [Test]
  5877. public void DeserializeInt32FromEmptyString()
  5878. {
  5879. ExceptionAssert.Throws<JsonSerializationException>(
  5880. "No JSON content found and type 'System.Int32' is not nullable. Path '', line 0, position 0.",
  5881. () =>
  5882. {
  5883. JsonConvert.DeserializeObject<int>("");
  5884. });
  5885. }
  5886. [Test]
  5887. public void DeserializeByteArrayFromEmptyString()
  5888. {
  5889. byte[] b = JsonConvert.DeserializeObject<byte[]>("");
  5890. Assert.IsNull(b);
  5891. }
  5892. [Test]
  5893. public void DeserializeDoubleFromNullString()
  5894. {
  5895. ExceptionAssert.Throws<ArgumentNullException>(
  5896. @"Value cannot be null.
  5897. Parameter name: value",
  5898. () =>
  5899. {
  5900. JsonConvert.DeserializeObject<double>(null);
  5901. });
  5902. }
  5903. [Test]
  5904. public void DeserializeFromNullString()
  5905. {
  5906. ExceptionAssert.Throws<ArgumentNullException>(
  5907. @"Value cannot be null.
  5908. Parameter name: value",
  5909. () =>
  5910. {
  5911. JsonConvert.DeserializeObject(null);
  5912. });
  5913. }
  5914. [Test]
  5915. public void DeserializeIsoDatesWithIsoConverter()
  5916. {
  5917. string jsonIsoText =
  5918. @"{""Value"":""2012-02-25T19:55:50.6095676+13:00""}";
  5919. DateTimeWrapper c = JsonConvert.DeserializeObject<DateTimeWrapper>(jsonIsoText, new IsoDateTimeConverter());
  5920. Assert.AreEqual(DateTimeKind.Local, c.Value.Kind);
  5921. }
  5922. #if !NET20
  5923. [Test]
  5924. public void DeserializeUTC()
  5925. {
  5926. DateTimeTestClass c =
  5927. JsonConvert.DeserializeObject<DateTimeTestClass>(
  5928. @"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12Z"",""PostField"":""Post""}",
  5929. new JsonSerializerSettings
  5930. {
  5931. DateTimeZoneHandling = DateTimeZoneHandling.Local
  5932. });
  5933. Assert.AreEqual(new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime(), c.DateTimeField);
  5934. Assert.AreEqual(new DateTimeOffset(2008, 12, 12, 12, 12, 12, 0, TimeSpan.Zero), c.DateTimeOffsetField);
  5935. Assert.AreEqual("Pre", c.PreField);
  5936. Assert.AreEqual("Post", c.PostField);
  5937. DateTimeTestClass c2 =
  5938. JsonConvert.DeserializeObject<DateTimeTestClass>(
  5939. @"{""PreField"":""Pre"",""DateTimeField"":""2008-01-01T01:01:01Z"",""DateTimeOffsetField"":""2008-01-01T01:01:01Z"",""PostField"":""Post""}",
  5940. new JsonSerializerSettings
  5941. {
  5942. DateTimeZoneHandling = DateTimeZoneHandling.Local
  5943. });
  5944. Assert.AreEqual(new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc).ToLocalTime(), c2.DateTimeField);
  5945. Assert.AreEqual(new DateTimeOffset(2008, 1, 1, 1, 1, 1, 0, TimeSpan.Zero), c2.DateTimeOffsetField);
  5946. Assert.AreEqual("Pre", c2.PreField);
  5947. Assert.AreEqual("Post", c2.PostField);
  5948. }
  5949. [Test]
  5950. public void NullableDeserializeUTC()
  5951. {
  5952. NullableDateTimeTestClass c =
  5953. JsonConvert.DeserializeObject<NullableDateTimeTestClass>(
  5954. @"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12Z"",""PostField"":""Post""}",
  5955. new JsonSerializerSettings
  5956. {
  5957. DateTimeZoneHandling = DateTimeZoneHandling.Local
  5958. });
  5959. Assert.AreEqual(new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime(), c.DateTimeField);
  5960. Assert.AreEqual(new DateTimeOffset(2008, 12, 12, 12, 12, 12, 0, TimeSpan.Zero), c.DateTimeOffsetField);
  5961. Assert.AreEqual("Pre", c.PreField);
  5962. Assert.AreEqual("Post", c.PostField);
  5963. NullableDateTimeTestClass c2 =
  5964. JsonConvert.DeserializeObject<NullableDateTimeTestClass>(
  5965. @"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}");
  5966. Assert.AreEqual(null, c2.DateTimeField);
  5967. Assert.AreEqual(null, c2.DateTimeOffsetField);
  5968. Assert.AreEqual("Pre", c2.PreField);
  5969. Assert.AreEqual("Post", c2.PostField);
  5970. }
  5971. [Test]
  5972. public void PrivateConstructor()
  5973. {
  5974. var person = PersonWithPrivateConstructor.CreatePerson();
  5975. person.Name = "John Doe";
  5976. person.Age = 25;
  5977. var serializedPerson = JsonConvert.SerializeObject(person);
  5978. var roundtrippedPerson = JsonConvert.DeserializeObject<PersonWithPrivateConstructor>(serializedPerson);
  5979. Assert.AreEqual(person.Name, roundtrippedPerson.Name);
  5980. }
  5981. #endif
  5982. #if !(SILVERLIGHT || NETFX_CORE)
  5983. [Test]
  5984. public void MetroBlogPost()
  5985. {
  5986. Product product = new Product();
  5987. product.Name = "Apple";
  5988. product.ExpiryDate = new DateTime(2012, 4, 1);
  5989. product.Price = 3.99M;
  5990. product.Sizes = new[] { "Small", "Medium", "Large" };
  5991. string json = JsonConvert.SerializeObject(product);
  5992. //{
  5993. // "Name": "Apple",
  5994. // "ExpiryDate": "2012-04-01T00:00:00",
  5995. // "Price": 3.99,
  5996. // "Sizes": [ "Small", "Medium", "Large" ]
  5997. //}
  5998. string metroJson = JsonConvert.SerializeObject(product, new JsonSerializerSettings
  5999. {
  6000. ContractResolver = new MetroPropertyNameResolver(),
  6001. Converters = { new MetroStringConverter() },
  6002. Formatting = Formatting.Indented
  6003. });
  6004. Assert.AreEqual(@"{
  6005. "":::NAME:::"": "":::APPLE:::"",
  6006. "":::EXPIRYDATE:::"": ""2012-04-01T00:00:00"",
  6007. "":::PRICE:::"": 3.99,
  6008. "":::SIZES:::"": [
  6009. "":::SMALL:::"",
  6010. "":::MEDIUM:::"",
  6011. "":::LARGE:::""
  6012. ]
  6013. }", metroJson);
  6014. //{
  6015. // ":::NAME:::": ":::APPLE:::",
  6016. // ":::EXPIRYDATE:::": "2012-04-01T00:00:00",
  6017. // ":::PRICE:::": 3.99,
  6018. // ":::SIZES:::": [ ":::SMALL:::", ":::MEDIUM:::", ":::LARGE:::" ]
  6019. //}
  6020. Color[] colors = new[] { Color.Blue, Color.Red, Color.Yellow, Color.Green, Color.Black, Color.Brown };
  6021. string json2 = JsonConvert.SerializeObject(colors, new JsonSerializerSettings
  6022. {
  6023. ContractResolver = new MetroPropertyNameResolver(),
  6024. Converters = { new MetroStringConverter(), new MetroColorConverter() },
  6025. Formatting = Formatting.Indented
  6026. });
  6027. Assert.AreEqual(@"[
  6028. "":::GRAY:::"",
  6029. "":::GRAY:::"",
  6030. "":::GRAY:::"",
  6031. "":::GRAY:::"",
  6032. "":::BLACK:::"",
  6033. "":::GRAY:::""
  6034. ]", json2);
  6035. }
  6036. public class MetroColorConverter : JsonConverter
  6037. {
  6038. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  6039. {
  6040. Color color = (Color)value;
  6041. Color fixedColor = (color == Color.White || color == Color.Black) ? color : Color.Gray;
  6042. writer.WriteValue(":::" + fixedColor.ToKnownColor().ToString().ToUpper() + ":::");
  6043. }
  6044. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  6045. {
  6046. return Enum.Parse(typeof(Color), reader.Value.ToString());
  6047. }
  6048. public override bool CanConvert(Type objectType)
  6049. {
  6050. return objectType == typeof(Color);
  6051. }
  6052. }
  6053. #endif
  6054. private class FooBar
  6055. {
  6056. public DateTimeOffset Foo { get; set; }
  6057. }
  6058. [Test]
  6059. public void TokenFromBson()
  6060. {
  6061. MemoryStream ms = new MemoryStream();
  6062. BsonWriter writer = new BsonWriter(ms);
  6063. writer.WriteStartArray();
  6064. writer.WriteValue("2000-01-02T03:04:05+06:00");
  6065. writer.WriteEndArray();
  6066. byte[] data = ms.ToArray();
  6067. BsonReader reader = new BsonReader(new MemoryStream(data))
  6068. {
  6069. ReadRootValueAsArray = true
  6070. };
  6071. JArray a = (JArray)JArray.ReadFrom(reader);
  6072. JValue v = (JValue)a[0];
  6073. Console.WriteLine(v.Value.GetType());
  6074. Console.WriteLine(a.ToString());
  6075. }
  6076. [Test]
  6077. public void ObjectRequiredDeserializeMissing()
  6078. {
  6079. string json = "{}";
  6080. IList<string> errors = new List<string>();
  6081. EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
  6082. {
  6083. errors.Add(e.ErrorContext.Error.Message);
  6084. e.ErrorContext.Handled = true;
  6085. };
  6086. var o = JsonConvert.DeserializeObject<RequiredObject>(json, new JsonSerializerSettings
  6087. {
  6088. Error = error
  6089. });
  6090. Assert.IsNotNull(o);
  6091. Assert.AreEqual(4, errors.Count);
  6092. Assert.AreEqual("Required property 'NonAttributeProperty' not found in JSON. Path '', line 1, position 2.", errors[0]);
  6093. Assert.AreEqual("Required property 'UnsetProperty' not found in JSON. Path '', line 1, position 2.", errors[1]);
  6094. Assert.AreEqual("Required property 'AllowNullProperty' not found in JSON. Path '', line 1, position 2.", errors[2]);
  6095. Assert.AreEqual("Required property 'AlwaysProperty' not found in JSON. Path '', line 1, position 2.", errors[3]);
  6096. }
  6097. [Test]
  6098. public void ObjectRequiredDeserializeNull()
  6099. {
  6100. string json = "{'NonAttributeProperty':null,'UnsetProperty':null,'AllowNullProperty':null,'AlwaysProperty':null}";
  6101. IList<string> errors = new List<string>();
  6102. EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
  6103. {
  6104. errors.Add(e.ErrorContext.Error.Message);
  6105. e.ErrorContext.Handled = true;
  6106. };
  6107. var o = JsonConvert.DeserializeObject<RequiredObject>(json, new JsonSerializerSettings
  6108. {
  6109. Error = error
  6110. });
  6111. Assert.IsNotNull(o);
  6112. Assert.AreEqual(3, errors.Count);
  6113. Assert.AreEqual("Required property 'NonAttributeProperty' expects a value but got null. Path '', line 1, position 97.", errors[0]);
  6114. Assert.AreEqual("Required property 'UnsetProperty' expects a value but got null. Path '', line 1, position 97.", errors[1]);
  6115. Assert.AreEqual("Required property 'AlwaysProperty' expects a value but got null. Path '', line 1, position 97.", errors[2]);
  6116. }
  6117. [Test]
  6118. public void ObjectRequiredSerialize()
  6119. {
  6120. IList<string> errors = new List<string>();
  6121. EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> error = (s, e) =>
  6122. {
  6123. errors.Add(e.ErrorContext.Error.Message);
  6124. e.ErrorContext.Handled = true;
  6125. };
  6126. string json = JsonConvert.SerializeObject(new RequiredObject(), new JsonSerializerSettings
  6127. {
  6128. Error = error,
  6129. Formatting = Formatting.Indented
  6130. });
  6131. Assert.AreEqual(@"{
  6132. ""DefaultProperty"": null,
  6133. ""AllowNullProperty"": null
  6134. }", json);
  6135. Assert.AreEqual(3, errors.Count);
  6136. Assert.AreEqual("Cannot write a null value for property 'NonAttributeProperty'. Property requires a value. Path ''.", errors[0]);
  6137. Assert.AreEqual("Cannot write a null value for property 'UnsetProperty'. Property requires a value. Path ''.", errors[1]);
  6138. Assert.AreEqual("Cannot write a null value for property 'AlwaysProperty'. Property requires a value. Path ''.", errors[2]);
  6139. }
  6140. [Test]
  6141. public void DeserializeCollectionItemConverter()
  6142. {
  6143. PropertyItemConverter c = new PropertyItemConverter
  6144. {
  6145. Data =
  6146. new[]{
  6147. "one",
  6148. "two",
  6149. "three"
  6150. }
  6151. };
  6152. var c2 = JsonConvert.DeserializeObject<PropertyItemConverter>("{'Data':['::ONE::','::TWO::']}");
  6153. Assert.IsNotNull(c2);
  6154. Assert.AreEqual(2, c2.Data.Count);
  6155. Assert.AreEqual("one", c2.Data[0]);
  6156. Assert.AreEqual("two", c2.Data[1]);
  6157. }
  6158. [Test]
  6159. public void SerializeCollectionItemConverter()
  6160. {
  6161. PropertyItemConverter c = new PropertyItemConverter
  6162. {
  6163. Data = new[]
  6164. {
  6165. "one",
  6166. "two",
  6167. "three"
  6168. }
  6169. };
  6170. string json = JsonConvert.SerializeObject(c);
  6171. Assert.AreEqual(@"{""Data"":["":::ONE:::"","":::TWO:::"","":::THREE:::""]}", json);
  6172. }
  6173. #if !NET20
  6174. [Test]
  6175. public void DateTimeDictionaryKey_DateTimeOffset_Iso()
  6176. {
  6177. IDictionary<DateTimeOffset, int> dic1 = new Dictionary<DateTimeOffset, int>
  6178. {
  6179. {new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero), 1},
  6180. {new DateTimeOffset(2013, 12, 12, 12, 12, 12, TimeSpan.Zero), 2}
  6181. };
  6182. string json = JsonConvert.SerializeObject(dic1, Formatting.Indented);
  6183. Assert.AreEqual(@"{
  6184. ""2000-12-12T12:12:12+00:00"": 1,
  6185. ""2013-12-12T12:12:12+00:00"": 2
  6186. }", json);
  6187. IDictionary<DateTimeOffset, int> dic2 = JsonConvert.DeserializeObject<IDictionary<DateTimeOffset, int>>(json);
  6188. Assert.AreEqual(2, dic2.Count);
  6189. Assert.AreEqual(1, dic2[new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero)]);
  6190. Assert.AreEqual(2, dic2[new DateTimeOffset(2013, 12, 12, 12, 12, 12, TimeSpan.Zero)]);
  6191. }
  6192. [Test]
  6193. public void DateTimeDictionaryKey_DateTimeOffset_MS()
  6194. {
  6195. IDictionary<DateTimeOffset?, int> dic1 = new Dictionary<DateTimeOffset?, int>
  6196. {
  6197. {new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero), 1},
  6198. {new DateTimeOffset(2013, 12, 12, 12, 12, 12, TimeSpan.Zero), 2}
  6199. };
  6200. string json = JsonConvert.SerializeObject(dic1, Formatting.Indented, new JsonSerializerSettings
  6201. {
  6202. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  6203. });
  6204. Assert.AreEqual(@"{
  6205. ""\/Date(976623132000+0000)\/"": 1,
  6206. ""\/Date(1386850332000+0000)\/"": 2
  6207. }", json);
  6208. IDictionary<DateTimeOffset?, int> dic2 = JsonConvert.DeserializeObject<IDictionary<DateTimeOffset?, int>>(json);
  6209. Assert.AreEqual(2, dic2.Count);
  6210. Assert.AreEqual(1, dic2[new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero)]);
  6211. Assert.AreEqual(2, dic2[new DateTimeOffset(2013, 12, 12, 12, 12, 12, TimeSpan.Zero)]);
  6212. }
  6213. #endif
  6214. [Test]
  6215. public void DateTimeDictionaryKey_DateTime_Iso()
  6216. {
  6217. IDictionary<DateTime, int> dic1 = new Dictionary<DateTime, int>
  6218. {
  6219. {new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc), 1},
  6220. {new DateTime(2013, 12, 12, 12, 12, 12, DateTimeKind.Utc), 2}
  6221. };
  6222. string json = JsonConvert.SerializeObject(dic1, Formatting.Indented);
  6223. Assert.AreEqual(@"{
  6224. ""2000-12-12T12:12:12Z"": 1,
  6225. ""2013-12-12T12:12:12Z"": 2
  6226. }", json);
  6227. IDictionary<DateTime, int> dic2 = JsonConvert.DeserializeObject<IDictionary<DateTime, int>>(json);
  6228. Assert.AreEqual(2, dic2.Count);
  6229. Assert.AreEqual(1, dic2[new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)]);
  6230. Assert.AreEqual(2, dic2[new DateTime(2013, 12, 12, 12, 12, 12, DateTimeKind.Utc)]);
  6231. }
  6232. [Test]
  6233. public void DateTimeDictionaryKey_DateTime_MS()
  6234. {
  6235. IDictionary<DateTime, int> dic1 = new Dictionary<DateTime, int>
  6236. {
  6237. {new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc), 1},
  6238. {new DateTime(2013, 12, 12, 12, 12, 12, DateTimeKind.Utc), 2}
  6239. };
  6240. string json = JsonConvert.SerializeObject(dic1, Formatting.Indented, new JsonSerializerSettings
  6241. {
  6242. DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  6243. });
  6244. Assert.AreEqual(@"{
  6245. ""\/Date(976623132000)\/"": 1,
  6246. ""\/Date(1386850332000)\/"": 2
  6247. }", json);
  6248. IDictionary<DateTime, int> dic2 = JsonConvert.DeserializeObject<IDictionary<DateTime, int>>(json);
  6249. Assert.AreEqual(2, dic2.Count);
  6250. Assert.AreEqual(1, dic2[new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)]);
  6251. Assert.AreEqual(2, dic2[new DateTime(2013, 12, 12, 12, 12, 12, DateTimeKind.Utc)]);
  6252. }
  6253. [Test]
  6254. public void DeserializeEmptyJsonString()
  6255. {
  6256. string s = (string) new JsonSerializer().Deserialize(new JsonTextReader(new StringReader("''")));
  6257. Assert.AreEqual("", s);
  6258. }
  6259. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40)
  6260. [Test]
  6261. public void SerializeAndDeserializeWithAttributes()
  6262. {
  6263. var testObj = new PersonSerializable() { Name = "John Doe", Age = 28 };
  6264. var objDeserialized = this.SerializeAndDeserialize<PersonSerializable>(testObj);
  6265. Assert.AreEqual(testObj.Name, objDeserialized.Name);
  6266. Assert.AreEqual(0, objDeserialized.Age);
  6267. }
  6268. private T SerializeAndDeserialize<T>(T obj)
  6269. where T : class
  6270. {
  6271. var json = Serialize(obj);
  6272. return Deserialize<T>(json);
  6273. }
  6274. private string Serialize<T>(T obj)
  6275. where T : class
  6276. {
  6277. var stringWriter = new StringWriter();
  6278. var serializer = new Newtonsoft.Json.JsonSerializer();
  6279. serializer.ContractResolver = new DefaultContractResolver(false)
  6280. {
  6281. IgnoreSerializableAttribute = false
  6282. };
  6283. serializer.Serialize(stringWriter, obj);
  6284. return stringWriter.ToString();
  6285. }
  6286. private T Deserialize<T>(string json)
  6287. where T : class
  6288. {
  6289. var jsonReader = new Newtonsoft.Json.JsonTextReader(new StringReader(json));
  6290. var serializer = new Newtonsoft.Json.JsonSerializer();
  6291. serializer.ContractResolver = new DefaultContractResolver(false)
  6292. {
  6293. IgnoreSerializableAttribute = false
  6294. };
  6295. return serializer.Deserialize(jsonReader, typeof(T)) as T;
  6296. }
  6297. #endif
  6298. [Test]
  6299. public void PropertyItemConverter()
  6300. {
  6301. Event e = new Event
  6302. {
  6303. EventName = "Blackadder III",
  6304. Venue = "Gryphon Theatre",
  6305. Performances = new List<DateTime>
  6306. {
  6307. DateTimeUtils.ConvertJavaScriptTicksToDateTime(1336458600000),
  6308. DateTimeUtils.ConvertJavaScriptTicksToDateTime(1336545000000),
  6309. DateTimeUtils.ConvertJavaScriptTicksToDateTime(1336636800000)
  6310. }
  6311. };
  6312. string json = JsonConvert.SerializeObject(e, Formatting.Indented);
  6313. //{
  6314. // "EventName": "Blackadder III",
  6315. // "Venue": "Gryphon Theatre",
  6316. // "Performances": [
  6317. // new Date(1336458600000),
  6318. // new Date(1336545000000),
  6319. // new Date(1336636800000)
  6320. // ]
  6321. //}
  6322. Assert.AreEqual(@"{
  6323. ""EventName"": ""Blackadder III"",
  6324. ""Venue"": ""Gryphon Theatre"",
  6325. ""Performances"": [
  6326. new Date(
  6327. 1336458600000
  6328. ),
  6329. new Date(
  6330. 1336545000000
  6331. ),
  6332. new Date(
  6333. 1336636800000
  6334. )
  6335. ]
  6336. }", json);
  6337. }
  6338. #if !(NET20 || NET35)
  6339. public class IgnoreDataMemberTestClass
  6340. {
  6341. [IgnoreDataMember]
  6342. public int Ignored { get; set; }
  6343. }
  6344. [Test]
  6345. public void IgnoreDataMemberTest()
  6346. {
  6347. string json = JsonConvert.SerializeObject(new IgnoreDataMemberTestClass() { Ignored = int.MaxValue }, Formatting.Indented);
  6348. Assert.AreEqual(@"{}", json);
  6349. }
  6350. #endif
  6351. #if !(NET20 || NET35)
  6352. [Test]
  6353. public void SerializeDataContractSerializationAttributes()
  6354. {
  6355. DataContractSerializationAttributesClass dataContract = new DataContractSerializationAttributesClass
  6356. {
  6357. NoAttribute = "Value!",
  6358. IgnoreDataMemberAttribute = "Value!",
  6359. DataMemberAttribute = "Value!",
  6360. IgnoreDataMemberAndDataMemberAttribute = "Value!"
  6361. };
  6362. //MemoryStream ms = new MemoryStream();
  6363. //DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DataContractSerializationAttributesClass));
  6364. //serializer.WriteObject(ms, dataContract);
  6365. //Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
  6366. string json = JsonConvert.SerializeObject(dataContract, Formatting.Indented);
  6367. Assert.AreEqual(@"{
  6368. ""DataMemberAttribute"": ""Value!"",
  6369. ""IgnoreDataMemberAndDataMemberAttribute"": ""Value!""
  6370. }", json);
  6371. PocoDataContractSerializationAttributesClass poco = new PocoDataContractSerializationAttributesClass
  6372. {
  6373. NoAttribute = "Value!",
  6374. IgnoreDataMemberAttribute = "Value!",
  6375. DataMemberAttribute = "Value!",
  6376. IgnoreDataMemberAndDataMemberAttribute = "Value!"
  6377. };
  6378. json = JsonConvert.SerializeObject(poco, Formatting.Indented);
  6379. Assert.AreEqual(@"{
  6380. ""NoAttribute"": ""Value!"",
  6381. ""DataMemberAttribute"": ""Value!""
  6382. }", json);
  6383. }
  6384. #endif
  6385. [Test]
  6386. public void CheckAdditionalContent()
  6387. {
  6388. string json = "{one:1}{}";
  6389. JsonSerializerSettings settings = new JsonSerializerSettings();
  6390. JsonSerializer s = JsonSerializer.Create(settings);
  6391. IDictionary<string, int> o = s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json)));
  6392. Assert.IsNotNull(o);
  6393. Assert.AreEqual(1, o["one"]);
  6394. settings.CheckAdditionalContent = true;
  6395. s = JsonSerializer.Create(settings);
  6396. ExceptionAssert.Throws<JsonReaderException>(
  6397. "Additional text encountered after finished reading JSON content: {. Path '', line 1, position 7.",
  6398. () =>
  6399. {
  6400. s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json)));
  6401. });
  6402. }
  6403. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40)
  6404. [Test]
  6405. public void DeserializeException()
  6406. {
  6407. string json = @"{ ""ClassName"" : ""System.InvalidOperationException"",
  6408. ""Data"" : null,
  6409. ""ExceptionMethod"" : ""8\nLogin\nAppBiz, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null\nMyApp.LoginBiz\nMyApp.User Login()"",
  6410. ""HResult"" : -2146233079,
  6411. ""HelpURL"" : null,
  6412. ""InnerException"" : { ""ClassName"" : ""System.Exception"",
  6413. ""Data"" : null,
  6414. ""ExceptionMethod"" : null,
  6415. ""HResult"" : -2146233088,
  6416. ""HelpURL"" : null,
  6417. ""InnerException"" : null,
  6418. ""Message"" : ""Inner exception..."",
  6419. ""RemoteStackIndex"" : 0,
  6420. ""RemoteStackTraceString"" : null,
  6421. ""Source"" : null,
  6422. ""StackTraceString"" : null,
  6423. ""WatsonBuckets"" : null
  6424. },
  6425. ""Message"" : ""Outter exception..."",
  6426. ""RemoteStackIndex"" : 0,
  6427. ""RemoteStackTraceString"" : null,
  6428. ""Source"" : ""AppBiz"",
  6429. ""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)"",
  6430. ""WatsonBuckets"" : null
  6431. }";
  6432. InvalidOperationException exception = JsonConvert.DeserializeObject<InvalidOperationException>(json);
  6433. Assert.IsNotNull(exception);
  6434. CustomAssert.IsInstanceOfType(typeof(InvalidOperationException), exception);
  6435. Assert.AreEqual("Outter exception...", exception.Message);
  6436. }
  6437. #endif
  6438. [Test]
  6439. public void AdditionalContentAfterFinish()
  6440. {
  6441. ExceptionAssert.Throws<JsonException>(
  6442. "Additional text found in JSON string after finishing deserializing object.",
  6443. () =>
  6444. {
  6445. string json = "[{},1]";
  6446. JsonSerializer serializer = new JsonSerializer();
  6447. serializer.CheckAdditionalContent = true;
  6448. var reader = new JsonTextReader(new StringReader(json));
  6449. reader.Read();
  6450. reader.Read();
  6451. serializer.Deserialize(reader, typeof (MyType));
  6452. });
  6453. }
  6454. [Test]
  6455. public void DeserializeRelativeUri()
  6456. {
  6457. IList<Uri> uris = JsonConvert.DeserializeObject<IList<Uri>>(@"[""http://localhost/path?query#hash""]");
  6458. Assert.AreEqual(1, uris.Count);
  6459. Assert.AreEqual(new Uri("http://localhost/path?query#hash"), uris[0]);
  6460. Uri uri = JsonConvert.DeserializeObject<Uri>(@"""http://localhost/path?query#hash""");
  6461. Assert.IsNotNull(uri);
  6462. Uri i1 = new Uri("http://localhost/path?query#hash", UriKind.RelativeOrAbsolute);
  6463. Uri i2 = new Uri("http://localhost/path?query#hash");
  6464. Assert.AreEqual(i1, i2);
  6465. uri = JsonConvert.DeserializeObject<Uri>(@"""/path?query#hash""");
  6466. Assert.IsNotNull(uri);
  6467. Assert.AreEqual(new Uri("/path?query#hash", UriKind.RelativeOrAbsolute), uri);
  6468. }
  6469. public class MyConverter : JsonConverter
  6470. {
  6471. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  6472. {
  6473. writer.WriteValue("X");
  6474. }
  6475. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  6476. {
  6477. return "X";
  6478. }
  6479. public override bool CanConvert(Type objectType)
  6480. {
  6481. return true;
  6482. }
  6483. }
  6484. public class MyType
  6485. {
  6486. [JsonProperty(ItemConverterType = typeof(MyConverter))]
  6487. public Dictionary<string, object> MyProperty { get; set; }
  6488. }
  6489. [Test]
  6490. public void DeserializeDictionaryItemConverter()
  6491. {
  6492. var actual = JsonConvert.DeserializeObject<MyType>(@"{ ""MyProperty"":{""Key"":""Y""}}");
  6493. Assert.AreEqual("X", actual.MyProperty["Key"]);
  6494. }
  6495. [Test]
  6496. public void DeserializeCaseInsensitiveKeyValuePairConverter()
  6497. {
  6498. KeyValuePair<int, string> result =
  6499. JsonConvert.DeserializeObject<KeyValuePair<int, string>>(
  6500. "{key: 123, \"VALUE\": \"test value\"}"
  6501. );
  6502. Assert.AreEqual(123, result.Key);
  6503. Assert.AreEqual("test value", result.Value);
  6504. }
  6505. [Test]
  6506. public void SerializeKeyValuePairConverterWithCamelCase()
  6507. {
  6508. string json =
  6509. JsonConvert.SerializeObject(new KeyValuePair<int, string>(123, "test value"), Formatting.Indented, new JsonSerializerSettings
  6510. {
  6511. ContractResolver = new CamelCasePropertyNamesContractResolver()
  6512. });
  6513. Assert.AreEqual(@"{
  6514. ""key"": 123,
  6515. ""value"": ""test value""
  6516. }", json);
  6517. }
  6518. public class EnumerableClass<T> : IEnumerable<T>
  6519. {
  6520. private readonly IList<T> _values;
  6521. public EnumerableClass(IEnumerable<T> values)
  6522. {
  6523. _values = new List<T>(values);
  6524. }
  6525. public IEnumerator<T> GetEnumerator()
  6526. {
  6527. return _values.GetEnumerator();
  6528. }
  6529. IEnumerator IEnumerable.GetEnumerator()
  6530. {
  6531. return GetEnumerator();
  6532. }
  6533. }
  6534. [Test]
  6535. public void DeserializeIEnumerableFromConstructor()
  6536. {
  6537. string json = @"[
  6538. 1,
  6539. 2,
  6540. null
  6541. ]";
  6542. var result = JsonConvert.DeserializeObject<EnumerableClass<int?>>(json);
  6543. Assert.AreEqual(3, result.Count());
  6544. Assert.AreEqual(1, result.ElementAt(0));
  6545. Assert.AreEqual(2, result.ElementAt(1));
  6546. Assert.AreEqual(null, result.ElementAt(2));
  6547. }
  6548. public class EnumerableClassFailure<T> : IEnumerable<T>
  6549. {
  6550. private readonly IList<T> _values;
  6551. public EnumerableClassFailure()
  6552. {
  6553. _values = new List<T>();
  6554. }
  6555. public IEnumerator<T> GetEnumerator()
  6556. {
  6557. return _values.GetEnumerator();
  6558. }
  6559. IEnumerator IEnumerable.GetEnumerator()
  6560. {
  6561. return GetEnumerator();
  6562. }
  6563. }
  6564. [Test]
  6565. public void DeserializeIEnumerableFromConstructor_Failure()
  6566. {
  6567. string json = @"[
  6568. ""One"",
  6569. ""II"",
  6570. ""3""
  6571. ]";
  6572. ExceptionAssert.Throws<JsonSerializationException>(
  6573. "Cannot create and populate list type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+EnumerableClassFailure`1[System.String]. Path '', line 1, position 1.",
  6574. () => JsonConvert.DeserializeObject<EnumerableClassFailure<string>>(json));
  6575. }
  6576. [JsonObject(MemberSerialization.Fields)]
  6577. public class MyTuple<T1>
  6578. {
  6579. private readonly T1 m_Item1;
  6580. public MyTuple(T1 item1)
  6581. {
  6582. m_Item1 = item1;
  6583. }
  6584. public T1 Item1
  6585. {
  6586. get { return m_Item1; }
  6587. }
  6588. }
  6589. [JsonObject(MemberSerialization.Fields)]
  6590. public class MyTuplePartial<T1>
  6591. {
  6592. private readonly T1 m_Item1;
  6593. public MyTuplePartial(T1 item1)
  6594. {
  6595. m_Item1 = item1;
  6596. }
  6597. public T1 Item1
  6598. {
  6599. get { return m_Item1; }
  6600. }
  6601. }
  6602. [Test]
  6603. public void SerializeFloatingPointHandling()
  6604. {
  6605. string json;
  6606. IList<double> d = new List<double> {1.1, double.NaN, double.PositiveInfinity};
  6607. json = JsonConvert.SerializeObject(d);
  6608. // [1.1,"NaN","Infinity"]
  6609. json = JsonConvert.SerializeObject(d, new JsonSerializerSettings { FloatFormatHandling = FloatFormatHandling.Symbol });
  6610. // [1.1,NaN,Infinity]
  6611. json = JsonConvert.SerializeObject(d, new JsonSerializerSettings {FloatFormatHandling = FloatFormatHandling.DefaultValue});
  6612. // [1.1,0.0,0.0]
  6613. Assert.AreEqual("[1.1,0.0,0.0]", json);
  6614. }
  6615. #if !(NET20 || NET35 || NET40 || SILVERLIGHT || PORTABLE40)
  6616. #if !PORTABLE
  6617. [Test]
  6618. public void DeserializeReadOnlyListWithBigInteger()
  6619. {
  6620. string json = @"[
  6621. 9000000000000000000000000000000000000000000000000
  6622. ]";
  6623. var l = JsonConvert.DeserializeObject<IReadOnlyList<BigInteger>>(json);
  6624. BigInteger nineQuindecillion = l[0];
  6625. // 9000000000000000000000000000000000000000000000000
  6626. Assert.AreEqual(BigInteger.Parse("9000000000000000000000000000000000000000000000000"), nineQuindecillion);
  6627. }
  6628. #endif
  6629. [Test]
  6630. public void DeserializeReadOnlyListWithInt()
  6631. {
  6632. string json = @"[
  6633. 900
  6634. ]";
  6635. var l = JsonConvert.DeserializeObject<IReadOnlyList<int>>(json);
  6636. int i = l[0];
  6637. // 900
  6638. Assert.AreEqual(900, i);
  6639. }
  6640. [Test]
  6641. public void DeserializeReadOnlyListWithNullableType()
  6642. {
  6643. string json = @"[
  6644. 1,
  6645. null
  6646. ]";
  6647. var l = JsonConvert.DeserializeObject<IReadOnlyList<int?>>(json);
  6648. Assert.AreEqual(1, l[0]);
  6649. Assert.AreEqual(null, l[1]);
  6650. }
  6651. #endif
  6652. [Test]
  6653. public void SerializeCustomTupleWithSerializableAttribute()
  6654. {
  6655. var tuple = new MyTuple<int>(500);
  6656. var json = JsonConvert.SerializeObject(tuple);
  6657. Assert.AreEqual(@"{""m_Item1"":500}", json);
  6658. MyTuple<int> obj = null;
  6659. Action doStuff = () =>
  6660. {
  6661. obj = JsonConvert.DeserializeObject<MyTuple<int>>(json);
  6662. };
  6663. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40)
  6664. doStuff();
  6665. Assert.AreEqual(500, obj.Item1);
  6666. #else
  6667. ExceptionAssert.Throws<JsonSerializationException>(
  6668. "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.",
  6669. doStuff);
  6670. #endif
  6671. }
  6672. #if DEBUG
  6673. [Test]
  6674. public void SerializeCustomTupleWithSerializableAttributeInPartialTrust()
  6675. {
  6676. try
  6677. {
  6678. JsonTypeReflector.SetFullyTrusted(false);
  6679. var tuple = new MyTuplePartial<int>(500);
  6680. var json = JsonConvert.SerializeObject(tuple);
  6681. Assert.AreEqual(@"{""m_Item1"":500}", json);
  6682. ExceptionAssert.Throws<JsonSerializationException>(
  6683. "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.",
  6684. () => JsonConvert.DeserializeObject<MyTuplePartial<int>>(json));
  6685. }
  6686. finally
  6687. {
  6688. JsonTypeReflector.SetFullyTrusted(true);
  6689. }
  6690. }
  6691. #endif
  6692. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || NET35 || NET20 || PORTABLE40)
  6693. [Test]
  6694. public void SerializeTupleWithSerializableAttribute()
  6695. {
  6696. var tuple = Tuple.Create(500);
  6697. var json = JsonConvert.SerializeObject(tuple, new JsonSerializerSettings
  6698. {
  6699. ContractResolver = new SerializableContractResolver()
  6700. });
  6701. Assert.AreEqual(@"{""m_Item1"":500}", json);
  6702. var obj = JsonConvert.DeserializeObject<Tuple<int>>(json, new JsonSerializerSettings
  6703. {
  6704. ContractResolver = new SerializableContractResolver()
  6705. });
  6706. Assert.AreEqual(500, obj.Item1);
  6707. }
  6708. public class SerializableContractResolver : DefaultContractResolver
  6709. {
  6710. public SerializableContractResolver()
  6711. {
  6712. IgnoreSerializableAttribute = false;
  6713. }
  6714. }
  6715. #endif
  6716. #if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40)
  6717. public class PopulateReadOnlyTestClass
  6718. {
  6719. public IList<int> NonReadOnlyList { get; set; }
  6720. public IDictionary<string, int> NonReadOnlyDictionary { get; set; }
  6721. public IList<int> Array { get; set; }
  6722. public IList<int> List { get; set; }
  6723. public IDictionary<string, int> Dictionary { get; set; }
  6724. public IReadOnlyCollection<int> IReadOnlyCollection { get; set; }
  6725. public ReadOnlyCollection<int> ReadOnlyCollection { get; set; }
  6726. public IReadOnlyList<int> IReadOnlyList { get; set; }
  6727. public IReadOnlyDictionary<string, int> IReadOnlyDictionary { get; set; }
  6728. public ReadOnlyDictionary<string, int> ReadOnlyDictionary { get; set; }
  6729. public PopulateReadOnlyTestClass()
  6730. {
  6731. NonReadOnlyList = new List<int> { 1 };
  6732. NonReadOnlyDictionary = new Dictionary<string, int> { { "first", 2 } };
  6733. Array = new[] {3};
  6734. List = new ReadOnlyCollection<int>(new[] { 4 });
  6735. Dictionary = new ReadOnlyDictionary<string, int>(new Dictionary<string, int> { { "first", 5 } });
  6736. IReadOnlyCollection = new ReadOnlyCollection<int>(new[] { 6 });
  6737. ReadOnlyCollection = new ReadOnlyCollection<int>(new[] { 7 });
  6738. IReadOnlyList = new ReadOnlyCollection<int>(new[] { 8 });
  6739. IReadOnlyDictionary = new ReadOnlyDictionary<string, int>(new Dictionary<string, int> { { "first", 9 } });
  6740. ReadOnlyDictionary = new ReadOnlyDictionary<string, int>(new Dictionary<string, int> { { "first", 10 } });
  6741. }
  6742. }
  6743. [Test]
  6744. public void SerializeReadOnlyCollections()
  6745. {
  6746. PopulateReadOnlyTestClass c1 = new PopulateReadOnlyTestClass();
  6747. string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
  6748. Assert.AreEqual(@"{
  6749. ""NonReadOnlyList"": [
  6750. 1
  6751. ],
  6752. ""NonReadOnlyDictionary"": {
  6753. ""first"": 2
  6754. },
  6755. ""Array"": [
  6756. 3
  6757. ],
  6758. ""List"": [
  6759. 4
  6760. ],
  6761. ""Dictionary"": {
  6762. ""first"": 5
  6763. },
  6764. ""IReadOnlyCollection"": [
  6765. 6
  6766. ],
  6767. ""ReadOnlyCollection"": [
  6768. 7
  6769. ],
  6770. ""IReadOnlyList"": [
  6771. 8
  6772. ],
  6773. ""IReadOnlyDictionary"": {
  6774. ""first"": 9
  6775. },
  6776. ""ReadOnlyDictionary"": {
  6777. ""first"": 10
  6778. }
  6779. }", json);
  6780. }
  6781. [Test]
  6782. public void PopulateReadOnlyCollections()
  6783. {
  6784. string json = @"{
  6785. ""NonReadOnlyList"": [
  6786. 11
  6787. ],
  6788. ""NonReadOnlyDictionary"": {
  6789. ""first"": 12
  6790. },
  6791. ""Array"": [
  6792. 13
  6793. ],
  6794. ""List"": [
  6795. 14
  6796. ],
  6797. ""Dictionary"": {
  6798. ""first"": 15
  6799. },
  6800. ""IReadOnlyCollection"": [
  6801. 16
  6802. ],
  6803. ""ReadOnlyCollection"": [
  6804. 17
  6805. ],
  6806. ""IReadOnlyList"": [
  6807. 18
  6808. ],
  6809. ""IReadOnlyDictionary"": {
  6810. ""first"": 19
  6811. },
  6812. ""ReadOnlyDictionary"": {
  6813. ""first"": 20
  6814. }
  6815. }";
  6816. var c2 = JsonConvert.DeserializeObject<PopulateReadOnlyTestClass>(json);
  6817. Assert.AreEqual(1, c2.NonReadOnlyDictionary.Count);
  6818. Assert.AreEqual(12, c2.NonReadOnlyDictionary["first"]);
  6819. Assert.AreEqual(2, c2.NonReadOnlyList.Count);
  6820. Assert.AreEqual(1, c2.NonReadOnlyList[0]);
  6821. Assert.AreEqual(11, c2.NonReadOnlyList[1]);
  6822. Assert.AreEqual(1, c2.Array.Count);
  6823. Assert.AreEqual(13, c2.Array[0]);
  6824. }
  6825. #endif
  6826. [Test]
  6827. public void SerializeArray2D()
  6828. {
  6829. Array2D aa = new Array2D();
  6830. aa.Before = "Before!";
  6831. aa.After = "After!";
  6832. aa.Coordinates = new[,] { { 1, 1 }, { 1, 2 }, { 2, 1 }, { 2, 2 } };
  6833. string json = JsonConvert.SerializeObject(aa);
  6834. Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}", json);
  6835. }
  6836. [Test]
  6837. public void SerializeArray3D()
  6838. {
  6839. Array3D aa = new Array3D();
  6840. aa.Before = "Before!";
  6841. aa.After = "After!";
  6842. 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 } } };
  6843. string json = JsonConvert.SerializeObject(aa);
  6844. 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);
  6845. }
  6846. [Test]
  6847. public void SerializeArray3DWithConverter()
  6848. {
  6849. Array3DWithConverter aa = new Array3DWithConverter();
  6850. aa.Before = "Before!";
  6851. aa.After = "After!";
  6852. 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 } } };
  6853. string json = JsonConvert.SerializeObject(aa, Formatting.Indented);
  6854. Assert.AreEqual(@"{
  6855. ""Before"": ""Before!"",
  6856. ""Coordinates"": [
  6857. [
  6858. [
  6859. 1.0,
  6860. 1.0,
  6861. 1.0
  6862. ],
  6863. [
  6864. 1.0,
  6865. 1.0,
  6866. 2.0
  6867. ]
  6868. ],
  6869. [
  6870. [
  6871. 1.0,
  6872. 2.0,
  6873. 1.0
  6874. ],
  6875. [
  6876. 1.0,
  6877. 2.0,
  6878. 2.0
  6879. ]
  6880. ],
  6881. [
  6882. [
  6883. 2.0,
  6884. 1.0,
  6885. 1.0
  6886. ],
  6887. [
  6888. 2.0,
  6889. 1.0,
  6890. 2.0
  6891. ]
  6892. ],
  6893. [
  6894. [
  6895. 2.0,
  6896. 2.0,
  6897. 1.0
  6898. ],
  6899. [
  6900. 2.0,
  6901. 2.0,
  6902. 2.0
  6903. ]
  6904. ]
  6905. ],
  6906. ""After"": ""After!""
  6907. }", json);
  6908. }
  6909. [Test]
  6910. public void DeserializeArray3DWithConverter()
  6911. {
  6912. string json = @"{
  6913. ""Before"": ""Before!"",
  6914. ""Coordinates"": [
  6915. [
  6916. [
  6917. 1.0,
  6918. 1.0,
  6919. 1.0
  6920. ],
  6921. [
  6922. 1.0,
  6923. 1.0,
  6924. 2.0
  6925. ]
  6926. ],
  6927. [
  6928. [
  6929. 1.0,
  6930. 2.0,
  6931. 1.0
  6932. ],
  6933. [
  6934. 1.0,
  6935. 2.0,
  6936. 2.0
  6937. ]
  6938. ],
  6939. [
  6940. [
  6941. 2.0,
  6942. 1.0,
  6943. 1.0
  6944. ],
  6945. [
  6946. 2.0,
  6947. 1.0,
  6948. 2.0
  6949. ]
  6950. ],
  6951. [
  6952. [
  6953. 2.0,
  6954. 2.0,
  6955. 1.0
  6956. ],
  6957. [
  6958. 2.0,
  6959. 2.0,
  6960. 2.0
  6961. ]
  6962. ]
  6963. ],
  6964. ""After"": ""After!""
  6965. }";
  6966. Array3DWithConverter aa = JsonConvert.DeserializeObject<Array3DWithConverter>(json);
  6967. Assert.AreEqual("Before!", aa.Before);
  6968. Assert.AreEqual("After!", aa.After);
  6969. Assert.AreEqual(4, aa.Coordinates.GetLength(0));
  6970. Assert.AreEqual(2, aa.Coordinates.GetLength(1));
  6971. Assert.AreEqual(3, aa.Coordinates.GetLength(2));
  6972. Assert.AreEqual(1, aa.Coordinates[0, 0, 0]);
  6973. Assert.AreEqual(2, aa.Coordinates[1, 1, 1]);
  6974. }
  6975. [Test]
  6976. public void DeserializeArray2D()
  6977. {
  6978. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2],[2,1],[2,2]],""After"":""After!""}";
  6979. Array2D aa = JsonConvert.DeserializeObject<Array2D>(json);
  6980. Assert.AreEqual("Before!", aa.Before);
  6981. Assert.AreEqual("After!", aa.After);
  6982. Assert.AreEqual(4, aa.Coordinates.GetLength(0));
  6983. Assert.AreEqual(2, aa.Coordinates.GetLength(1));
  6984. Assert.AreEqual(1, aa.Coordinates[0, 0]);
  6985. Assert.AreEqual(2, aa.Coordinates[1, 1]);
  6986. string after = JsonConvert.SerializeObject(aa);
  6987. Assert.AreEqual(json, after);
  6988. }
  6989. [Test]
  6990. public void DeserializeArray2D_WithTooManyItems()
  6991. {
  6992. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2,3],[2,1],[2,2]],""After"":""After!""}";
  6993. ExceptionAssert.Throws<Exception>(
  6994. "Cannot deserialize non-cubical array as multidimensional array.",
  6995. () => JsonConvert.DeserializeObject<Array2D>(json));
  6996. }
  6997. [Test]
  6998. public void DeserializeArray2D_WithTooFewItems()
  6999. {
  7000. string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1],[2,1],[2,2]],""After"":""After!""}";
  7001. ExceptionAssert.Throws<Exception>(
  7002. "Cannot deserialize non-cubical array as multidimensional array.",
  7003. () => JsonConvert.DeserializeObject<Array2D>(json));
  7004. }
  7005. [Test]
  7006. public void DeserializeArray3D()
  7007. {
  7008. 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!""}";
  7009. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  7010. Assert.AreEqual("Before!", aa.Before);
  7011. Assert.AreEqual("After!", aa.After);
  7012. Assert.AreEqual(4, aa.Coordinates.GetLength(0));
  7013. Assert.AreEqual(2, aa.Coordinates.GetLength(1));
  7014. Assert.AreEqual(3, aa.Coordinates.GetLength(2));
  7015. Assert.AreEqual(1, aa.Coordinates[0, 0, 0]);
  7016. Assert.AreEqual(2, aa.Coordinates[1, 1, 1]);
  7017. string after = JsonConvert.SerializeObject(aa);
  7018. Assert.AreEqual(json, after);
  7019. }
  7020. [Test]
  7021. public void DeserializeArray3D_WithTooManyItems()
  7022. {
  7023. 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!""}";
  7024. ExceptionAssert.Throws<Exception>(
  7025. "Cannot deserialize non-cubical array as multidimensional array.",
  7026. () => JsonConvert.DeserializeObject<Array3D>(json));
  7027. }
  7028. [Test]
  7029. public void DeserializeArray3D_WithBadItems()
  7030. {
  7031. 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!""}";
  7032. ExceptionAssert.Throws<JsonSerializationException>(
  7033. "Unexpected token when deserializing multidimensional array: StartObject. Path 'Coordinates[3][1]', line 1, position 99.",
  7034. () => JsonConvert.DeserializeObject<Array3D>(json));
  7035. }
  7036. [Test]
  7037. public void DeserializeArray3D_WithTooFewItems()
  7038. {
  7039. 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!""}";
  7040. ExceptionAssert.Throws<Exception>(
  7041. "Cannot deserialize non-cubical array as multidimensional array.",
  7042. () => JsonConvert.DeserializeObject<Array3D>(json));
  7043. }
  7044. [Test]
  7045. public void SerializeEmpty3DArray()
  7046. {
  7047. Array3D aa = new Array3D();
  7048. aa.Before = "Before!";
  7049. aa.After = "After!";
  7050. aa.Coordinates = new int[0, 0, 0];
  7051. string json = JsonConvert.SerializeObject(aa);
  7052. Assert.AreEqual(@"{""Before"":""Before!"",""Coordinates"":[],""After"":""After!""}", json);
  7053. }
  7054. [Test]
  7055. public void DeserializeEmpty3DArray()
  7056. {
  7057. string json = @"{""Before"":""Before!"",""Coordinates"":[],""After"":""After!""}";
  7058. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  7059. Assert.AreEqual("Before!", aa.Before);
  7060. Assert.AreEqual("After!", aa.After);
  7061. Assert.AreEqual(0, aa.Coordinates.GetLength(0));
  7062. Assert.AreEqual(0, aa.Coordinates.GetLength(1));
  7063. Assert.AreEqual(0, aa.Coordinates.GetLength(2));
  7064. string after = JsonConvert.SerializeObject(aa);
  7065. Assert.AreEqual(json, after);
  7066. }
  7067. [Test]
  7068. public void DeserializeIncomplete3DArray()
  7069. {
  7070. string json = @"{""Before"":""Before!"",""Coordinates"":[/*hi*/[/*hi*/[1/*hi*/,/*hi*/1/*hi*/,1]/*hi*/,/*hi*/[1,1";
  7071. ExceptionAssert.Throws<JsonSerializationException>(
  7072. "Unexpected end when deserializing array. Path 'Coordinates[0][1][1]', line 1, position 90.",
  7073. () => JsonConvert.DeserializeObject<Array3D>(json));
  7074. }
  7075. [Test]
  7076. public void DeserializeIncompleteNotTopLevel3DArray()
  7077. {
  7078. string json = @"{""Before"":""Before!"",""Coordinates"":[/*hi*/[/*hi*/";
  7079. ExceptionAssert.Throws<JsonSerializationException>(
  7080. "Unexpected end when deserializing array. Path 'Coordinates[0]', line 1, position 48.",
  7081. () => JsonConvert.DeserializeObject<Array3D>(json));
  7082. }
  7083. [Test]
  7084. public void DeserializeNull3DArray()
  7085. {
  7086. string json = @"{""Before"":""Before!"",""Coordinates"":null,""After"":""After!""}";
  7087. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  7088. Assert.AreEqual("Before!", aa.Before);
  7089. Assert.AreEqual("After!", aa.After);
  7090. Assert.AreEqual(null, aa.Coordinates);
  7091. string after = JsonConvert.SerializeObject(aa);
  7092. Assert.AreEqual(json, after);
  7093. }
  7094. [Test]
  7095. public void DeserializeSemiEmpty3DArray()
  7096. {
  7097. string json = @"{""Before"":""Before!"",""Coordinates"":[[]],""After"":""After!""}";
  7098. Array3D aa = JsonConvert.DeserializeObject<Array3D>(json);
  7099. Assert.AreEqual("Before!", aa.Before);
  7100. Assert.AreEqual("After!", aa.After);
  7101. Assert.AreEqual(1, aa.Coordinates.GetLength(0));
  7102. Assert.AreEqual(0, aa.Coordinates.GetLength(1));
  7103. Assert.AreEqual(0, aa.Coordinates.GetLength(2));
  7104. string after = JsonConvert.SerializeObject(aa);
  7105. Assert.AreEqual(json, after);
  7106. }
  7107. [Test]
  7108. public void SerializeReferenceTracked3DArray()
  7109. {
  7110. Event e1 = new Event
  7111. {
  7112. EventName = "EventName!"
  7113. };
  7114. Event[,] array1 = new [,] { { e1, e1 }, { e1, e1 } };
  7115. IList<Event[,]> values1 = new List<Event[,]>
  7116. {
  7117. array1,
  7118. array1
  7119. };
  7120. string json = JsonConvert.SerializeObject(values1, new JsonSerializerSettings
  7121. {
  7122. PreserveReferencesHandling = PreserveReferencesHandling.All,
  7123. Formatting = Formatting.Indented
  7124. });
  7125. Assert.AreEqual(@"{
  7126. ""$id"": ""1"",
  7127. ""$values"": [
  7128. {
  7129. ""$id"": ""2"",
  7130. ""$values"": [
  7131. [
  7132. {
  7133. ""$id"": ""3"",
  7134. ""EventName"": ""EventName!"",
  7135. ""Venue"": null,
  7136. ""Performances"": null
  7137. },
  7138. {
  7139. ""$ref"": ""3""
  7140. }
  7141. ],
  7142. [
  7143. {
  7144. ""$ref"": ""3""
  7145. },
  7146. {
  7147. ""$ref"": ""3""
  7148. }
  7149. ]
  7150. ]
  7151. },
  7152. {
  7153. ""$ref"": ""2""
  7154. }
  7155. ]
  7156. }", json);
  7157. }
  7158. [Test]
  7159. public void SerializeTypeName3DArray()
  7160. {
  7161. Event e1 = new Event
  7162. {
  7163. EventName = "EventName!"
  7164. };
  7165. Event[,] array1 = new[,] { { e1, e1 }, { e1, e1 } };
  7166. IList<Event[,]> values1 = new List<Event[,]>
  7167. {
  7168. array1,
  7169. array1
  7170. };
  7171. string json = JsonConvert.SerializeObject(values1, new JsonSerializerSettings
  7172. {
  7173. TypeNameHandling = TypeNameHandling.All,
  7174. Formatting = Formatting.Indented
  7175. });
  7176. Assert.AreEqual(@"{
  7177. ""$type"": ""System.Collections.Generic.List`1[[Newtonsoft.Json.Tests.Serialization.Event[,], Newtonsoft.Json.Tests]], mscorlib"",
  7178. ""$values"": [
  7179. {
  7180. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event[,], Newtonsoft.Json.Tests"",
  7181. ""$values"": [
  7182. [
  7183. {
  7184. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  7185. ""EventName"": ""EventName!"",
  7186. ""Venue"": null,
  7187. ""Performances"": null
  7188. },
  7189. {
  7190. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  7191. ""EventName"": ""EventName!"",
  7192. ""Venue"": null,
  7193. ""Performances"": null
  7194. }
  7195. ],
  7196. [
  7197. {
  7198. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  7199. ""EventName"": ""EventName!"",
  7200. ""Venue"": null,
  7201. ""Performances"": null
  7202. },
  7203. {
  7204. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  7205. ""EventName"": ""EventName!"",
  7206. ""Venue"": null,
  7207. ""Performances"": null
  7208. }
  7209. ]
  7210. ]
  7211. },
  7212. {
  7213. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event[,], Newtonsoft.Json.Tests"",
  7214. ""$values"": [
  7215. [
  7216. {
  7217. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  7218. ""EventName"": ""EventName!"",
  7219. ""Venue"": null,
  7220. ""Performances"": null
  7221. },
  7222. {
  7223. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  7224. ""EventName"": ""EventName!"",
  7225. ""Venue"": null,
  7226. ""Performances"": null
  7227. }
  7228. ],
  7229. [
  7230. {
  7231. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  7232. ""EventName"": ""EventName!"",
  7233. ""Venue"": null,
  7234. ""Performances"": null
  7235. },
  7236. {
  7237. ""$type"": ""Newtonsoft.Json.Tests.Serialization.Event, Newtonsoft.Json.Tests"",
  7238. ""EventName"": ""EventName!"",
  7239. ""Venue"": null,
  7240. ""Performances"": null
  7241. }
  7242. ]
  7243. ]
  7244. }
  7245. ]
  7246. }", json);
  7247. IList<Event[,]> values2 = (IList<Event[,]>)JsonConvert.DeserializeObject(json, new JsonSerializerSettings
  7248. {
  7249. TypeNameHandling = TypeNameHandling.All
  7250. });
  7251. Assert.AreEqual(2, values2.Count);
  7252. Assert.AreEqual("EventName!", values2[0][0, 0].EventName);
  7253. }
  7254. #if NETFX_CORE
  7255. [Test]
  7256. public void SerializeWinRTJsonObject()
  7257. {
  7258. var o = Windows.Data.Json.JsonObject.Parse(@"{
  7259. ""CPU"": ""Intel"",
  7260. ""Drives"": [
  7261. ""DVD read/writer"",
  7262. ""500 gigabyte hard drive""
  7263. ]
  7264. }");
  7265. string json = JsonConvert.SerializeObject(o, Formatting.Indented);
  7266. Assert.AreEqual(@"{
  7267. ""Drives"": [
  7268. ""DVD read/writer"",
  7269. ""500 gigabyte hard drive""
  7270. ],
  7271. ""CPU"": ""Intel""
  7272. }", json);
  7273. }
  7274. #endif
  7275. #if !NET20
  7276. [Test]
  7277. public void RoundtripOfDateTimeOffset()
  7278. {
  7279. var content = @"{""startDateTime"":""2012-07-19T14:30:00+09:30""}";
  7280. var jsonSerializerSettings = new JsonSerializerSettings() {DateFormatHandling = DateFormatHandling.IsoDateFormat, DateParseHandling = DateParseHandling.DateTimeOffset, DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind};
  7281. var obj = (JObject)JsonConvert.DeserializeObject(content, jsonSerializerSettings);
  7282. var dateTimeOffset = (DateTimeOffset)((JValue) obj["startDateTime"]).Value;
  7283. Assert.AreEqual(TimeSpan.FromHours(9.5), dateTimeOffset.Offset);
  7284. Assert.AreEqual("07/19/2012 14:30:00 +09:30", dateTimeOffset.ToString(CultureInfo.InvariantCulture));
  7285. }
  7286. public class NullableFloats
  7287. {
  7288. public object Object { get; set; }
  7289. public float Float { get; set; }
  7290. public double Double { get; set; }
  7291. public float? NullableFloat { get; set; }
  7292. public double? NullableDouble { get; set; }
  7293. public object ObjectNull { get; set; }
  7294. }
  7295. [Test]
  7296. public void NullableFloatingPoint()
  7297. {
  7298. NullableFloats floats = new NullableFloats
  7299. {
  7300. Object = double.NaN,
  7301. ObjectNull = null,
  7302. Float = float.NaN,
  7303. NullableDouble = double.NaN,
  7304. NullableFloat = null
  7305. };
  7306. string json = JsonConvert.SerializeObject(floats, Formatting.Indented, new JsonSerializerSettings
  7307. {
  7308. FloatFormatHandling = FloatFormatHandling.DefaultValue
  7309. });
  7310. Assert.AreEqual(@"{
  7311. ""Object"": 0.0,
  7312. ""Float"": 0.0,
  7313. ""Double"": 0.0,
  7314. ""NullableFloat"": null,
  7315. ""NullableDouble"": null,
  7316. ""ObjectNull"": null
  7317. }", json);
  7318. }
  7319. [Test]
  7320. public void DateFormatString()
  7321. {
  7322. IList<object> dates = new List<object>
  7323. {
  7324. new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc),
  7325. new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1))
  7326. };
  7327. string json = JsonConvert.SerializeObject(dates, Formatting.Indented, new JsonSerializerSettings
  7328. {
  7329. DateFormatString = "yyyy tt",
  7330. Culture = new CultureInfo("en-NZ")
  7331. });
  7332. Assert.AreEqual(@"[
  7333. ""2000 p.m."",
  7334. ""2000 p.m.""
  7335. ]", json);
  7336. }
  7337. [Test]
  7338. public void DateFormatStringForInternetExplorer()
  7339. {
  7340. IList<object> dates = new List<object>
  7341. {
  7342. new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc),
  7343. new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1))
  7344. };
  7345. string json = JsonConvert.SerializeObject(dates, Formatting.Indented, new JsonSerializerSettings
  7346. {
  7347. DateFormatString = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK"
  7348. });
  7349. Assert.AreEqual(@"[
  7350. ""2000-12-12T12:12:12.000Z"",
  7351. ""2000-12-12T12:12:12.000+01:00""
  7352. ]", json);
  7353. }
  7354. [Test]
  7355. public void JsonSerializerDateFormatString()
  7356. {
  7357. IList<object> dates = new List<object>
  7358. {
  7359. new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc),
  7360. new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1))
  7361. };
  7362. StringWriter sw = new StringWriter();
  7363. JsonTextWriter jsonWriter = new JsonTextWriter(sw);
  7364. JsonSerializer serializer = JsonSerializer.Create(new JsonSerializerSettings
  7365. {
  7366. DateFormatString = "yyyy tt",
  7367. Culture = new CultureInfo("en-NZ"),
  7368. Formatting = Formatting.Indented
  7369. });
  7370. serializer.Serialize(jsonWriter, dates);
  7371. Assert.IsNull(jsonWriter.DateFormatString);
  7372. Assert.AreEqual(CultureInfo.InvariantCulture, jsonWriter.Culture);
  7373. Assert.AreEqual(Formatting.None, jsonWriter.Formatting);
  7374. string json = sw.ToString();
  7375. Assert.AreEqual(@"[
  7376. ""2000 p.m."",
  7377. ""2000 p.m.""
  7378. ]", json);
  7379. }
  7380. #if !(NET20 || NET35)
  7381. [Test]
  7382. public void SerializeDeserializeTuple()
  7383. {
  7384. Tuple<int, int> tuple = Tuple.Create(500, 20);
  7385. string json = JsonConvert.SerializeObject(tuple);
  7386. Assert.AreEqual(@"{""Item1"":500,""Item2"":20}", json);
  7387. Tuple<int, int> tuple2 = JsonConvert.DeserializeObject<Tuple<int, int>>(json);
  7388. Assert.AreEqual(500, tuple2.Item1);
  7389. Assert.AreEqual(20, tuple2.Item2);
  7390. }
  7391. #endif
  7392. public class MessageWithIsoDate
  7393. {
  7394. public String IsoDate { get; set; }
  7395. }
  7396. [Test]
  7397. public void JsonSerializerStringEscapeHandling()
  7398. {
  7399. StringWriter sw = new StringWriter();
  7400. JsonTextWriter jsonWriter = new JsonTextWriter(sw);
  7401. JsonSerializer serializer = JsonSerializer.Create(new JsonSerializerSettings
  7402. {
  7403. StringEscapeHandling = StringEscapeHandling.EscapeHtml,
  7404. Formatting = Formatting.Indented
  7405. });
  7406. serializer.Serialize(jsonWriter, new { html = "<html></html>" });
  7407. Assert.AreEqual(StringEscapeHandling.Default, jsonWriter.StringEscapeHandling);
  7408. string json = sw.ToString();
  7409. Assert.AreEqual(@"{
  7410. ""html"": ""\u003chtml\u003e\u003c/html\u003e""
  7411. }", json);
  7412. }
  7413. public class NoConstructorReadOnlyCollection<T> : ReadOnlyCollection<T>
  7414. {
  7415. public NoConstructorReadOnlyCollection() : base(new List<T>())
  7416. {
  7417. }
  7418. }
  7419. [Test]
  7420. public void NoConstructorReadOnlyCollectionTest()
  7421. {
  7422. ExceptionAssert.Throws<JsonSerializationException>(
  7423. "Cannot deserialize readonly or fixed size list: Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+NoConstructorReadOnlyCollection`1[System.Int32]. Path '', line 1, position 1.",
  7424. () => JsonConvert.DeserializeObject<NoConstructorReadOnlyCollection<int>>("[1]"));
  7425. }
  7426. #if !(NET40 || NET35 || NET20 || PORTABLE40)
  7427. public class NoConstructorReadOnlyDictionary<TKey, TValue> : ReadOnlyDictionary<TKey, TValue>
  7428. {
  7429. public NoConstructorReadOnlyDictionary()
  7430. : base(new Dictionary<TKey, TValue>())
  7431. {
  7432. }
  7433. }
  7434. [Test]
  7435. public void NoConstructorReadOnlyDictionaryTest()
  7436. {
  7437. ExceptionAssert.Throws<JsonSerializationException>(
  7438. "Cannot deserialize readonly or fixed size dictionary: Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+NoConstructorReadOnlyDictionary`2[System.Int32,System.Int32]. Path '1', line 1, position 5.",
  7439. () => JsonConvert.DeserializeObject<NoConstructorReadOnlyDictionary<int, int>>("{'1':1}"));
  7440. }
  7441. #endif
  7442. #if !(PORTABLE || NET35 || NET20 || SILVERLIGHT || PORTABLE40)
  7443. [Test]
  7444. public void ReadTooLargeInteger()
  7445. {
  7446. string json = @"[999999999999999999999999999999999999999999999999]";
  7447. IList<BigInteger> l = JsonConvert.DeserializeObject<IList<BigInteger>>(json);
  7448. Assert.AreEqual(BigInteger.Parse("999999999999999999999999999999999999999999999999"), l[0]);
  7449. ExceptionAssert.Throws<JsonSerializationException>(
  7450. "Error converting value 999999999999999999999999999999999999999999999999 to type 'System.Int64'. Path '[0]', line 1, position 49.",
  7451. () => JsonConvert.DeserializeObject<IList<long>>(json));
  7452. }
  7453. #endif
  7454. [Test]
  7455. public void ReadStringFloatingPointSymbols()
  7456. {
  7457. string json = @"[
  7458. ""NaN"",
  7459. ""Infinity"",
  7460. ""-Infinity""
  7461. ]";
  7462. IList<float> floats = JsonConvert.DeserializeObject<IList<float>>(json);
  7463. Assert.AreEqual(float.NaN, floats[0]);
  7464. Assert.AreEqual(float.PositiveInfinity, floats[1]);
  7465. Assert.AreEqual(float.NegativeInfinity, floats[2]);
  7466. IList<double> doubles = JsonConvert.DeserializeObject<IList<double>>(json);
  7467. Assert.AreEqual(float.NaN, doubles[0]);
  7468. Assert.AreEqual(float.PositiveInfinity, doubles[1]);
  7469. Assert.AreEqual(float.NegativeInfinity, doubles[2]);
  7470. }
  7471. [Test]
  7472. public void DefaultDateStringFormatVsUnsetDateStringFormat()
  7473. {
  7474. IDictionary<string, object> dates = new Dictionary<string, object>
  7475. {
  7476. {"DateTime-Unspecified", new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Unspecified)},
  7477. {"DateTime-Utc", new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)},
  7478. {"DateTime-Local", new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Local)},
  7479. {"DateTimeOffset-Zero", new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero)},
  7480. {"DateTimeOffset-Plus1", new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1))},
  7481. {"DateTimeOffset-Plus15", new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(1.5))}
  7482. };
  7483. string expected = JsonConvert.SerializeObject(dates, Formatting.Indented);
  7484. Console.WriteLine(expected);
  7485. string actual = JsonConvert.SerializeObject(dates, Formatting.Indented, new JsonSerializerSettings
  7486. {
  7487. DateFormatString = JsonSerializerSettings.DefaultDateFormatString
  7488. });
  7489. Console.WriteLine(expected);
  7490. Assert.AreEqual(expected, actual);
  7491. }
  7492. #endif
  7493. #if !NET20
  7494. public class NullableTestClass
  7495. {
  7496. public bool? MyNullableBool { get; set; }
  7497. public int? MyNullableInteger { get; set; }
  7498. public DateTime? MyNullableDateTime { get; set; }
  7499. public DateTimeOffset? MyNullableDateTimeOffset { get; set; }
  7500. public Decimal? MyNullableDecimal { get; set; }
  7501. }
  7502. [Test]
  7503. public void TestStringToNullableDeserialization()
  7504. {
  7505. string json = @"{
  7506. ""MyNullableBool"": """",
  7507. ""MyNullableInteger"": """",
  7508. ""MyNullableDateTime"": """",
  7509. ""MyNullableDateTimeOffset"": """",
  7510. ""MyNullableDecimal"": """"
  7511. }";
  7512. NullableTestClass c2 = JsonConvert.DeserializeObject<NullableTestClass>(json);
  7513. Assert.IsNull(c2.MyNullableBool);
  7514. Assert.IsNull(c2.MyNullableInteger);
  7515. Assert.IsNull(c2.MyNullableDateTime);
  7516. Assert.IsNull(c2.MyNullableDateTimeOffset);
  7517. Assert.IsNull(c2.MyNullableDecimal);
  7518. }
  7519. #endif
  7520. #if !(NET20 || NET35 || PORTABLE40)
  7521. [Test]
  7522. public void HashSetInterface()
  7523. {
  7524. ISet<string> s1 = new HashSet<string>(new[] {"1", "two", "III"});
  7525. string json = JsonConvert.SerializeObject(s1);
  7526. ISet<string> s2 = JsonConvert.DeserializeObject<ISet<string>>(json);
  7527. Assert.AreEqual(s1.Count, s2.Count);
  7528. foreach (string s in s1)
  7529. {
  7530. Assert.IsTrue(s2.Contains(s));
  7531. }
  7532. }
  7533. #endif
  7534. public class NewEmployee : Employee
  7535. {
  7536. public int Age { get; set; }
  7537. public bool ShouldSerializeName()
  7538. {
  7539. return false;
  7540. }
  7541. }
  7542. [Test]
  7543. public void ShouldSerializeInheritedClassTest()
  7544. {
  7545. NewEmployee joe = new NewEmployee();
  7546. joe.Name = "Joe Employee";
  7547. joe.Age = 100;
  7548. Employee mike = new Employee();
  7549. mike.Name = "Mike Manager";
  7550. mike.Manager = mike;
  7551. joe.Manager = mike;
  7552. //StringWriter sw = new StringWriter();
  7553. //XmlSerializer x = new XmlSerializer(typeof(NewEmployee));
  7554. //x.Serialize(sw, joe);
  7555. //Console.WriteLine(sw);
  7556. //JavaScriptSerializer s = new JavaScriptSerializer();
  7557. //Console.WriteLine(s.Serialize(new {html = @"<script>hi</script>; & ! ^ * ( ) ! @ # $ % ^ ' "" - , . / ; : [ { } ] ; ' - _ = + ? ` ~ \ |"}));
  7558. string json = JsonConvert.SerializeObject(joe, Formatting.Indented);
  7559. Assert.AreEqual(@"{
  7560. ""Age"": 100,
  7561. ""Name"": ""Joe Employee"",
  7562. ""Manager"": {
  7563. ""Name"": ""Mike Manager""
  7564. }
  7565. }", json);
  7566. }
  7567. [Test]
  7568. public void DeserializeDecimal()
  7569. {
  7570. JsonTextReader reader = new JsonTextReader(new StringReader("1234567890.123456"));
  7571. var settings = new JsonSerializerSettings();
  7572. var serialiser = JsonSerializer.Create(settings);
  7573. decimal? d = serialiser.Deserialize<decimal?>(reader);
  7574. Assert.AreEqual(1234567890.123456m, d);
  7575. }
  7576. #if !(PORTABLE || SILVERLIGHT || NETFX_CORE || WINDOWS_PHONE || PORTABLE40)
  7577. [Test]
  7578. public void DontSerializeStaticFields()
  7579. {
  7580. string json =
  7581. JsonConvert.SerializeObject(new AnswerFilterModel(), Formatting.Indented, new JsonSerializerSettings
  7582. {
  7583. ContractResolver = new DefaultContractResolver
  7584. {
  7585. IgnoreSerializableAttribute = false
  7586. }
  7587. });
  7588. Assert.AreEqual(@"{
  7589. ""<Active>k__BackingField"": false,
  7590. ""<Ja>k__BackingField"": false,
  7591. ""<Handlungsbedarf>k__BackingField"": false,
  7592. ""<Beratungsbedarf>k__BackingField"": false,
  7593. ""<Unzutreffend>k__BackingField"": false,
  7594. ""<Unbeantwortet>k__BackingField"": false
  7595. }", json);
  7596. }
  7597. #endif
  7598. [Test]
  7599. public void DeserializeNonGenericList()
  7600. {
  7601. IList l = JsonConvert.DeserializeObject<IList>("['string!']");
  7602. Assert.AreEqual(typeof(List<object>), l.GetType());
  7603. Assert.AreEqual(1, l.Count);
  7604. Assert.AreEqual("string!", l[0]);
  7605. }
  7606. #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE || PORTABLE40)
  7607. [Test]
  7608. public void SerializeBigInteger()
  7609. {
  7610. BigInteger i = BigInteger.Parse("123456789999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990");
  7611. string json = JsonConvert.SerializeObject(new [] {i}, Formatting.Indented);
  7612. Assert.AreEqual(@"[
  7613. 123456789999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990
  7614. ]", json);
  7615. }
  7616. #endif
  7617. #if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40)
  7618. [Test]
  7619. public void DeserializeReadOnlyListInterface()
  7620. {
  7621. IReadOnlyList<int> list = JsonConvert.DeserializeObject<IReadOnlyList<int>>("[1,2,3]");
  7622. Assert.AreEqual(3, list.Count);
  7623. Assert.AreEqual(1, list[0]);
  7624. Assert.AreEqual(2, list[1]);
  7625. Assert.AreEqual(3, list[2]);
  7626. }
  7627. [Test]
  7628. public void DeserializeReadOnlyCollectionInterface()
  7629. {
  7630. IReadOnlyCollection<int> list = JsonConvert.DeserializeObject<IReadOnlyCollection<int>>("[1,2,3]");
  7631. Assert.AreEqual(3, list.Count);
  7632. Assert.AreEqual(1, list.ElementAt(0));
  7633. Assert.AreEqual(2, list.ElementAt(1));
  7634. Assert.AreEqual(3, list.ElementAt(2));
  7635. }
  7636. [Test]
  7637. public void DeserializeReadOnlyCollection()
  7638. {
  7639. ReadOnlyCollection<int> list = JsonConvert.DeserializeObject<ReadOnlyCollection<int>>("[1,2,3]");
  7640. Assert.AreEqual(3, list.Count);
  7641. Assert.AreEqual(1, list[0]);
  7642. Assert.AreEqual(2, list[1]);
  7643. Assert.AreEqual(3, list[2]);
  7644. }
  7645. [Test]
  7646. public void DeserializeReadOnlyDictionaryInterface()
  7647. {
  7648. IReadOnlyDictionary<string, int> dic = JsonConvert.DeserializeObject<IReadOnlyDictionary<string, int>>("{'one':1,'two':2}");
  7649. Assert.AreEqual(2, dic.Count);
  7650. Assert.AreEqual(1, dic["one"]);
  7651. Assert.AreEqual(2, dic["two"]);
  7652. CustomAssert.IsInstanceOfType(typeof(ReadOnlyDictionary<string, int>), dic);
  7653. }
  7654. [Test]
  7655. public void DeserializeReadOnlyDictionary()
  7656. {
  7657. ReadOnlyDictionary<string, int> dic = JsonConvert.DeserializeObject<ReadOnlyDictionary<string, int>>("{'one':1,'two':2}");
  7658. Assert.AreEqual(2, dic.Count);
  7659. Assert.AreEqual(1, dic["one"]);
  7660. Assert.AreEqual(2, dic["two"]);
  7661. }
  7662. public class CustomReadOnlyDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue>
  7663. {
  7664. private readonly IDictionary<TKey, TValue> _dictionary;
  7665. public CustomReadOnlyDictionary(IDictionary<TKey, TValue> dictionary)
  7666. {
  7667. _dictionary = dictionary;
  7668. }
  7669. public bool ContainsKey(TKey key)
  7670. {
  7671. return _dictionary.ContainsKey(key);
  7672. }
  7673. public IEnumerable<TKey> Keys
  7674. {
  7675. get { return _dictionary.Keys; }
  7676. }
  7677. public bool TryGetValue(TKey key, out TValue value)
  7678. {
  7679. return _dictionary.TryGetValue(key, out value);
  7680. }
  7681. public IEnumerable<TValue> Values
  7682. {
  7683. get { return _dictionary.Values; }
  7684. }
  7685. public TValue this[TKey key]
  7686. {
  7687. get { return _dictionary[key]; }
  7688. }
  7689. public int Count
  7690. {
  7691. get { return _dictionary.Count; }
  7692. }
  7693. public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
  7694. {
  7695. return _dictionary.GetEnumerator();
  7696. }
  7697. IEnumerator IEnumerable.GetEnumerator()
  7698. {
  7699. return _dictionary.GetEnumerator();
  7700. }
  7701. }
  7702. [Test]
  7703. public void SerializeCustomReadOnlyDictionary()
  7704. {
  7705. IDictionary<string, int> d = new Dictionary<string, int>
  7706. {
  7707. {"one", 1},
  7708. {"two", 2}
  7709. };
  7710. CustomReadOnlyDictionary<string, int> dic = new CustomReadOnlyDictionary<string, int>(d);
  7711. string json = JsonConvert.SerializeObject(dic, Formatting.Indented);
  7712. Assert.AreEqual(@"{
  7713. ""one"": 1,
  7714. ""two"": 2
  7715. }", json);
  7716. }
  7717. public class CustomReadOnlyCollection<T> : IReadOnlyCollection<T>
  7718. {
  7719. private readonly IList<T> _values;
  7720. public CustomReadOnlyCollection (IList<T> values)
  7721. {
  7722. _values = values;
  7723. }
  7724. public int Count
  7725. {
  7726. get { return _values.Count; }
  7727. }
  7728. public IEnumerator<T> GetEnumerator()
  7729. {
  7730. return _values.GetEnumerator();
  7731. }
  7732. IEnumerator IEnumerable.GetEnumerator()
  7733. {
  7734. return _values.GetEnumerator();
  7735. }
  7736. }
  7737. [Test]
  7738. public void SerializeCustomReadOnlyCollection()
  7739. {
  7740. IList<int> l = new List<int>
  7741. {
  7742. 1,
  7743. 2,
  7744. 3
  7745. };
  7746. CustomReadOnlyCollection<int> list = new CustomReadOnlyCollection<int>(l);
  7747. string json = JsonConvert.SerializeObject(list, Formatting.Indented);
  7748. Assert.AreEqual(@"[
  7749. 1,
  7750. 2,
  7751. 3
  7752. ]", json);
  7753. }
  7754. #endif
  7755. public class PrivateDefaultCtorList<T> : List<T>
  7756. {
  7757. private PrivateDefaultCtorList()
  7758. {
  7759. }
  7760. }
  7761. [Test]
  7762. public void DeserializePrivateListCtor()
  7763. {
  7764. ExceptionAssert.Throws<JsonSerializationException>(
  7765. "Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+PrivateDefaultCtorList`1[System.Int32]. Path '', line 1, position 1.",
  7766. () => JsonConvert.DeserializeObject<PrivateDefaultCtorList<int>>("[1,2]")
  7767. );
  7768. var list = JsonConvert.DeserializeObject<PrivateDefaultCtorList<int>>("[1,2]", new JsonSerializerSettings
  7769. {
  7770. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
  7771. });
  7772. Assert.AreEqual(2, list.Count);
  7773. }
  7774. public class PrivateDefaultCtorWithIEnumerableCtorList<T> : List<T>
  7775. {
  7776. private PrivateDefaultCtorWithIEnumerableCtorList()
  7777. {
  7778. }
  7779. public PrivateDefaultCtorWithIEnumerableCtorList(IEnumerable<T> values)
  7780. : base(values)
  7781. {
  7782. Add(default(T));
  7783. }
  7784. }
  7785. [Test]
  7786. public void DeserializePrivateListConstructor()
  7787. {
  7788. var list = JsonConvert.DeserializeObject<PrivateDefaultCtorWithIEnumerableCtorList<int>>("[1,2]");
  7789. Assert.AreEqual(3, list.Count);
  7790. Assert.AreEqual(1, list[0]);
  7791. Assert.AreEqual(2, list[1]);
  7792. Assert.AreEqual(0, list[2]);
  7793. }
  7794. [Test]
  7795. public void DeserializeNonIsoDateDictionaryKey()
  7796. {
  7797. Dictionary<DateTime, string> d = JsonConvert.DeserializeObject<Dictionary<DateTime, string>>(@"{""04/28/2013 00:00:00"":""test""}");
  7798. Assert.AreEqual(1, d.Count);
  7799. DateTime key = DateTime.Parse("04/28/2013 00:00:00", CultureInfo.InvariantCulture);
  7800. Assert.AreEqual("test", d[key]);
  7801. }
  7802. public class IdReferenceResolver : IReferenceResolver
  7803. {
  7804. private readonly IDictionary<Guid, PersonReference> _people = new Dictionary<Guid, PersonReference>();
  7805. public object ResolveReference(object context, string reference)
  7806. {
  7807. Guid id = new Guid(reference);
  7808. PersonReference p;
  7809. _people.TryGetValue(id, out p);
  7810. return p;
  7811. }
  7812. public string GetReference(object context, object value)
  7813. {
  7814. PersonReference p = (PersonReference)value;
  7815. _people[p.Id] = p;
  7816. return p.Id.ToString();
  7817. }
  7818. public bool IsReferenced(object context, object value)
  7819. {
  7820. PersonReference p = (PersonReference)value;
  7821. return _people.ContainsKey(p.Id);
  7822. }
  7823. public void AddReference(object context, string reference, object value)
  7824. {
  7825. Guid id = new Guid(reference);
  7826. _people[id] = (PersonReference)value;
  7827. }
  7828. }
  7829. [Test]
  7830. public void SerializeCustomReferenceResolver()
  7831. {
  7832. PersonReference john = new PersonReference
  7833. {
  7834. Id = new Guid("0B64FFDF-D155-44AD-9689-58D9ADB137F3"),
  7835. Name = "John Smith"
  7836. };
  7837. PersonReference jane = new PersonReference
  7838. {
  7839. Id = new Guid("AE3C399C-058D-431D-91B0-A36C266441B9"),
  7840. Name = "Jane Smith"
  7841. };
  7842. john.Spouse = jane;
  7843. jane.Spouse = john;
  7844. IList<PersonReference> people = new List<PersonReference>
  7845. {
  7846. john,
  7847. jane
  7848. };
  7849. string json = JsonConvert.SerializeObject(people, new JsonSerializerSettings
  7850. {
  7851. ReferenceResolver = new IdReferenceResolver(),
  7852. PreserveReferencesHandling = PreserveReferencesHandling.Objects,
  7853. Formatting = Formatting.Indented
  7854. });
  7855. Assert.AreEqual(@"[
  7856. {
  7857. ""$id"": ""0b64ffdf-d155-44ad-9689-58d9adb137f3"",
  7858. ""Name"": ""John Smith"",
  7859. ""Spouse"": {
  7860. ""$id"": ""ae3c399c-058d-431d-91b0-a36c266441b9"",
  7861. ""Name"": ""Jane Smith"",
  7862. ""Spouse"": {
  7863. ""$ref"": ""0b64ffdf-d155-44ad-9689-58d9adb137f3""
  7864. }
  7865. }
  7866. },
  7867. {
  7868. ""$ref"": ""ae3c399c-058d-431d-91b0-a36c266441b9""
  7869. }
  7870. ]", json);
  7871. }
  7872. public class Foo2
  7873. {
  7874. public string Name { get; set; }
  7875. }
  7876. [Test]
  7877. [Ignore]
  7878. public void SerializeMultipleObjectsFromStream()
  7879. {
  7880. StringReader sr = new StringReader(@"{ ""name"": ""bar"" }{ ""name"": ""baz"" }");
  7881. var reader1 = new JsonTextReader(sr);
  7882. var serializer1 = new JsonSerializer { };
  7883. var foo1 = serializer1.Deserialize<Foo2>(reader1);
  7884. Assert.AreEqual("bar", foo1.Name);
  7885. var reader2 = new JsonTextReader(sr);
  7886. var serializer2 = new JsonSerializer { };
  7887. var foo2 = serializer2.Deserialize<Foo2>(reader2);
  7888. Assert.AreEqual("baz", foo2.Name);
  7889. }
  7890. #if !(PORTABLE || PORTABLE40 || NETFX_CORE)
  7891. [Test]
  7892. public void SerializeDictionaryWithStructKey()
  7893. {
  7894. string json = JsonConvert.SerializeObject(
  7895. new Dictionary<Size, Size> { { new Size(1, 2), new Size(3, 4) } }
  7896. );
  7897. Assert.AreEqual(@"{""1, 2"":""3, 4""}", json);
  7898. Dictionary<Size, Size> d = JsonConvert.DeserializeObject<Dictionary<Size, Size>>(json);
  7899. Assert.AreEqual(new Size(1, 2), d.Keys.First());
  7900. Assert.AreEqual(new Size(3, 4), d.Values.First());
  7901. }
  7902. #endif
  7903. [Test]
  7904. public void DeserializeCustomReferenceResolver()
  7905. {
  7906. string json = @"[
  7907. {
  7908. ""$id"": ""0b64ffdf-d155-44ad-9689-58d9adb137f3"",
  7909. ""Name"": ""John Smith"",
  7910. ""Spouse"": {
  7911. ""$id"": ""ae3c399c-058d-431d-91b0-a36c266441b9"",
  7912. ""Name"": ""Jane Smith"",
  7913. ""Spouse"": {
  7914. ""$ref"": ""0b64ffdf-d155-44ad-9689-58d9adb137f3""
  7915. }
  7916. }
  7917. },
  7918. {
  7919. ""$ref"": ""ae3c399c-058d-431d-91b0-a36c266441b9""
  7920. }
  7921. ]";
  7922. IList<PersonReference> people = JsonConvert.DeserializeObject<IList<PersonReference>>(json, new JsonSerializerSettings
  7923. {
  7924. ReferenceResolver = new IdReferenceResolver(),
  7925. PreserveReferencesHandling = PreserveReferencesHandling.Objects,
  7926. Formatting = Formatting.Indented
  7927. });
  7928. Assert.AreEqual(2, people.Count);
  7929. PersonReference john = people[0];
  7930. PersonReference jane = people[1];
  7931. Assert.AreEqual(john, jane.Spouse);
  7932. Assert.AreEqual(jane, john.Spouse);
  7933. }
  7934. #if !(NETFX_CORE || NET35 || NET20 || PORTABLE || PORTABLE40)
  7935. [TypeConverter(typeof(MyInterfaceConverter))]
  7936. internal interface IMyInterface
  7937. {
  7938. string Name { get; }
  7939. string PrintTest();
  7940. }
  7941. internal class MyInterfaceConverter : TypeConverter
  7942. {
  7943. private readonly List<IMyInterface> _writers = new List<IMyInterface>
  7944. {
  7945. new ConsoleWriter(),
  7946. new TraceWriter()
  7947. };
  7948. public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
  7949. {
  7950. return destinationType == typeof(string);
  7951. }
  7952. public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
  7953. {
  7954. return sourceType == typeof(string);
  7955. }
  7956. public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
  7957. {
  7958. if (value == null)
  7959. return null;
  7960. return (from w in _writers where w.Name == value.ToString() select w).FirstOrDefault();
  7961. }
  7962. public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
  7963. Type destinationType)
  7964. {
  7965. if (value == null)
  7966. return null;
  7967. return ((IMyInterface)value).Name;
  7968. }
  7969. }
  7970. [TypeConverter(typeof(MyInterfaceConverter))]
  7971. internal class ConsoleWriter : IMyInterface
  7972. {
  7973. public string Name
  7974. {
  7975. get { return "Console Writer"; }
  7976. }
  7977. public string PrintTest()
  7978. {
  7979. return "ConsoleWriter";
  7980. }
  7981. public override string ToString()
  7982. {
  7983. return Name;
  7984. }
  7985. }
  7986. internal class TraceWriter : IMyInterface
  7987. {
  7988. public string Name
  7989. {
  7990. get { return "Trace Writer"; }
  7991. }
  7992. public override string ToString()
  7993. {
  7994. return Name;
  7995. }
  7996. public string PrintTest()
  7997. {
  7998. return "TraceWriter";
  7999. }
  8000. }
  8001. internal class TypeConverterJsonConverter : JsonConverter
  8002. {
  8003. private TypeConverter GetConverter(Type type)
  8004. {
  8005. var converters = type.GetCustomAttributes(typeof(TypeConverterAttribute), true).Union(
  8006. from t in type.GetInterfaces()
  8007. from c in t.GetCustomAttributes(typeof(TypeConverterAttribute), true)
  8008. select c).Distinct();
  8009. return
  8010. (from c in converters
  8011. let converter =
  8012. (TypeConverter)Activator.CreateInstance(Type.GetType(((TypeConverterAttribute)c).ConverterTypeName))
  8013. where converter.CanConvertFrom(typeof(string))
  8014. && converter.CanConvertTo(typeof(string))
  8015. select converter)
  8016. .FirstOrDefault();
  8017. }
  8018. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  8019. {
  8020. var converter = GetConverter(value.GetType());
  8021. var text = converter.ConvertToInvariantString(value);
  8022. writer.WriteValue(text);
  8023. }
  8024. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  8025. {
  8026. var converter = GetConverter(objectType);
  8027. return converter.ConvertFromInvariantString(reader.Value.ToString());
  8028. }
  8029. public override bool CanConvert(Type objectType)
  8030. {
  8031. return GetConverter(objectType) != null;
  8032. }
  8033. }
  8034. [Test]
  8035. public void TypeConverterOnInterface()
  8036. {
  8037. var consoleWriter = new ConsoleWriter();
  8038. // If dynamic type handling is enabled, case 1 and 3 work fine
  8039. var options = new JsonSerializerSettings
  8040. {
  8041. Converters = new JsonConverterCollection {new TypeConverterJsonConverter()},
  8042. //TypeNameHandling = TypeNameHandling.All
  8043. };
  8044. //
  8045. // Case 1: Serialize the concrete value and restore it from the interface
  8046. // Therefore we need dynamic handling of type information if the type is not serialized with the type converter directly
  8047. //
  8048. var text1 = JsonConvert.SerializeObject(consoleWriter, Formatting.Indented, options);
  8049. Assert.AreEqual(@"""Console Writer""", text1);
  8050. var restoredWriter = JsonConvert.DeserializeObject<IMyInterface>(text1, options);
  8051. Assert.AreEqual("ConsoleWriter", restoredWriter.PrintTest());
  8052. //
  8053. // Case 2: Serialize a dictionary where the interface is the key
  8054. // The key is always serialized with its ToString() method and therefore needs a mechanism to be restored from that (using the type converter)
  8055. //
  8056. var dict2 = new Dictionary<IMyInterface, string>();
  8057. dict2.Add(consoleWriter, "Console");
  8058. var text2 = JsonConvert.SerializeObject(dict2, Formatting.Indented, options);
  8059. Assert.AreEqual(@"{
  8060. ""Console Writer"": ""Console""
  8061. }", text2);
  8062. var restoredObject = JsonConvert.DeserializeObject<Dictionary<IMyInterface, string>>(text2, options);
  8063. Assert.AreEqual("ConsoleWriter", restoredObject.First().Key.PrintTest());
  8064. //
  8065. // Case 3 Serialize a dictionary where the interface is the value
  8066. // The key is always serialized with its ToString() method and therefore needs a mechanism to be restored from that (using the type converter)
  8067. //
  8068. var dict3 = new Dictionary<string, IMyInterface>();
  8069. dict3.Add("Console", consoleWriter);
  8070. var text3 = JsonConvert.SerializeObject(dict3, Formatting.Indented, options);
  8071. Assert.AreEqual(@"{
  8072. ""Console"": ""Console Writer""
  8073. }", text3);
  8074. var restoredDict2 = JsonConvert.DeserializeObject<Dictionary<string, IMyInterface>>(text3, options);
  8075. Assert.AreEqual("ConsoleWriter", restoredDict2.First().Value.PrintTest());
  8076. }
  8077. #endif
  8078. [Test]
  8079. public void Main()
  8080. {
  8081. ParticipantEntity product = new ParticipantEntity();
  8082. product.Properties = new Dictionary<string, string> { { "s", "d" } };
  8083. string json = JsonConvert.SerializeObject(product);
  8084. Console.WriteLine(json);
  8085. ParticipantEntity deserializedProduct = JsonConvert.DeserializeObject<ParticipantEntity>(json);
  8086. }
  8087. internal class ParticipantEntity
  8088. {
  8089. private Dictionary<string, string> _properties;
  8090. [JsonConstructor]
  8091. public ParticipantEntity()
  8092. {
  8093. }
  8094. /// <summary>
  8095. /// Gets or sets the date and time that the participant was created in the CU.
  8096. /// </summary>
  8097. [JsonProperty(PropertyName = "pa_created", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
  8098. public DateTimeOffset CreationDate { get; internal set; }
  8099. /// <summary>
  8100. /// Gets the properties of the participant.
  8101. /// </summary>
  8102. [JsonProperty(PropertyName = "pa_info")]
  8103. public Dictionary<string, string> Properties
  8104. {
  8105. get { return _properties ?? (_properties = new Dictionary<string, string>()); }
  8106. set { _properties = value; }
  8107. }
  8108. }
  8109. #if !(PORTABLE || NETFX_CORE)
  8110. public class ConvertibleId : IConvertible
  8111. {
  8112. public int Value;
  8113. TypeCode IConvertible.GetTypeCode() { return TypeCode.Object; }
  8114. object IConvertible.ToType(Type conversionType, IFormatProvider provider)
  8115. {
  8116. if (conversionType == typeof(object)) { return this; }
  8117. if (conversionType == typeof(int)) { return (int)Value; }
  8118. if (conversionType == typeof(long)) { return (long)Value; }
  8119. if (conversionType == typeof(string)) { return Value.ToString(CultureInfo.InvariantCulture); }
  8120. throw new InvalidCastException();
  8121. }
  8122. bool IConvertible.ToBoolean(IFormatProvider provider) { throw new InvalidCastException(); }
  8123. byte IConvertible.ToByte(IFormatProvider provider) { throw new InvalidCastException(); }
  8124. char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(); }
  8125. DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(); }
  8126. decimal IConvertible.ToDecimal(IFormatProvider provider) { throw new InvalidCastException(); }
  8127. double IConvertible.ToDouble(IFormatProvider provider) { throw new InvalidCastException(); }
  8128. short IConvertible.ToInt16(IFormatProvider provider) { return (short)Value; }
  8129. int IConvertible.ToInt32(IFormatProvider provider) { return Value; }
  8130. long IConvertible.ToInt64(IFormatProvider provider) { return (long)Value; }
  8131. sbyte IConvertible.ToSByte(IFormatProvider provider) { throw new InvalidCastException(); }
  8132. float IConvertible.ToSingle(IFormatProvider provider) { throw new InvalidCastException(); }
  8133. string IConvertible.ToString(IFormatProvider provider) { throw new InvalidCastException(); }
  8134. ushort IConvertible.ToUInt16(IFormatProvider provider) { throw new InvalidCastException(); }
  8135. uint IConvertible.ToUInt32(IFormatProvider provider) { throw new InvalidCastException(); }
  8136. ulong IConvertible.ToUInt64(IFormatProvider provider) { throw new InvalidCastException(); }
  8137. }
  8138. public class TestClassConvertable
  8139. {
  8140. public ConvertibleId Id;
  8141. public int X;
  8142. }
  8143. [Test]
  8144. public void ConvertibleIdTest()
  8145. {
  8146. var c = new TestClassConvertable { Id = new ConvertibleId { Value = 1 }, X = 2 };
  8147. var s = JsonConvert.SerializeObject(c, Formatting.Indented);
  8148. Assert.AreEqual(@"{
  8149. ""Id"": ""1"",
  8150. ""X"": 2
  8151. }", s);
  8152. }
  8153. #endif
  8154. }
  8155. public class PersonReference
  8156. {
  8157. internal Guid Id { get; set; }
  8158. public string Name { get; set; }
  8159. public PersonReference Spouse { get; set; }
  8160. }
  8161. public enum Antworten
  8162. {
  8163. First,
  8164. Second
  8165. }
  8166. public class SelectListItem
  8167. {
  8168. public string Text { get; set; }
  8169. public string Value { get; set; }
  8170. public bool Selected { get; set; }
  8171. }
  8172. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  8173. [Serializable]
  8174. public class AnswerFilterModel
  8175. {
  8176. [NonSerialized]
  8177. private readonly IList answerValues;
  8178. /// <summary>
  8179. /// Initializes a new instance of the class.
  8180. /// </summary>
  8181. public AnswerFilterModel()
  8182. {
  8183. this.answerValues = (from answer in Enum.GetNames(typeof(Antworten))
  8184. select new SelectListItem { Text = answer, Value = answer, Selected = false })
  8185. .ToList();
  8186. }
  8187. /// <summary>
  8188. /// Gets or sets a value indicating whether active.
  8189. /// </summary>
  8190. public bool Active { get; set; }
  8191. /// <summary>
  8192. /// Gets or sets a value indicating whether ja.
  8193. /// nach bisherigen Antworten.
  8194. /// </summary>
  8195. public bool Ja { get; set; }
  8196. /// <summary>
  8197. /// Gets or sets a value indicating whether handlungsbedarf.
  8198. /// </summary>
  8199. public bool Handlungsbedarf { get; set; }
  8200. /// <summary>
  8201. /// Gets or sets a value indicating whether beratungsbedarf.
  8202. /// </summary>
  8203. public bool Beratungsbedarf { get; set; }
  8204. /// <summary>
  8205. /// Gets or sets a value indicating whether unzutreffend.
  8206. /// </summary>
  8207. public bool Unzutreffend { get; set; }
  8208. /// <summary>
  8209. /// Gets or sets a value indicating whether unbeantwortet.
  8210. /// </summary>
  8211. public bool Unbeantwortet { get; set; }
  8212. /// <summary>
  8213. /// Gets the answer values.
  8214. /// </summary>
  8215. public IEnumerable AnswerValues
  8216. {
  8217. get { return this.answerValues; }
  8218. }
  8219. }
  8220. [Serializable]
  8221. public class PersonSerializable
  8222. {
  8223. public PersonSerializable()
  8224. { }
  8225. private string _name = "";
  8226. public string Name
  8227. {
  8228. get { return _name; }
  8229. set { _name = value; }
  8230. }
  8231. [NonSerialized]
  8232. private int _age = 0;
  8233. public int Age
  8234. {
  8235. get { return _age; }
  8236. set { _age = value; }
  8237. }
  8238. }
  8239. #endif
  8240. public class Event
  8241. {
  8242. public string EventName { get; set; }
  8243. public string Venue { get; set; }
  8244. [JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
  8245. public IList<DateTime> Performances { get; set; }
  8246. }
  8247. public class PropertyItemConverter
  8248. {
  8249. [JsonProperty(ItemConverterType = typeof(MetroStringConverter))]
  8250. public IList<string> Data { get; set; }
  8251. }
  8252. public class PersonWithPrivateConstructor
  8253. {
  8254. private PersonWithPrivateConstructor()
  8255. { }
  8256. public static PersonWithPrivateConstructor CreatePerson()
  8257. {
  8258. return new PersonWithPrivateConstructor();
  8259. }
  8260. public string Name { get; set; }
  8261. public int Age { get; set; }
  8262. }
  8263. public class DateTimeWrapper
  8264. {
  8265. public DateTime Value { get; set; }
  8266. }
  8267. public class Widget1
  8268. {
  8269. public WidgetId1? Id { get; set; }
  8270. }
  8271. [JsonConverter(typeof(WidgetIdJsonConverter))]
  8272. public struct WidgetId1
  8273. {
  8274. public long Value { get; set; }
  8275. }
  8276. public class WidgetIdJsonConverter : JsonConverter
  8277. {
  8278. public override bool CanConvert(Type objectType)
  8279. {
  8280. return objectType == typeof(WidgetId1) || objectType == typeof(WidgetId1?);
  8281. }
  8282. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  8283. {
  8284. WidgetId1 id = (WidgetId1)value;
  8285. writer.WriteValue(id.Value.ToString());
  8286. }
  8287. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  8288. {
  8289. if (reader.TokenType == JsonToken.Null)
  8290. return null;
  8291. return new WidgetId1 { Value = int.Parse(reader.Value.ToString()) };
  8292. }
  8293. }
  8294. public enum MyEnum
  8295. {
  8296. Value1,
  8297. Value2,
  8298. Value3
  8299. }
  8300. public class WithEnums
  8301. {
  8302. public int Id { get; set; }
  8303. public MyEnum? NullableEnum { get; set; }
  8304. }
  8305. public class Item
  8306. {
  8307. public Guid SourceTypeID { get; set; }
  8308. public Guid BrokerID { get; set; }
  8309. public double Latitude { get; set; }
  8310. public double Longitude { get; set; }
  8311. public DateTime TimeStamp { get; set; }
  8312. [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
  8313. public object Payload { get; set; }
  8314. }
  8315. public class NullableGuid
  8316. {
  8317. public Guid? Id { get; set; }
  8318. }
  8319. public class Widget
  8320. {
  8321. public WidgetId? Id { get; set; }
  8322. }
  8323. public struct WidgetId
  8324. {
  8325. public string Value { get; set; }
  8326. }
  8327. public class DecimalTestClass
  8328. {
  8329. public decimal Quantity { get; set; }
  8330. public double OptionalQuantity { get; set; }
  8331. }
  8332. public class TestObject
  8333. {
  8334. public TestObject()
  8335. {
  8336. }
  8337. public TestObject(string name, byte[] data)
  8338. {
  8339. Name = name;
  8340. Data = data;
  8341. }
  8342. public string Name { get; set; }
  8343. public byte[] Data { get; set; }
  8344. }
  8345. public class UriGuidTimeSpanTestClass
  8346. {
  8347. public Guid Guid { get; set; }
  8348. public Guid? NullableGuid { get; set; }
  8349. public TimeSpan TimeSpan { get; set; }
  8350. public TimeSpan? NullableTimeSpan { get; set; }
  8351. public Uri Uri { get; set; }
  8352. }
  8353. internal class Aa
  8354. {
  8355. public int no;
  8356. }
  8357. internal class Bb : Aa
  8358. {
  8359. public new bool no;
  8360. }
  8361. #if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE)
  8362. [JsonObject(MemberSerialization.OptIn)]
  8363. public class GameObject
  8364. {
  8365. [JsonProperty]
  8366. public string Id { get; set; }
  8367. [JsonProperty]
  8368. public string Name { get; set; }
  8369. [JsonProperty] public ConcurrentDictionary<string, Component> Components;
  8370. public GameObject()
  8371. {
  8372. Components = new ConcurrentDictionary<string, Component>();
  8373. }
  8374. }
  8375. [JsonObject(MemberSerialization.OptIn)]
  8376. public class Component
  8377. {
  8378. [JsonIgnore] // Ignore circular reference
  8379. public GameObject GameObject { get; set; }
  8380. public Component()
  8381. {
  8382. }
  8383. }
  8384. [JsonObject(MemberSerialization.OptIn)]
  8385. public class TestComponent : Component
  8386. {
  8387. [JsonProperty]
  8388. public int MyProperty { get; set; }
  8389. public TestComponent()
  8390. {
  8391. }
  8392. }
  8393. #endif
  8394. [JsonObject(MemberSerialization.OptIn)]
  8395. public class TestComponentSimple
  8396. {
  8397. [JsonProperty]
  8398. public int MyProperty { get; set; }
  8399. public TestComponentSimple()
  8400. {
  8401. }
  8402. }
  8403. [JsonObject(ItemRequired = Required.Always)]
  8404. public class RequiredObject
  8405. {
  8406. public int? NonAttributeProperty { get; set; }
  8407. [JsonProperty]
  8408. public int? UnsetProperty { get; set; }
  8409. [JsonProperty(Required = Required.Default)]
  8410. public int? DefaultProperty { get; set; }
  8411. [JsonProperty(Required = Required.AllowNull)]
  8412. public int? AllowNullProperty { get; set; }
  8413. [JsonProperty(Required = Required.Always)]
  8414. public int? AlwaysProperty { get; set; }
  8415. }
  8416. public class MetroStringConverter : JsonConverter
  8417. {
  8418. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  8419. {
  8420. #if !(SILVERLIGHT || NETFX_CORE)
  8421. writer.WriteValue(":::" + value.ToString().ToUpper(CultureInfo.InvariantCulture) + ":::");
  8422. #else
  8423. writer.WriteValue(":::" + value.ToString().ToUpper() + ":::");
  8424. #endif
  8425. }
  8426. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  8427. {
  8428. string s = (string)reader.Value;
  8429. if (s == null)
  8430. return null;
  8431. #if !(SILVERLIGHT || NETFX_CORE)
  8432. return s.ToLower(CultureInfo.InvariantCulture).Trim(new[] { ':' });
  8433. #else
  8434. return s.ToLower().Trim(new[] { ':' });
  8435. #endif
  8436. }
  8437. public override bool CanConvert(Type objectType)
  8438. {
  8439. return objectType == typeof(string);
  8440. }
  8441. }
  8442. public class MetroPropertyNameResolver : DefaultContractResolver
  8443. {
  8444. protected internal override string ResolvePropertyName(string propertyName)
  8445. {
  8446. #if !(SILVERLIGHT || NETFX_CORE)
  8447. return ":::" + propertyName.ToUpper(CultureInfo.InvariantCulture) + ":::";
  8448. #else
  8449. return ":::" + propertyName.ToUpper() + ":::";
  8450. #endif
  8451. }
  8452. }
  8453. #if !(NET20 || NET35)
  8454. [DataContract]
  8455. public class DataContractSerializationAttributesClass
  8456. {
  8457. public string NoAttribute { get; set; }
  8458. [IgnoreDataMember]
  8459. public string IgnoreDataMemberAttribute { get; set; }
  8460. [DataMember]
  8461. public string DataMemberAttribute { get; set; }
  8462. [IgnoreDataMember]
  8463. [DataMember]
  8464. public string IgnoreDataMemberAndDataMemberAttribute { get; set; }
  8465. }
  8466. public class PocoDataContractSerializationAttributesClass
  8467. {
  8468. public string NoAttribute { get; set; }
  8469. [IgnoreDataMember]
  8470. public string IgnoreDataMemberAttribute { get; set; }
  8471. [DataMember]
  8472. public string DataMemberAttribute { get; set; }
  8473. [IgnoreDataMember]
  8474. [DataMember]
  8475. public string IgnoreDataMemberAndDataMemberAttribute { get; set; }
  8476. }
  8477. #endif
  8478. public class Array2D
  8479. {
  8480. public string Before { get; set; }
  8481. public int[,] Coordinates { get; set; }
  8482. public string After { get; set; }
  8483. }
  8484. public class Array3D
  8485. {
  8486. public string Before { get; set; }
  8487. public int[,,] Coordinates { get; set; }
  8488. public string After { get; set; }
  8489. }
  8490. public class Array3DWithConverter
  8491. {
  8492. public string Before { get; set; }
  8493. [JsonProperty(ItemConverterType = typeof(IntToFloatConverter))]
  8494. public int[, ,] Coordinates { get; set; }
  8495. public string After { get; set; }
  8496. }
  8497. public class IntToFloatConverter : JsonConverter
  8498. {
  8499. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  8500. {
  8501. writer.WriteValue(Convert.ToDouble(value));
  8502. }
  8503. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  8504. {
  8505. return Convert.ToInt32(reader.Value);
  8506. }
  8507. public override bool CanConvert(Type objectType)
  8508. {
  8509. return objectType == typeof (int);
  8510. }
  8511. }
  8512. public class ShouldSerializeTestClass
  8513. {
  8514. internal bool _shouldSerializeName;
  8515. public string Name { get; set; }
  8516. public int Age { get; set; }
  8517. public void ShouldSerializeAge()
  8518. {
  8519. // dummy. should never be used because it doesn't return bool
  8520. }
  8521. public bool ShouldSerializeName()
  8522. {
  8523. return _shouldSerializeName;
  8524. }
  8525. }
  8526. public class SpecifiedTestClass
  8527. {
  8528. private bool _nameSpecified;
  8529. public string Name { get; set; }
  8530. public int Age { get; set; }
  8531. public int Weight { get; set; }
  8532. public int Height { get; set; }
  8533. public int FavoriteNumber { get; set; }
  8534. // dummy. should never be used because it isn't of type bool
  8535. [JsonIgnore]
  8536. public long AgeSpecified { get; set; }
  8537. [JsonIgnore]
  8538. public bool NameSpecified
  8539. {
  8540. get { return _nameSpecified; }
  8541. set { _nameSpecified = value; }
  8542. }
  8543. [JsonIgnore]
  8544. public bool WeightSpecified;
  8545. [JsonIgnore]
  8546. [System.Xml.Serialization.XmlIgnoreAttribute]
  8547. public bool HeightSpecified;
  8548. [JsonIgnore]
  8549. public bool FavoriteNumberSpecified
  8550. {
  8551. // get only example
  8552. get { return FavoriteNumber != 0; }
  8553. }
  8554. }
  8555. public class DirectoryAccount
  8556. {
  8557. // normal deserialization
  8558. public string DisplayName { get; set; }
  8559. // these properties are set in OnDeserialized
  8560. public string UserName { get; set; }
  8561. public string Domain { get; set; }
  8562. [JsonExtensionData]
  8563. private IDictionary<string, JToken> _additionalData;
  8564. [OnDeserialized]
  8565. private void OnDeserialized(StreamingContext context)
  8566. {
  8567. // SAMAccountName is not deserialized to any property
  8568. // and so it is added to the extension data dictionary
  8569. string samAccountName = (string)_additionalData["SAMAccountName"];
  8570. Domain = samAccountName.Split('\\')[0];
  8571. UserName = samAccountName.Split('\\')[1];
  8572. }
  8573. public DirectoryAccount()
  8574. {
  8575. _additionalData = new Dictionary<string, JToken>();
  8576. }
  8577. }
  8578. #if !NETFX_CORE
  8579. public struct Ratio : IConvertible, IFormattable, ISerializable
  8580. {
  8581. private readonly int _numerator;
  8582. private readonly int _denominator;
  8583. public Ratio(int numerator, int denominator)
  8584. {
  8585. _numerator = numerator;
  8586. _denominator = denominator;
  8587. }
  8588. #region Properties
  8589. public int Numerator
  8590. {
  8591. get { return _numerator; }
  8592. }
  8593. public int Denominator
  8594. {
  8595. get { return _denominator; }
  8596. }
  8597. public bool IsNan
  8598. {
  8599. get { return _denominator == 0; }
  8600. }
  8601. #endregion
  8602. #region Serialization operations
  8603. public Ratio(SerializationInfo info, StreamingContext context)
  8604. {
  8605. _numerator = info.GetInt32("n");
  8606. _denominator = info.GetInt32("d");
  8607. }
  8608. public void GetObjectData(SerializationInfo info, StreamingContext context)
  8609. {
  8610. info.AddValue("n", _numerator);
  8611. info.AddValue("d", _denominator);
  8612. }
  8613. #endregion
  8614. #region IConvertible Members
  8615. public TypeCode GetTypeCode()
  8616. {
  8617. return TypeCode.Object;
  8618. }
  8619. public bool ToBoolean(IFormatProvider provider)
  8620. {
  8621. return this._numerator == 0;
  8622. }
  8623. public byte ToByte(IFormatProvider provider)
  8624. {
  8625. return (byte)(this._numerator / this._denominator);
  8626. }
  8627. public char ToChar(IFormatProvider provider)
  8628. {
  8629. return Convert.ToChar(this._numerator / this._denominator);
  8630. }
  8631. public DateTime ToDateTime(IFormatProvider provider)
  8632. {
  8633. return Convert.ToDateTime(this._numerator / this._denominator);
  8634. }
  8635. public decimal ToDecimal(IFormatProvider provider)
  8636. {
  8637. return (decimal)this._numerator / this._denominator;
  8638. }
  8639. public double ToDouble(IFormatProvider provider)
  8640. {
  8641. return this._denominator == 0
  8642. ? double.NaN
  8643. : (double)this._numerator / this._denominator;
  8644. }
  8645. public short ToInt16(IFormatProvider provider)
  8646. {
  8647. return (short)(this._numerator / this._denominator);
  8648. }
  8649. public int ToInt32(IFormatProvider provider)
  8650. {
  8651. return this._numerator / this._denominator;
  8652. }
  8653. public long ToInt64(IFormatProvider provider)
  8654. {
  8655. return this._numerator / this._denominator;
  8656. }
  8657. public sbyte ToSByte(IFormatProvider provider)
  8658. {
  8659. return (sbyte)(this._numerator / this._denominator);
  8660. }
  8661. public float ToSingle(IFormatProvider provider)
  8662. {
  8663. return this._denominator == 0
  8664. ? float.NaN
  8665. : (float)this._numerator / this._denominator;
  8666. }
  8667. public string ToString(IFormatProvider provider)
  8668. {
  8669. return this._denominator == 1
  8670. ? this._numerator.ToString(provider)
  8671. : this._numerator.ToString(provider) + "/" + this._denominator.ToString(provider);
  8672. }
  8673. public object ToType(Type conversionType, IFormatProvider provider)
  8674. {
  8675. return Convert.ChangeType(ToDouble(provider), conversionType, provider);
  8676. }
  8677. public ushort ToUInt16(IFormatProvider provider)
  8678. {
  8679. return (ushort)(this._numerator / this._denominator);
  8680. }
  8681. public uint ToUInt32(IFormatProvider provider)
  8682. {
  8683. return (uint)(this._numerator / this._denominator);
  8684. }
  8685. public ulong ToUInt64(IFormatProvider provider)
  8686. {
  8687. return (ulong)(this._numerator / this._denominator);
  8688. }
  8689. #endregion
  8690. #region String operations
  8691. public override string ToString()
  8692. {
  8693. return ToString(CultureInfo.InvariantCulture);
  8694. }
  8695. public string ToString(string format, IFormatProvider formatProvider)
  8696. {
  8697. return ToString(CultureInfo.InvariantCulture);
  8698. }
  8699. public static Ratio Parse(string input)
  8700. {
  8701. return Parse(input, CultureInfo.InvariantCulture);
  8702. }
  8703. public static Ratio Parse(string input, IFormatProvider formatProvider)
  8704. {
  8705. Ratio result;
  8706. if (!TryParse(input, formatProvider, out result))
  8707. {
  8708. throw new FormatException(
  8709. string.Format(
  8710. CultureInfo.InvariantCulture,
  8711. "Text '{0}' is invalid text representation of ratio",
  8712. input));
  8713. }
  8714. return result;
  8715. }
  8716. public static bool TryParse(string input, out Ratio result)
  8717. {
  8718. return TryParse(input, CultureInfo.InvariantCulture, out result);
  8719. }
  8720. public static bool TryParse(string input, IFormatProvider formatProvider, out Ratio result)
  8721. {
  8722. if (input != null)
  8723. {
  8724. var fractionIndex = input.IndexOf('/');
  8725. int numerator;
  8726. if (fractionIndex < 0)
  8727. {
  8728. if (int.TryParse(input, NumberStyles.Integer, formatProvider, out numerator))
  8729. {
  8730. result = new Ratio(numerator, 1);
  8731. return true;
  8732. }
  8733. }
  8734. else
  8735. {
  8736. int denominator;
  8737. if (int.TryParse(input.Substring(0, fractionIndex), NumberStyles.Integer, formatProvider, out numerator) &&
  8738. int.TryParse(input.Substring(fractionIndex + 1), NumberStyles.Integer, formatProvider, out denominator))
  8739. {
  8740. result = new Ratio(numerator, denominator);
  8741. return true;
  8742. }
  8743. }
  8744. }
  8745. result = default(Ratio);
  8746. return false;
  8747. }
  8748. #endregion
  8749. }
  8750. #endif
  8751. }