DataContractJsonSerializerTest.cs 47 KB

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