PageRenderTime 56ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 1ms

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

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