PageRenderTime 131ms CodeModel.GetById 41ms RepoModel.GetById 1ms app.codeStats 1ms

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

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