PageRenderTime 47ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/trunk/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs

#
C# | 321 lines | 294 code | 5 blank | 22 comment | 0 complexity | 0db427234164477637b981f85a172085 MD5 | raw file
  1. #region License
  2. // Copyright (c) 2007 James Newton-King
  3. //
  4. // Permission is hereby granted, free of charge, to any person
  5. // obtaining a copy of this software and associated documentation
  6. // files (the "Software"), to deal in the Software without
  7. // restriction, including without limitation the rights to use,
  8. // copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the
  10. // Software is furnished to do so, subject to the following
  11. // conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  18. // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  20. // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21. // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23. // OTHER DEALINGS IN THE SOFTWARE.
  24. #endregion
  25. using System;
  26. using System.Collections.Generic;
  27. using System.Linq;
  28. using System.Text;
  29. using Newtonsoft.Json.Linq;
  30. using Newtonsoft.Json.Tests.TestObjects;
  31. using NUnit.Framework;
  32. namespace Newtonsoft.Json.Tests.Serialization
  33. {
  34. public class TypeNameHandlingTests : TestFixtureBase
  35. {
  36. [Test]
  37. public void WriteTypeNameForObjects()
  38. {
  39. string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
  40. EmployeeReference employee = new EmployeeReference();
  41. string json = JsonConvert.SerializeObject(employee, Formatting.Indented, new JsonSerializerSettings
  42. {
  43. TypeNameHandling = TypeNameHandling.Objects
  44. });
  45. Assert.AreEqual(@"{
  46. ""$id"": ""1"",
  47. ""$type"": """ + employeeRef + @""",
  48. ""Name"": null,
  49. ""Manager"": null
  50. }", json);
  51. }
  52. [Test]
  53. public void DeserializeTypeName()
  54. {
  55. string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
  56. string json = @"{
  57. ""$id"": ""1"",
  58. ""$type"": """ + employeeRef + @""",
  59. ""Name"": ""Name!"",
  60. ""Manager"": null
  61. }";
  62. object employee = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
  63. {
  64. TypeNameHandling = TypeNameHandling.Objects
  65. });
  66. Assert.IsInstanceOfType(typeof(EmployeeReference), employee);
  67. Assert.AreEqual("Name!", ((EmployeeReference)employee).Name);
  68. }
  69. [Test]
  70. public void SerializeGenericObjectListWithTypeName()
  71. {
  72. string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
  73. string personRef = typeof(Person).AssemblyQualifiedName;
  74. List<object> values = new List<object>
  75. {
  76. new EmployeeReference
  77. {
  78. Name = "Bob",
  79. Manager = new EmployeeReference {Name = "Frank"}
  80. },
  81. new Person
  82. {
  83. Department = "Department",
  84. BirthDate = new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc),
  85. LastModified = new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc)
  86. },
  87. "String!",
  88. int.MinValue
  89. };
  90. string json = JsonConvert.SerializeObject(values, Formatting.Indented, new JsonSerializerSettings
  91. {
  92. TypeNameHandling = TypeNameHandling.Objects
  93. });
  94. Assert.AreEqual(@"[
  95. {
  96. ""$id"": ""1"",
  97. ""$type"": """ + employeeRef + @""",
  98. ""Name"": ""Bob"",
  99. ""Manager"": {
  100. ""$id"": ""2"",
  101. ""$type"": """ + employeeRef + @""",
  102. ""Name"": ""Frank"",
  103. ""Manager"": null
  104. }
  105. },
  106. {
  107. ""$type"": """ + personRef + @""",
  108. ""Name"": null,
  109. ""BirthDate"": ""\/Date(978134400000)\/"",
  110. ""LastModified"": ""\/Date(978134400000)\/""
  111. },
  112. ""String!"",
  113. -2147483648
  114. ]", json);
  115. }
  116. [Test]
  117. public void DeserializeGenericObjectListWithTypeName()
  118. {
  119. string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
  120. string personRef = typeof(Person).AssemblyQualifiedName;
  121. string json = @"[
  122. {
  123. ""$id"": ""1"",
  124. ""$type"": """ + employeeRef + @""",
  125. ""Name"": ""Bob"",
  126. ""Manager"": {
  127. ""$id"": ""2"",
  128. ""$type"": """ + employeeRef + @""",
  129. ""Name"": ""Frank"",
  130. ""Manager"": null
  131. }
  132. },
  133. {
  134. ""$type"": """ + personRef + @""",
  135. ""Name"": null,
  136. ""BirthDate"": ""\/Date(978134400000)\/"",
  137. ""LastModified"": ""\/Date(978134400000)\/""
  138. },
  139. ""String!"",
  140. -2147483648
  141. ]";
  142. List<object> values = (List<object>)JsonConvert.DeserializeObject(json, typeof(List<object>), new JsonSerializerSettings
  143. {
  144. TypeNameHandling = TypeNameHandling.Objects
  145. });
  146. Assert.AreEqual(4, values.Count);
  147. EmployeeReference e = (EmployeeReference)values[0];
  148. Person p = (Person)values[1];
  149. Assert.AreEqual("Bob", e.Name);
  150. Assert.AreEqual("Frank", e.Manager.Name);
  151. Assert.AreEqual(null, p.Name);
  152. Assert.AreEqual(new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc), p.BirthDate);
  153. Assert.AreEqual(new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc), p.LastModified);
  154. Assert.AreEqual("String!", values[2]);
  155. Assert.AreEqual(int.MinValue, values[3]);
  156. }
  157. [Test]
  158. [ExpectedException(typeof(JsonSerializationException))]
  159. public void DeserializeWithBadTypeName()
  160. {
  161. string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
  162. string json = @"{
  163. ""$id"": ""1"",
  164. ""$type"": """ + employeeRef + @""",
  165. ""Name"": ""Name!"",
  166. ""Manager"": null
  167. }";
  168. JsonConvert.DeserializeObject(json, typeof(Person), new JsonSerializerSettings
  169. {
  170. TypeNameHandling = TypeNameHandling.Objects
  171. });
  172. }
  173. [Test]
  174. public void DeserializeTypeNameWithNoTypeNameHandling()
  175. {
  176. string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
  177. string json = @"{
  178. ""$id"": ""1"",
  179. ""$type"": """ + employeeRef + @""",
  180. ""Name"": ""Name!"",
  181. ""Manager"": null
  182. }";
  183. JObject o = (JObject)JsonConvert.DeserializeObject(json);
  184. Assert.AreEqual(@"{
  185. ""Name"": ""Name!"",
  186. ""Manager"": null
  187. }", o.ToString());
  188. }
  189. [Test]
  190. [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved.")]
  191. public void DeserializeTypeNameOnly()
  192. {
  193. string json = @"{
  194. ""$id"": ""1"",
  195. ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Employee"",
  196. ""Name"": ""Name!"",
  197. ""Manager"": null
  198. }";
  199. JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
  200. {
  201. TypeNameHandling = TypeNameHandling.Objects
  202. });
  203. }
  204. public interface ICorrelatedMessage
  205. {
  206. string CorrelationId { get; set; }
  207. }
  208. public class SendHttpRequest : ICorrelatedMessage
  209. {
  210. public SendHttpRequest()
  211. {
  212. RequestEncoding = "UTF-8";
  213. Method = "GET";
  214. }
  215. public string Method { get; set; }
  216. public Dictionary<string, string> Headers { get; set; }
  217. public string Url { get; set; }
  218. public Dictionary<string, string> RequestData;
  219. public string RequestBodyText { get; set; }
  220. public string User { get; set; }
  221. public string Passwd { get; set; }
  222. public string RequestEncoding { get; set; }
  223. public string CorrelationId { get; set; }
  224. }
  225. [Test]
  226. public void DeserializeGenericTypeName()
  227. {
  228. string typeName = typeof(SendHttpRequest).AssemblyQualifiedName;
  229. string json = @"{
  230. ""$type"": """ + typeName + @""",
  231. ""RequestData"": {
  232. ""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"",
  233. ""Id"": ""siedemnaƛcie"",
  234. ""X"": ""323""
  235. },
  236. ""Method"": ""GET"",
  237. ""Url"": ""http://www.onet.pl"",
  238. ""RequestEncoding"": ""UTF-8"",
  239. ""CorrelationId"": ""xyz""
  240. }";
  241. ICorrelatedMessage message = JsonConvert.DeserializeObject<ICorrelatedMessage>(json, new JsonSerializerSettings
  242. {
  243. TypeNameHandling = TypeNameHandling.Objects
  244. });
  245. Assert.IsInstanceOfType(typeof(SendHttpRequest), message);
  246. SendHttpRequest request = (SendHttpRequest)message;
  247. Assert.AreEqual("xyz", request.CorrelationId);
  248. Assert.AreEqual(2, request.RequestData.Count);
  249. Assert.AreEqual("siedemnaƛcie", request.RequestData["Id"]);
  250. }
  251. [Test]
  252. public void SerializeObjectWithMultipleGenericLists()
  253. {
  254. string containerTypeName = typeof(Container).AssemblyQualifiedName;
  255. string productTypeName = typeof(Product).AssemblyQualifiedName;
  256. Container container = new Container
  257. {
  258. In = new List<Product>(),
  259. Out = new List<Product>()
  260. };
  261. string json = JsonConvert.SerializeObject(container, Formatting.Indented,
  262. new JsonSerializerSettings
  263. {
  264. NullValueHandling = NullValueHandling.Ignore,
  265. TypeNameHandling = TypeNameHandling.All
  266. });
  267. Assert.AreEqual(@"{
  268. ""$type"": """ + containerTypeName + @""",
  269. ""In"": {
  270. ""$type"": ""System.Collections.Generic.List`1[[" + productTypeName + @"]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"",
  271. ""$values"": []
  272. },
  273. ""Out"": {
  274. ""$type"": ""System.Collections.Generic.List`1[[" + productTypeName + @"]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"",
  275. ""$values"": []
  276. }
  277. }", json);
  278. }
  279. }
  280. }