DataContractJsonSerializerTest.cs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  1. //
  2. // DataContractJsonSerializerTest.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. // Ankit Jain <[email protected]>
  7. //
  8. // Copyright (C) 2005-2007 Novell, Inc. http://www.novell.com
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. //
  30. // This test code contains tests for DataContractJsonSerializer, which is
  31. // imported from DataContractSerializerTest.cs.
  32. //
  33. using System;
  34. using System.Collections.Generic;
  35. using System.Collections.ObjectModel;
  36. using System.IO;
  37. using System.Net;
  38. using System.Runtime.Serialization;
  39. using System.Runtime.Serialization.Json;
  40. using System.Text;
  41. using System.Xml;
  42. using NUnit.Framework;
  43. namespace MonoTests.System.Runtime.Serialization.Json
  44. {
  45. [TestFixture]
  46. public class DataContractJsonSerializerTest
  47. {
  48. static readonly XmlWriterSettings settings;
  49. static DataContractJsonSerializerTest ()
  50. {
  51. settings = new XmlWriterSettings ();
  52. settings.OmitXmlDeclaration = true;
  53. }
  54. [DataContract]
  55. class Sample1
  56. {
  57. [DataMember]
  58. public string Member1;
  59. }
  60. [Test]
  61. [ExpectedException (typeof (ArgumentNullException))]
  62. public void ConstructorTypeNull ()
  63. {
  64. new DataContractJsonSerializer (null);
  65. }
  66. [Test]
  67. public void ConstructorKnownTypesNull ()
  68. {
  69. // null knownTypes is allowed.
  70. new DataContractJsonSerializer (typeof (Sample1), (IEnumerable<Type>) null);
  71. new DataContractJsonSerializer (typeof (Sample1), "Foo", null);
  72. }
  73. [Test]
  74. [ExpectedException (typeof (ArgumentNullException))]
  75. public void ConstructorNameNull ()
  76. {
  77. new DataContractJsonSerializer (typeof (Sample1), (string) null);
  78. }
  79. [Test]
  80. [ExpectedException (typeof (ArgumentOutOfRangeException))]
  81. public void ConstructorNegativeMaxObjects ()
  82. {
  83. new DataContractJsonSerializer (typeof (Sample1), "Sample1",
  84. null, -1, false, null, false);
  85. }
  86. [Test]
  87. public void ConstructorMisc ()
  88. {
  89. new DataContractJsonSerializer (typeof (GlobalSample1)).WriteObject (new MemoryStream (), new GlobalSample1 ());
  90. }
  91. [Test]
  92. public void WriteObjectContent ()
  93. {
  94. StringWriter sw = new StringWriter ();
  95. using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
  96. DataContractJsonSerializer ser =
  97. new DataContractJsonSerializer (typeof (string));
  98. xw.WriteStartElement ("my-element");
  99. ser.WriteObjectContent (xw, "TEST STRING");
  100. xw.WriteEndElement ();
  101. }
  102. Assert.AreEqual ("<my-element>TEST STRING</my-element>",
  103. sw.ToString ());
  104. }
  105. // int
  106. [Test]
  107. public void SerializeIntXml ()
  108. {
  109. StringWriter sw = new StringWriter ();
  110. SerializeInt (XmlWriter.Create (sw, settings));
  111. Assert.AreEqual (
  112. @"<root type=""number"">1</root>",
  113. sw.ToString ());
  114. }
  115. [Test]
  116. public void SerializeIntJson ()
  117. {
  118. MemoryStream ms = new MemoryStream ();
  119. SerializeInt (JsonReaderWriterFactory.CreateJsonWriter (ms));
  120. Assert.AreEqual (
  121. "1",
  122. Encoding.UTF8.GetString (ms.ToArray ()));
  123. }
  124. void SerializeInt (XmlWriter writer)
  125. {
  126. DataContractJsonSerializer ser =
  127. new DataContractJsonSerializer (typeof (int));
  128. using (XmlWriter w = writer) {
  129. ser.WriteObject (w, 1);
  130. }
  131. }
  132. // int, with rootName
  133. [Test]
  134. public void SerializeIntXmlWithRootName ()
  135. {
  136. StringWriter sw = new StringWriter ();
  137. SerializeIntWithRootName (XmlWriter.Create (sw, settings));
  138. Assert.AreEqual (
  139. @"<myroot type=""number"">1</myroot>",
  140. sw.ToString ());
  141. }
  142. [Test]
  143. // since JsonWriter supports only "root" as the root name, using
  144. // XmlWriter from JsonReaderWriterFactory will always fail with
  145. // an explicit rootName.
  146. [ExpectedException (typeof (SerializationException))]
  147. public void SerializeIntJsonWithRootName ()
  148. {
  149. MemoryStream ms = new MemoryStream ();
  150. SerializeIntWithRootName (JsonReaderWriterFactory.CreateJsonWriter (ms));
  151. Assert.AreEqual (
  152. "1",
  153. Encoding.UTF8.GetString (ms.ToArray ()));
  154. }
  155. void SerializeIntWithRootName (XmlWriter writer)
  156. {
  157. DataContractJsonSerializer ser =
  158. new DataContractJsonSerializer (typeof (int), "myroot");
  159. using (XmlWriter w = writer) {
  160. ser.WriteObject (w, 1);
  161. }
  162. }
  163. // pass typeof(DCEmpty), serialize int
  164. [Test]
  165. public void SerializeIntForDCEmptyXml ()
  166. {
  167. StringWriter sw = new StringWriter ();
  168. SerializeIntForDCEmpty (XmlWriter.Create (sw, settings));
  169. Assert.AreEqual (
  170. @"<root type=""number"">1</root>",
  171. sw.ToString ());
  172. }
  173. [Test]
  174. public void SerializeIntForDCEmptyJson ()
  175. {
  176. MemoryStream ms = new MemoryStream ();
  177. SerializeIntForDCEmpty (JsonReaderWriterFactory.CreateJsonWriter (ms));
  178. Assert.AreEqual (
  179. "1",
  180. Encoding.UTF8.GetString (ms.ToArray ()));
  181. }
  182. void SerializeIntForDCEmpty (XmlWriter writer)
  183. {
  184. DataContractJsonSerializer ser =
  185. new DataContractJsonSerializer (typeof (DCEmpty));
  186. using (XmlWriter w = writer) {
  187. ser.WriteObject (w, 1);
  188. }
  189. }
  190. // DCEmpty
  191. [Test]
  192. public void SerializeEmptyClassXml ()
  193. {
  194. StringWriter sw = new StringWriter ();
  195. SerializeEmptyClass (XmlWriter.Create (sw, settings));
  196. Assert.AreEqual (
  197. @"<root type=""object"" />",
  198. sw.ToString ());
  199. }
  200. [Test]
  201. public void SerializeEmptyClassJson ()
  202. {
  203. MemoryStream ms = new MemoryStream ();
  204. SerializeEmptyClass (JsonReaderWriterFactory.CreateJsonWriter (ms));
  205. Assert.AreEqual (
  206. "{}",
  207. Encoding.UTF8.GetString (ms.ToArray ()));
  208. }
  209. void SerializeEmptyClass (XmlWriter writer)
  210. {
  211. DataContractJsonSerializer ser =
  212. new DataContractJsonSerializer (typeof (DCEmpty));
  213. using (XmlWriter w = writer) {
  214. ser.WriteObject (w, new DCEmpty ());
  215. }
  216. }
  217. // string (primitive)
  218. [Test]
  219. public void SerializePrimitiveStringXml ()
  220. {
  221. StringWriter sw = new StringWriter ();
  222. SerializePrimitiveString (XmlWriter.Create (sw, settings));
  223. Assert.AreEqual (
  224. "<root>TEST</root>",
  225. sw.ToString ());
  226. }
  227. [Test]
  228. public void SerializePrimitiveStringJson ()
  229. {
  230. MemoryStream ms = new MemoryStream ();
  231. SerializePrimitiveString (JsonReaderWriterFactory.CreateJsonWriter (ms));
  232. Assert.AreEqual (
  233. @"""TEST""",
  234. Encoding.UTF8.GetString (ms.ToArray ()));
  235. }
  236. void SerializePrimitiveString (XmlWriter writer)
  237. {
  238. XmlObjectSerializer ser =
  239. new DataContractJsonSerializer (typeof (string));
  240. using (XmlWriter w = writer) {
  241. ser.WriteObject (w, "TEST");
  242. }
  243. }
  244. // QName (primitive but ...)
  245. [Test]
  246. public void SerializePrimitiveQNameXml ()
  247. {
  248. StringWriter sw = new StringWriter ();
  249. SerializePrimitiveQName (XmlWriter.Create (sw, settings));
  250. Assert.AreEqual (
  251. "<root>foo:urn:foo</root>",
  252. sw.ToString ());
  253. }
  254. [Test]
  255. public void SerializePrimitiveQNameJson ()
  256. {
  257. MemoryStream ms = new MemoryStream ();
  258. SerializePrimitiveQName (JsonReaderWriterFactory.CreateJsonWriter (ms));
  259. Assert.AreEqual (
  260. @"""foo:urn:foo""",
  261. Encoding.UTF8.GetString (ms.ToArray ()));
  262. }
  263. void SerializePrimitiveQName (XmlWriter writer)
  264. {
  265. XmlObjectSerializer ser =
  266. new DataContractJsonSerializer (typeof (XmlQualifiedName));
  267. using (XmlWriter w = writer) {
  268. ser.WriteObject (w, new XmlQualifiedName ("foo", "urn:foo"));
  269. }
  270. }
  271. // DBNull (primitive)
  272. [Test]
  273. public void SerializeDBNullXml ()
  274. {
  275. StringWriter sw = new StringWriter ();
  276. SerializeDBNull (XmlWriter.Create (sw, settings));
  277. Assert.AreEqual (
  278. @"<root type=""object"" />",
  279. sw.ToString ());
  280. }
  281. [Test]
  282. public void SerializeDBNullJson ()
  283. {
  284. MemoryStream ms = new MemoryStream ();
  285. SerializeDBNull (JsonReaderWriterFactory.CreateJsonWriter (ms));
  286. Assert.AreEqual (
  287. "{}",
  288. Encoding.UTF8.GetString (ms.ToArray ()));
  289. }
  290. void SerializeDBNull (XmlWriter writer)
  291. {
  292. DataContractJsonSerializer ser =
  293. new DataContractJsonSerializer (typeof (DBNull));
  294. using (XmlWriter w = writer) {
  295. ser.WriteObject (w, DBNull.Value);
  296. }
  297. }
  298. // DCSimple1
  299. [Test]
  300. public void SerializeSimpleClass1Xml ()
  301. {
  302. StringWriter sw = new StringWriter ();
  303. SerializeSimpleClass1 (XmlWriter.Create (sw, settings));
  304. Assert.AreEqual (
  305. @"<root type=""object""><Foo>TEST</Foo></root>",
  306. sw.ToString ());
  307. }
  308. [Test]
  309. public void SerializeSimpleClass1Json ()
  310. {
  311. MemoryStream ms = new MemoryStream ();
  312. SerializeSimpleClass1 (JsonReaderWriterFactory.CreateJsonWriter (ms));
  313. Assert.AreEqual (
  314. @"{""Foo"":""TEST""}",
  315. Encoding.UTF8.GetString (ms.ToArray ()));
  316. }
  317. void SerializeSimpleClass1 (XmlWriter writer)
  318. {
  319. DataContractJsonSerializer ser =
  320. new DataContractJsonSerializer (typeof (DCSimple1));
  321. using (XmlWriter w = writer) {
  322. ser.WriteObject (w, new DCSimple1 ());
  323. }
  324. }
  325. // NonDC
  326. [Test]
  327. // NonDC is not a DataContract type.
  328. public void SerializeNonDCOnlyCtor ()
  329. {
  330. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (NonDC));
  331. }
  332. [Test]
  333. //[ExpectedException (typeof (InvalidDataContractException))]
  334. // NonDC is not a DataContract type.
  335. // UPDATE: non-DataContract types are became valid in RTM.
  336. public void SerializeNonDC ()
  337. {
  338. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (NonDC));
  339. using (XmlWriter w = XmlWriter.Create (TextWriter.Null, settings)) {
  340. ser.WriteObject (w, new NonDC ());
  341. }
  342. }
  343. // DCHasNonDC
  344. [Test]
  345. //[ExpectedException (typeof (InvalidDataContractException))]
  346. // DCHasNonDC itself is a DataContract type whose field is
  347. // marked as DataMember but its type is not DataContract.
  348. // UPDATE: non-DataContract types are became valid in RTM.
  349. public void SerializeDCHasNonDC ()
  350. {
  351. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCHasNonDC));
  352. using (XmlWriter w = XmlWriter.Create (TextWriter.Null, settings)) {
  353. ser.WriteObject (w, new DCHasNonDC ());
  354. }
  355. }
  356. // DCHasSerializable
  357. [Test]
  358. public void SerializeSimpleSerializable1Xml ()
  359. {
  360. StringWriter sw = new StringWriter ();
  361. SerializeSimpleSerializable1 (XmlWriter.Create (sw, settings));
  362. Assert.AreEqual (
  363. @"<root type=""object""><Ser type=""object""><Doh>doh!</Doh></Ser></root>",
  364. sw.ToString ());
  365. }
  366. [Test]
  367. public void SerializeSimpleSerializable1Json ()
  368. {
  369. MemoryStream ms = new MemoryStream ();
  370. SerializeSimpleSerializable1 (JsonReaderWriterFactory.CreateJsonWriter (ms));
  371. Assert.AreEqual (
  372. @"{""Ser"":{""Doh"":""doh!""}}",
  373. Encoding.UTF8.GetString (ms.ToArray ()));
  374. }
  375. // DCHasSerializable itself is DataContract and has a field
  376. // whose type is not contract but serializable.
  377. void SerializeSimpleSerializable1 (XmlWriter writer)
  378. {
  379. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCHasSerializable));
  380. using (XmlWriter w = writer) {
  381. ser.WriteObject (w, new DCHasSerializable ());
  382. }
  383. }
  384. [Test]
  385. public void SerializeDCWithNameXml ()
  386. {
  387. StringWriter sw = new StringWriter ();
  388. SerializeDCWithName (XmlWriter.Create (sw, settings));
  389. Assert.AreEqual (
  390. @"<root type=""object""><FooMember>value</FooMember></root>",
  391. sw.ToString ());
  392. }
  393. [Test]
  394. public void SerializeDCWithNameJson ()
  395. {
  396. MemoryStream ms = new MemoryStream ();
  397. SerializeDCWithName (JsonReaderWriterFactory.CreateJsonWriter (ms));
  398. Assert.AreEqual (
  399. @"{""FooMember"":""value""}",
  400. Encoding.UTF8.GetString (ms.ToArray ()));
  401. }
  402. void SerializeDCWithName (XmlWriter writer)
  403. {
  404. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithName));
  405. using (XmlWriter w = writer) {
  406. ser.WriteObject (w, new DCWithName ());
  407. }
  408. }
  409. [Test]
  410. public void SerializeDCWithEmptyName1 ()
  411. {
  412. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEmptyName));
  413. StringWriter sw = new StringWriter ();
  414. DCWithEmptyName dc = new DCWithEmptyName ();
  415. using (XmlWriter w = XmlWriter.Create (sw, settings)) {
  416. try {
  417. ser.WriteObject (w, dc);
  418. } catch (InvalidDataContractException) {
  419. return;
  420. }
  421. }
  422. Assert.Fail ("Expected InvalidDataContractException");
  423. }
  424. [Test]
  425. public void SerializeDCWithEmptyName2 ()
  426. {
  427. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithName));
  428. StringWriter sw = new StringWriter ();
  429. /* DataContractAttribute.Name == "", not valid */
  430. DCWithEmptyName dc = new DCWithEmptyName ();
  431. using (XmlWriter w = XmlWriter.Create (sw, settings)) {
  432. try {
  433. ser.WriteObject (w, dc);
  434. } catch (InvalidDataContractException) {
  435. return;
  436. }
  437. }
  438. Assert.Fail ("Expected InvalidDataContractException");
  439. }
  440. [Test]
  441. [Category("NotWorking")]
  442. public void SerializeDCWithNullName ()
  443. {
  444. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithNullName));
  445. StringWriter sw = new StringWriter ();
  446. using (XmlWriter w = XmlWriter.Create (sw, settings)) {
  447. try {
  448. /* DataContractAttribute.Name == "", not valid */
  449. ser.WriteObject (w, new DCWithNullName ());
  450. } catch (InvalidDataContractException) {
  451. return;
  452. }
  453. }
  454. Assert.Fail ("Expected InvalidDataContractException");
  455. }
  456. [Test]
  457. public void SerializeDCWithEmptyNamespace1 ()
  458. {
  459. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEmptyNamespace));
  460. StringWriter sw = new StringWriter ();
  461. using (XmlWriter w = XmlWriter.Create (sw, settings)) {
  462. ser.WriteObject (w, new DCWithEmptyNamespace ());
  463. }
  464. }
  465. [Test]
  466. public void SerializeWrappedClassXml ()
  467. {
  468. StringWriter sw = new StringWriter ();
  469. SerializeWrappedClass (XmlWriter.Create (sw, settings));
  470. Assert.AreEqual (
  471. @"<root type=""object"" />",
  472. sw.ToString ());
  473. }
  474. [Test]
  475. public void SerializeWrappedClassJson ()
  476. {
  477. MemoryStream ms = new MemoryStream ();
  478. SerializeWrappedClass (JsonReaderWriterFactory.CreateJsonWriter (ms));
  479. Assert.AreEqual (
  480. "{}",
  481. Encoding.UTF8.GetString (ms.ToArray ()));
  482. }
  483. void SerializeWrappedClass (XmlWriter writer)
  484. {
  485. DataContractJsonSerializer ser =
  486. new DataContractJsonSerializer (typeof (Wrapper.DCWrapped));
  487. using (XmlWriter w = writer) {
  488. ser.WriteObject (w, new Wrapper.DCWrapped ());
  489. }
  490. }
  491. // CollectionContainer : Items must have a setter. (but became valid in RTM).
  492. [Test]
  493. public void SerializeReadOnlyCollectionMember ()
  494. {
  495. DataContractJsonSerializer ser =
  496. new DataContractJsonSerializer (typeof (CollectionContainer));
  497. StringWriter sw = new StringWriter ();
  498. using (XmlWriter w = XmlWriter.Create (sw, settings)) {
  499. ser.WriteObject (w, null);
  500. }
  501. }
  502. // DataCollectionContainer : Items must have a setter. (but became valid in RTM).
  503. [Test]
  504. public void SerializeReadOnlyDataCollectionMember ()
  505. {
  506. DataContractJsonSerializer ser =
  507. new DataContractJsonSerializer (typeof (DataCollectionContainer));
  508. StringWriter sw = new StringWriter ();
  509. using (XmlWriter w = XmlWriter.Create (sw, settings)) {
  510. ser.WriteObject (w, null);
  511. }
  512. }
  513. [Test]
  514. [Ignore ("https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=409970")]
  515. [ExpectedException (typeof (SerializationException))]
  516. public void DeserializeReadOnlyDataCollection_NullCollection ()
  517. {
  518. DataContractJsonSerializer ser =
  519. new DataContractJsonSerializer (typeof (CollectionContainer));
  520. StringWriter sw = new StringWriter ();
  521. var c = new CollectionContainer ();
  522. c.Items.Add ("foo");
  523. c.Items.Add ("bar");
  524. using (XmlWriter w = XmlWriter.Create (sw, settings))
  525. ser.WriteObject (w, c);
  526. // CollectionContainer.Items is null, so it cannot deserialize non-null collection.
  527. using (XmlReader r = XmlReader.Create (new StringReader (sw.ToString ())))
  528. c = (CollectionContainer) ser.ReadObject (r);
  529. }
  530. [Test]
  531. public void SerializeGuidXml ()
  532. {
  533. StringWriter sw = new StringWriter ();
  534. SerializeGuid (XmlWriter.Create (sw, settings));
  535. Assert.AreEqual (
  536. @"<root>00000000-0000-0000-0000-000000000000</root>",
  537. sw.ToString ());
  538. }
  539. [Test]
  540. public void SerializeGuidJson ()
  541. {
  542. MemoryStream ms = new MemoryStream ();
  543. SerializeGuid (JsonReaderWriterFactory.CreateJsonWriter (ms));
  544. Assert.AreEqual (
  545. @"""00000000-0000-0000-0000-000000000000""",
  546. Encoding.UTF8.GetString (ms.ToArray ()));
  547. }
  548. void SerializeGuid (XmlWriter writer)
  549. {
  550. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Guid));
  551. using (XmlWriter w = writer) {
  552. ser.WriteObject (w, Guid.Empty);
  553. }
  554. }
  555. [Test]
  556. public void SerializeEnumXml ()
  557. {
  558. StringWriter sw = new StringWriter ();
  559. SerializeEnum (XmlWriter.Create (sw, settings));
  560. Assert.AreEqual (
  561. @"<root type=""number"">0</root>",
  562. sw.ToString ());
  563. }
  564. [Test]
  565. public void SerializeEnumJson ()
  566. {
  567. MemoryStream ms = new MemoryStream ();
  568. SerializeEnum (JsonReaderWriterFactory.CreateJsonWriter (ms));
  569. Assert.AreEqual (
  570. "0",
  571. Encoding.UTF8.GetString (ms.ToArray ()));
  572. }
  573. void SerializeEnum (XmlWriter writer)
  574. {
  575. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Colors));
  576. using (XmlWriter w = writer) {
  577. ser.WriteObject (w, new Colors ());
  578. }
  579. }
  580. [Test]
  581. public void SerializeEnum2Xml ()
  582. {
  583. StringWriter sw = new StringWriter ();
  584. SerializeEnum2 (XmlWriter.Create (sw, settings));
  585. Assert.AreEqual (
  586. @"<root type=""number"">0</root>",
  587. sw.ToString ());
  588. }
  589. [Test]
  590. public void SerializeEnum2Json ()
  591. {
  592. MemoryStream ms = new MemoryStream ();
  593. SerializeEnum2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
  594. Assert.AreEqual (
  595. "0",
  596. Encoding.UTF8.GetString (ms.ToArray ()));
  597. }
  598. void SerializeEnum2 (XmlWriter writer)
  599. {
  600. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Colors));
  601. using (XmlWriter w = writer) {
  602. ser.WriteObject (w, 0);
  603. }
  604. }
  605. [Test] // so, DataContract does not affect here.
  606. public void SerializeEnumWithDCXml ()
  607. {
  608. StringWriter sw = new StringWriter ();
  609. SerializeEnumWithDC (XmlWriter.Create (sw, settings));
  610. Assert.AreEqual (
  611. @"<root type=""number"">0</root>",
  612. sw.ToString ());
  613. }
  614. [Test]
  615. public void SerializeEnumWithDCJson ()
  616. {
  617. MemoryStream ms = new MemoryStream ();
  618. SerializeEnumWithDC (JsonReaderWriterFactory.CreateJsonWriter (ms));
  619. Assert.AreEqual (
  620. "0",
  621. Encoding.UTF8.GetString (ms.ToArray ()));
  622. }
  623. void SerializeEnumWithDC (XmlWriter writer)
  624. {
  625. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
  626. using (XmlWriter w = writer) {
  627. ser.WriteObject (w, new ColorsWithDC ());
  628. }
  629. }
  630. [Test]
  631. public void SerializeEnumWithNoDCXml ()
  632. {
  633. StringWriter sw = new StringWriter ();
  634. SerializeEnumWithNoDC (XmlWriter.Create (sw, settings));
  635. Assert.AreEqual (
  636. @"<root type=""number"">0</root>",
  637. sw.ToString ());
  638. }
  639. [Test]
  640. public void SerializeEnumWithNoDCJson ()
  641. {
  642. MemoryStream ms = new MemoryStream ();
  643. SerializeEnumWithNoDC (JsonReaderWriterFactory.CreateJsonWriter (ms));
  644. Assert.AreEqual (
  645. "0",
  646. Encoding.UTF8.GetString (ms.ToArray ()));
  647. }
  648. void SerializeEnumWithNoDC (XmlWriter writer)
  649. {
  650. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsEnumMemberNoDC));
  651. using (XmlWriter w = writer) {
  652. ser.WriteObject (w, new ColorsEnumMemberNoDC ());
  653. }
  654. }
  655. [Test]
  656. public void SerializeEnumWithDC2Xml ()
  657. {
  658. StringWriter sw = new StringWriter ();
  659. SerializeEnumWithDC2 (XmlWriter.Create (sw, settings));
  660. Assert.AreEqual (
  661. @"<root type=""number"">3</root>",
  662. sw.ToString ());
  663. }
  664. [Test]
  665. public void SerializeEnumWithDC2Json ()
  666. {
  667. MemoryStream ms = new MemoryStream ();
  668. SerializeEnumWithDC2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
  669. Assert.AreEqual (
  670. "3",
  671. Encoding.UTF8.GetString (ms.ToArray ()));
  672. }
  673. void SerializeEnumWithDC2 (XmlWriter writer)
  674. {
  675. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
  676. using (XmlWriter w = writer) {
  677. ser.WriteObject (w, 3);
  678. }
  679. }
  680. /*
  681. [Test]
  682. [ExpectedException (typeof (SerializationException))]
  683. public void SerializeEnumWithDCInvalid ()
  684. {
  685. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
  686. StringWriter sw = new StringWriter ();
  687. ColorsWithDC cdc = ColorsWithDC.Blue;
  688. using (XmlWriter w = XmlWriter.Create (sw, settings)) {
  689. ser.WriteObject (w, cdc);
  690. }
  691. }
  692. */
  693. [Test]
  694. public void SerializeDCWithEnumXml ()
  695. {
  696. StringWriter sw = new StringWriter ();
  697. SerializeDCWithEnum (XmlWriter.Create (sw, settings));
  698. Assert.AreEqual (
  699. @"<root type=""object""><_colors type=""number"">0</_colors></root>",
  700. sw.ToString ());
  701. }
  702. [Test]
  703. public void SerializeDCWithEnumJson ()
  704. {
  705. MemoryStream ms = new MemoryStream ();
  706. SerializeDCWithEnum (JsonReaderWriterFactory.CreateJsonWriter (ms));
  707. Assert.AreEqual (
  708. @"{""_colors"":0}",
  709. Encoding.UTF8.GetString (ms.ToArray ()));
  710. }
  711. void SerializeDCWithEnum (XmlWriter writer)
  712. {
  713. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEnum));
  714. using (XmlWriter w = writer) {
  715. ser.WriteObject (w, new DCWithEnum ());
  716. }
  717. }
  718. [Test]
  719. public void SerializerDCArrayXml ()
  720. {
  721. StringWriter sw = new StringWriter ();
  722. SerializerDCArray (XmlWriter.Create (sw, settings));
  723. Assert.AreEqual (
  724. @"<root type=""array""><item type=""object""><_colors type=""number"">0</_colors></item><item type=""object""><_colors type=""number"">1</_colors></item></root>",
  725. sw.ToString ());
  726. }
  727. [Test]
  728. public void SerializerDCArrayJson ()
  729. {
  730. MemoryStream ms = new MemoryStream ();
  731. SerializerDCArray (JsonReaderWriterFactory.CreateJsonWriter (ms));
  732. Assert.AreEqual (
  733. @"[{""_colors"":0},{""_colors"":1}]",
  734. Encoding.UTF8.GetString (ms.ToArray ()));
  735. }
  736. void SerializerDCArray (XmlWriter writer)
  737. {
  738. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEnum []));
  739. DCWithEnum [] arr = new DCWithEnum [2];
  740. arr [0] = new DCWithEnum (); arr [0].colors = Colors.Red;
  741. arr [1] = new DCWithEnum (); arr [1].colors = Colors.Green;
  742. using (XmlWriter w = writer) {
  743. ser.WriteObject (w, arr);
  744. }
  745. }
  746. [Test]
  747. public void SerializerDCArray2Xml ()
  748. {
  749. StringWriter sw = new StringWriter ();
  750. SerializerDCArray2 (XmlWriter.Create (sw, settings));
  751. Assert.AreEqual (
  752. @"<root type=""array""><item __type=""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"" type=""object""><_colors type=""number"">0</_colors></item><item __type=""DCSimple1:#MonoTests.System.Runtime.Serialization.Json"" type=""object""><Foo>hello</Foo></item></root>",
  753. sw.ToString ());
  754. }
  755. [Test]
  756. public void SerializerDCArray2Json ()
  757. {
  758. MemoryStream ms = new MemoryStream ();
  759. SerializerDCArray2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
  760. Assert.AreEqual (
  761. @"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0},{""__type"":""DCSimple1:#MonoTests.System.Runtime.Serialization.Json"",""Foo"":""hello""}]",
  762. Encoding.UTF8.GetString (ms.ToArray ()));
  763. }
  764. void SerializerDCArray2 (XmlWriter writer)
  765. {
  766. List<Type> known = new List<Type> ();
  767. known.Add (typeof (DCWithEnum));
  768. known.Add (typeof (DCSimple1));
  769. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (object []), known);
  770. object [] arr = new object [2];
  771. arr [0] = new DCWithEnum (); ((DCWithEnum)arr [0]).colors = Colors.Red;
  772. arr [1] = new DCSimple1 (); ((DCSimple1) arr [1]).Foo = "hello";
  773. using (XmlWriter w = writer) {
  774. ser.WriteObject (w, arr);
  775. }
  776. }
  777. [Test]
  778. public void SerializerDCArray3Xml ()
  779. {
  780. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (int []));
  781. StringWriter sw = new StringWriter ();
  782. int [] arr = new int [2];
  783. arr [0] = 1; arr [1] = 2;
  784. using (XmlWriter w = XmlWriter.Create (sw, settings)) {
  785. ser.WriteObject (w, arr);
  786. }
  787. Assert.AreEqual (
  788. @"<root type=""array""><item type=""number"">1</item><item type=""number"">2</item></root>",
  789. sw.ToString ());
  790. }
  791. [Test]
  792. public void SerializerDCArray3Json ()
  793. {
  794. MemoryStream ms = new MemoryStream ();
  795. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (int []));
  796. int [] arr = new int [2];
  797. arr [0] = 1; arr [1] = 2;
  798. using (XmlWriter w = JsonReaderWriterFactory.CreateJsonWriter (ms)) {
  799. ser.WriteObject (w, arr);
  800. }
  801. Assert.AreEqual (
  802. @"[1,2]",
  803. Encoding.UTF8.GetString (ms.ToArray ()));
  804. }
  805. [Test]
  806. // ... so, non-JSON XmlWriter is still accepted.
  807. public void SerializeNonDCArrayXml ()
  808. {
  809. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
  810. StringWriter sw = new StringWriter ();
  811. using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
  812. ser.WriteObject (xw, new SerializeNonDCArrayType ());
  813. }
  814. Assert.AreEqual (@"<root type=""object""><IPAddresses type=""array"" /></root>",
  815. sw.ToString ());
  816. }
  817. [Test]
  818. public void SerializeNonDCArrayJson ()
  819. {
  820. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
  821. MemoryStream ms = new MemoryStream ();
  822. using (XmlWriter xw = JsonReaderWriterFactory.CreateJsonWriter (ms)) {
  823. ser.WriteObject (xw, new SerializeNonDCArrayType ());
  824. }
  825. Assert.AreEqual (@"{""IPAddresses"":[]}",
  826. Encoding.UTF8.GetString (ms.ToArray ()));
  827. }
  828. [Test]
  829. public void SerializeNonDCArrayItems ()
  830. {
  831. DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
  832. StringWriter sw = new StringWriter ();
  833. using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
  834. SerializeNonDCArrayType obj = new SerializeNonDCArrayType ();
  835. obj.IPAddresses = new NonDCItem [] {new NonDCItem () { Data = new byte [] {1, 2, 3, 4} } };
  836. ser.WriteObject (xw, obj);
  837. }
  838. XmlDocument doc = new XmlDocument ();
  839. doc.LoadXml (sw.ToString ());
  840. XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
  841. nsmgr.AddNamespace ("s", "http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization");
  842. nsmgr.AddNamespace ("n", "http://schemas.datacontract.org/2004/07/System.Net");
  843. nsmgr.AddNamespace ("a", "http://schemas.microsoft.com/2003/10/Serialization/Arrays");
  844. Assert.AreEqual (1, doc.SelectNodes ("/root/IPAddresses/item", nsmgr).Count, "#1");
  845. XmlElement el = doc.SelectSingleNode ("/root/IPAddresses/item/Data", nsmgr) as XmlElement;
  846. Assert.IsNotNull (el, "#3");
  847. Assert.AreEqual (4, el.SelectNodes ("item", nsmgr).Count, "#4");
  848. }
  849. [Test]
  850. public void MaxItemsInObjectGraph1 ()
  851. {
  852. // object count == maximum
  853. DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCEmpty), null, 1, false, null, false);
  854. s.WriteObject (XmlWriter.Create (TextWriter.Null), new DCEmpty ());
  855. }
  856. [Test]
  857. [ExpectedException (typeof (SerializationException))]
  858. public void MaxItemsInObjectGraph2 ()
  859. {
  860. // object count > maximum
  861. DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCSimple1), null, 1, false, null, false);
  862. s.WriteObject (XmlWriter.Create (TextWriter.Null), new DCSimple1 ());
  863. }
  864. [Test]
  865. public void DeserializeString ()
  866. {
  867. Assert.AreEqual ("ABC", Deserialize ("\"ABC\"", typeof (string)));
  868. }
  869. [Test]
  870. public void DeserializeInt ()
  871. {
  872. Assert.AreEqual (5, Deserialize ("5", typeof (int)));
  873. }
  874. [Test]
  875. public void DeserializeArray ()
  876. {
  877. int [] ret = (int []) Deserialize ("[5,6,7]", typeof (int []));
  878. Assert.AreEqual (5, ret [0], "#1");
  879. Assert.AreEqual (6, ret [1], "#2");
  880. Assert.AreEqual (7, ret [2], "#3");
  881. }
  882. [Test]
  883. public void DeserializeArrayUntyped ()
  884. {
  885. object [] ret = (object []) Deserialize ("[5,6,7]", typeof (object []));
  886. Assert.AreEqual (5, ret [0], "#1");
  887. Assert.AreEqual (6, ret [1], "#2");
  888. Assert.AreEqual (7, ret [2], "#3");
  889. }
  890. [Test]
  891. public void DeserializeMixedArray ()
  892. {
  893. object [] ret = (object []) Deserialize ("[5,\"6\",false]", typeof (object []));
  894. Assert.AreEqual (5, ret [0], "#1");
  895. Assert.AreEqual ("6", ret [1], "#2");
  896. Assert.AreEqual (false, ret [2], "#3");
  897. }
  898. [Test]
  899. [ExpectedException (typeof (SerializationException))]
  900. public void DeserializeEmptyAsString ()
  901. {
  902. // it somehow expects "root" which should have been already consumed.
  903. Deserialize ("", typeof (string));
  904. }
  905. [Test]
  906. [ExpectedException (typeof (SerializationException))]
  907. public void DeserializeEmptyAsInt ()
  908. {
  909. // it somehow expects "root" which should have been already consumed.
  910. Deserialize ("", typeof (int));
  911. }
  912. [Test]
  913. [ExpectedException (typeof (SerializationException))]
  914. public void DeserializeEmptyAsDBNull ()
  915. {
  916. // it somehow expects "root" which should have been already consumed.
  917. Deserialize ("", typeof (DBNull));
  918. }
  919. [Test]
  920. public void DeserializeEmptyObjectAsString ()
  921. {
  922. // looks like it is converted to ""
  923. Assert.AreEqual (String.Empty, Deserialize ("{}", typeof (string)));
  924. }
  925. [Test]
  926. [ExpectedException (typeof (SerializationException))]
  927. public void DeserializeEmptyObjectAsInt ()
  928. {
  929. Deserialize ("{}", typeof (int));
  930. }
  931. [Test]
  932. public void DeserializeEmptyObjectAsDBNull ()
  933. {
  934. Assert.AreEqual (DBNull.Value, Deserialize ("{}", typeof (DBNull)));
  935. }
  936. [Test]
  937. [ExpectedException (typeof (SerializationException))]
  938. public void DeserializeEnumByName ()
  939. {
  940. // enum is parsed into long
  941. Deserialize (@"""Red""", typeof (Colors));
  942. }
  943. [Test]
  944. public void DeserializeEnum2 ()
  945. {
  946. object o = Deserialize ("0", typeof (Colors));
  947. Assert.AreEqual (typeof (Colors), o.GetType (), "#de3");
  948. Colors c = (Colors) o;
  949. Assert.AreEqual (Colors.Red, c, "#de4");
  950. }
  951. [Test]
  952. [ExpectedException (typeof (SerializationException))]
  953. public void DeserializeEnumInvalid ()
  954. {
  955. Deserialize ("", typeof (Colors));
  956. }
  957. [Test]
  958. [ExpectedException (typeof (SerializationException))]
  959. [Category ("NotDotNet")] // 0.0 is an invalid Colors value.
  960. public void DeserializeEnumInvalid3 ()
  961. {
  962. //"0.0" instead of "0"
  963. Deserialize (
  964. "0.0",
  965. typeof (Colors));
  966. }
  967. [Test]
  968. public void DeserializeEnumWithDC ()
  969. {
  970. object o = Deserialize ("0", typeof (ColorsWithDC));
  971. Assert.AreEqual (typeof (ColorsWithDC), o.GetType (), "#de5");
  972. ColorsWithDC cdc = (ColorsWithDC) o;
  973. Assert.AreEqual (ColorsWithDC.Red, o, "#de6");
  974. }
  975. [Test]
  976. [ExpectedException (typeof (SerializationException))]
  977. [Category ("NotDotNet")] // 4 is an invalid Colors value.
  978. [Category ("NotWorking")]
  979. public void DeserializeEnumWithDCInvalid ()
  980. {
  981. Deserialize (
  982. "4",
  983. typeof (ColorsWithDC));
  984. }
  985. [Test]
  986. public void DeserializeDCWithEnum ()
  987. {
  988. object o = Deserialize (
  989. "{\"_colors\":0}",
  990. typeof (DCWithEnum));
  991. Assert.AreEqual (typeof (DCWithEnum), o.GetType (), "#de7");
  992. DCWithEnum dc = (DCWithEnum) o;
  993. Assert.AreEqual (Colors.Red, dc.colors, "#de8");
  994. }
  995. [Test]
  996. public void ReadObjectVerifyObjectNameFalse ()
  997. {
  998. string xml = @"<any><Member1>bar</Member1></any>";
  999. object o = new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
  1000. .ReadObject (XmlReader.Create (new StringReader (xml)), false);
  1001. Assert.IsTrue (o is VerifyObjectNameTestData, "#1");
  1002. string xml2 = @"<any><x:Member1 xmlns:x=""http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"">bar</x:Member1></any>";
  1003. o = new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
  1004. .ReadObject (XmlReader.Create (new StringReader (xml2)), false);
  1005. Assert.IsTrue (o is VerifyObjectNameTestData, "#2");
  1006. }
  1007. [Test]
  1008. [ExpectedException (typeof (SerializationException))]
  1009. public void ReadObjectVerifyObjectNameTrue ()
  1010. {
  1011. string xml = @"<any><Member1>bar</Member1></any>";
  1012. new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
  1013. .ReadObject (XmlReader.Create (new StringReader (xml)), true);
  1014. }
  1015. [Test] // member name is out of scope
  1016. public void ReadObjectVerifyObjectNameTrue2 ()
  1017. {
  1018. string xml = @"<root><Member2>bar</Member2></root>";
  1019. new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
  1020. .ReadObject (XmlReader.Create (new StringReader (xml)), true);
  1021. }
  1022. [Test]
  1023. public void ReadTypedObjectJson ()
  1024. {
  1025. object o = Deserialize (@"{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0}", typeof (DCWithEnum));
  1026. Assert.AreEqual (typeof (DCWithEnum), o.GetType ());
  1027. }
  1028. [Test]
  1029. public void ReadObjectDCArrayJson ()
  1030. {
  1031. object o = Deserialize (@"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0}]",
  1032. typeof (object []), typeof (DCWithEnum));
  1033. Assert.AreEqual (typeof (object []), o.GetType (), "#1");
  1034. object [] arr = (object []) o;
  1035. Assert.AreEqual (typeof (DCWithEnum), arr [0].GetType (), "#2");
  1036. }
  1037. [Test]
  1038. public void ReadObjectDCArray2Json ()
  1039. {
  1040. object o = Deserialize (@"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0},{""__type"":""DCSimple1:#MonoTests.System.Runtime.Serialization.Json"",""Foo"":""hello""}]",
  1041. typeof (object []), typeof (DCWithEnum), typeof (DCSimple1));
  1042. Assert.AreEqual (typeof (object []), o.GetType (), "#1");
  1043. object [] arr = (object []) o;
  1044. Assert.AreEqual (typeof (DCWithEnum), arr [0].GetType (), "#2");
  1045. Assert.AreEqual (typeof (DCSimple1), arr [1].GetType (), "#3");
  1046. }
  1047. private object Deserialize (string xml, Type type, params Type [] knownTypes)
  1048. {
  1049. DataContractJsonSerializer ser = new DataContractJsonSerializer (type, knownTypes);
  1050. XmlReader xr = JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (xml), new XmlDictionaryReaderQuotas ());
  1051. return ser.ReadObject (xr);
  1052. }
  1053. [Test]
  1054. public void IsStartObject ()
  1055. {
  1056. DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCSimple1));
  1057. Assert.IsTrue (s.IsStartObject (XmlReader.Create (new StringReader ("<root></root>"))), "#1");
  1058. Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<dummy></dummy>"))), "#2");
  1059. Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<Foo></Foo>"))), "#3");
  1060. Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<root xmlns='urn:foo'></root>"))), "#4");
  1061. }
  1062. [Test]
  1063. public void SerializeNonDC2 ()
  1064. {
  1065. var ser = new DataContractJsonSerializer (typeof (TestData));
  1066. StringWriter sw = new StringWriter ();
  1067. var obj = new TestData () { Foo = "foo", Bar = "bar", Baz = "baz" };
  1068. // XML
  1069. using (var xw = XmlWriter.Create (sw))
  1070. ser.WriteObject (xw, obj);
  1071. var s = sw.ToString ();
  1072. // since the order is not preserved, we compare only contents.
  1073. Assert.IsTrue (s.IndexOf ("<Foo>foo</Foo>") > 0, "#1-1");
  1074. Assert.IsTrue (s.IndexOf ("<Bar>bar</Bar>") > 0, "#1-2");
  1075. Assert.IsFalse (s.IndexOf ("<Baz>baz</Baz>") > 0, "#1-3");
  1076. // JSON
  1077. MemoryStream ms = new MemoryStream ();
  1078. using (var xw = JsonReaderWriterFactory.CreateJsonWriter (ms))
  1079. ser.WriteObject (ms, obj);
  1080. s = new StreamReader (new MemoryStream (ms.ToArray ())).ReadToEnd ().Replace ('"', '/');
  1081. // since the order is not preserved, we compare only contents.
  1082. Assert.IsTrue (s.IndexOf ("/Foo/:/foo/") > 0, "#2-1");
  1083. Assert.IsTrue (s.IndexOf ("/Bar/:/bar/") > 0, "#2-2");
  1084. Assert.IsFalse (s.IndexOf ("/Baz/:/baz/") > 0, "#2-3");
  1085. }
  1086. [Test]
  1087. public void AlwaysEmitTypeInformation ()
  1088. {
  1089. var ms = new MemoryStream ();
  1090. var ds = new DataContractJsonSerializer (typeof (string), "root", null, 10, false, null, true);
  1091. ds.WriteObject (ms, "foobar");
  1092. var s = Encoding.UTF8.GetString (ms.ToArray ());
  1093. Assert.AreEqual ("\"foobar\"", s, "#1");
  1094. }
  1095. [Test]
  1096. public void AlwaysEmitTypeInformation2 ()
  1097. {
  1098. var ms = new MemoryStream ();
  1099. var ds = new DataContractJsonSerializer (typeof (TestData), "root", null, 10, false, null, true);
  1100. ds.WriteObject (ms, new TestData () { Foo = "foo"});
  1101. var s = Encoding.UTF8.GetString (ms.ToArray ());
  1102. Assert.AreEqual (@"{""__type"":""TestData:#MonoTests.System.Runtime.Serialization.Json"",""Bar"":null,""Foo"":""foo""}", s, "#1");
  1103. }
  1104. [Test]
  1105. public void AlwaysEmitTypeInformation3 ()
  1106. {
  1107. var ms = new MemoryStream ();
  1108. var ds = new DataContractJsonSerializer (typeof (TestData), "root", null, 10, false, null, false);
  1109. ds.WriteObject (ms, new TestData () { Foo = "foo"});
  1110. var s = Encoding.UTF8.GetString (ms.ToArray ());
  1111. Assert.AreEqual (@"{""Bar"":null,""Foo"":""foo""}", s, "#1");
  1112. }
  1113. [Test]
  1114. public void TestNonpublicDeserialization ()
  1115. {
  1116. string s1= @"{""Bar"":""bar"", ""Foo"":""foo"", ""Baz"":""baz""}";
  1117. TestData o1 = ((TestData)(new DataContractJsonSerializer (typeof (TestData)).ReadObject (JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (s1), new XmlDictionaryReaderQuotas ()))));
  1118. Assert.AreEqual (null, o1.Baz, "#1");
  1119. string s2 = @"{""TestData"":[{""key"":""key1"",""value"":""value1""}]}";
  1120. KeyValueTestData o2 = ((KeyValueTestData)(new DataContractJsonSerializer (typeof (KeyValueTestData)).ReadObject (JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (s2), new XmlDictionaryReaderQuotas ()))));
  1121. Assert.AreEqual (1, o2.TestData.Count, "#2");
  1122. Assert.AreEqual ("key1", o2.TestData[0].Key, "#3");
  1123. Assert.AreEqual ("value1", o2.TestData[0].Value, "#4");
  1124. }
  1125. // [Test] use this case if you want to check lame silverlight parser behavior. Seealso #549756
  1126. public void QuotelessDeserialization ()
  1127. {
  1128. string s1 = @"{FooMember:""value""}";
  1129. var ds = new DataContractJsonSerializer (typeof (DCWithName));
  1130. ds.ReadObject (new MemoryStream (Encoding.UTF8.GetBytes (s1)));
  1131. string s2 = @"{FooMember:"" \""{dummy:string}\""""}";
  1132. ds.ReadObject (new MemoryStream (Encoding.UTF8.GetBytes (s2)));
  1133. }
  1134. [Test]
  1135. [Category ("NotWorking")]
  1136. public void TypeIsNotPartsOfKnownTypes ()
  1137. {
  1138. var dcs = new DataContractSerializer (typeof (string));
  1139. Assert.AreEqual (0, dcs.KnownTypes.Count, "KnownTypes #1");
  1140. var dcjs = new DataContractJsonSerializer (typeof (string));
  1141. Assert.AreEqual (0, dcjs.KnownTypes.Count, "KnownTypes #2");
  1142. }
  1143. [Test]
  1144. public void ReadWriteNullObject ()
  1145. {
  1146. DataContractJsonSerializer dcjs = new DataContractJsonSerializer (typeof (string));
  1147. using (MemoryStream ms = new MemoryStream ()) {
  1148. dcjs.WriteObject (ms, null);
  1149. ms.Position = 0;
  1150. using (StreamReader sr = new StreamReader (ms)) {
  1151. string data = sr.ReadToEnd ();
  1152. Assert.AreEqual ("null", data, "WriteObject(stream,null)");
  1153. ms.Position = 0;
  1154. Assert.IsNull (dcjs.ReadObject (ms), "ReadObject(stream)");
  1155. }
  1156. };
  1157. }
  1158. object ReadWriteObject (Type type, object obj, string expected)
  1159. {
  1160. using (MemoryStream ms = new MemoryStream ()) {
  1161. DataContractJsonSerializer dcjs = new DataContractJsonSerializer (type);
  1162. dcjs.WriteObject (ms, obj);
  1163. ms.Position = 0;
  1164. using (StreamReader sr = new StreamReader (ms)) {
  1165. Assert.AreEqual (expected, sr.ReadToEnd (), "WriteObject");
  1166. ms.Position = 0;
  1167. return dcjs.ReadObject (ms);
  1168. }
  1169. }
  1170. }
  1171. [Test]
  1172. [Ignore ("Wrong test case. See bug #573691")]
  1173. public void ReadWriteObject_Single_SpecialCases ()
  1174. {
  1175. Assert.IsTrue (Single.IsNaN ((float) ReadWriteObject (typeof (float), Single.NaN, "NaN")));
  1176. Assert.IsTrue (Single.IsNegativeInfinity ((float) ReadWriteObject (typeof (float), Single.NegativeInfinity, "-INF")));
  1177. Assert.IsTrue (Single.IsPositiveInfinity ((float) ReadWriteObject (typeof (float), Single.PositiveInfinity, "INF")));
  1178. }
  1179. [Test]
  1180. [Ignore ("Wrong test case. See bug #573691")]
  1181. public void ReadWriteObject_Double_SpecialCases ()
  1182. {
  1183. Assert.IsTrue (Double.IsNaN ((double) ReadWriteObject (typeof (double), Double.NaN, "NaN")));
  1184. Assert.IsTrue (Double.IsNegativeInfinity ((double) ReadWriteObject (typeof (double), Double.NegativeInfinity, "-INF")));
  1185. Assert.IsTrue (Double.IsPositiveInfinity ((double) ReadWriteObject (typeof (double), Double.PositiveInfinity, "INF")));
  1186. }
  1187. [Test]
  1188. public void ReadWriteDateTime ()
  1189. {
  1190. var ms = new MemoryStream ();
  1191. DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (Query));
  1192. Query query = new Query () {
  1193. StartDate = new DateTime (2010, 3, 4, 5, 6, 7),
  1194. EndDate = new DateTime (2010, 4, 5, 6, 7, 8)
  1195. };
  1196. serializer.WriteObject (ms, query);
  1197. Assert.AreEqual ("{\"StartDate\":\"\\/Date(1267679167000)\\/\",\"EndDate\":\"\\/Date(1270447628000)\\/\"}", Encoding.UTF8.GetString (ms.ToArray ()), "#1");
  1198. ms.Position = 0;
  1199. Console.WriteLine (new StreamReader (ms).ReadToEnd ());
  1200. ms.Position = 0;
  1201. var q = (Query) serializer.ReadObject(ms);
  1202. Assert.AreEqual (query.StartDate, q.StartDate, "#2");
  1203. Assert.AreEqual (query.EndDate, q.EndDate, "#3");
  1204. }
  1205. }
  1206. public class TestData
  1207. {
  1208. public string Foo { get; set; }
  1209. public string Bar { get; set; }
  1210. internal string Baz { get; set; }
  1211. }
  1212. public enum Colors {
  1213. Red, Green, Blue
  1214. }
  1215. [DataContract (Name = "_ColorsWithDC")]
  1216. public enum ColorsWithDC {
  1217. [EnumMember (Value = "_Red")]
  1218. Red,
  1219. [EnumMember]
  1220. Green,
  1221. Blue
  1222. }
  1223. public enum ColorsEnumMemberNoDC {
  1224. [EnumMember (Value = "_Red")]
  1225. Red,
  1226. [EnumMember]
  1227. Green,
  1228. Blue
  1229. }
  1230. [DataContract]
  1231. public class DCWithEnum {
  1232. [DataMember (Name = "_colors")]
  1233. public Colors colors;
  1234. }
  1235. [DataContract]
  1236. public class DCEmpty
  1237. {
  1238. // serializer doesn't touch it.
  1239. public string Foo = "TEST";
  1240. }
  1241. [DataContract]
  1242. public class DCSimple1
  1243. {
  1244. [DataMember]
  1245. public string Foo = "TEST";
  1246. }
  1247. [DataContract]
  1248. public class DCHasNonDC
  1249. {
  1250. [DataMember]
  1251. public NonDC Hoge= new NonDC ();
  1252. }
  1253. public class NonDC
  1254. {
  1255. public string Whee = "whee!";
  1256. }
  1257. [DataContract]
  1258. public class DCHasSerializable
  1259. {
  1260. [DataMember]
  1261. public SimpleSer1 Ser = new SimpleSer1 ();
  1262. }
  1263. [DataContract (Name = "Foo")]
  1264. public class DCWithName
  1265. {
  1266. [DataMember (Name = "FooMember")]
  1267. public string DMWithName = "value";
  1268. }
  1269. [DataContract (Name = "")]
  1270. public class DCWithEmptyName
  1271. {
  1272. [DataMember]
  1273. public string Foo;
  1274. }
  1275. [DataContract (Name = null)]
  1276. public class DCWithNullName
  1277. {
  1278. [DataMember]
  1279. public string Foo;
  1280. }
  1281. [DataContract (Namespace = "")]
  1282. public class DCWithEmptyNamespace
  1283. {
  1284. [DataMember]
  1285. public string Foo;
  1286. }
  1287. [Serializable]
  1288. public class SimpleSer1
  1289. {
  1290. public string Doh = "doh!";
  1291. }
  1292. public class Wrapper
  1293. {
  1294. [DataContract]
  1295. public class DCWrapped
  1296. {
  1297. }
  1298. }
  1299. [DataContract]
  1300. public class CollectionContainer
  1301. {
  1302. Collection<string> items = new Collection<string> ();
  1303. [DataMember]
  1304. public Collection<string> Items {
  1305. get { return items; }
  1306. }
  1307. }
  1308. [CollectionDataContract]
  1309. public class DataCollection<T> : Collection<T>
  1310. {
  1311. }
  1312. [DataContract]
  1313. public class DataCollectionContainer
  1314. {
  1315. DataCollection<string> items = new DataCollection<string> ();
  1316. [DataMember]
  1317. public DataCollection<string> Items {
  1318. get { return items; }
  1319. }
  1320. }
  1321. [DataContract]
  1322. class SerializeNonDCArrayType
  1323. {
  1324. [DataMember]
  1325. public NonDCItem [] IPAddresses = new NonDCItem [0];
  1326. }
  1327. public class NonDCItem
  1328. {
  1329. public byte [] Data { get; set; }
  1330. }
  1331. [DataContract]
  1332. public class VerifyObjectNameTestData
  1333. {
  1334. [DataMember]
  1335. string Member1 = "foo";
  1336. }
  1337. [Serializable]
  1338. public class KeyValueTestData {
  1339. public List<KeyValuePair<string,string>> TestData = new List<KeyValuePair<string,string>>();
  1340. }
  1341. [DataContract] // bug #586169
  1342. public class Query
  1343. {
  1344. [DataMember (Order=1)]
  1345. public DateTime StartDate { get; set; }
  1346. [DataMember (Order=2)]
  1347. public DateTime EndDate { get; set; }
  1348. }
  1349. }
  1350. [DataContract]
  1351. class GlobalSample1
  1352. {
  1353. }