DataContractJsonSerializerTest.cs 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764
  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. [DataContract(Name = "DateTest")]
  1207. public class DateTest
  1208. {
  1209. [DataMember(Name = "should_have_value")]
  1210. public DateTime? ShouldHaveValue { get; set; }
  1211. }
  1212. //
  1213. // This tests both the extended format "number-0500" as well
  1214. // as the nullable field in the structure
  1215. [Test]
  1216. public void BugXamarin163 ()
  1217. {
  1218. string json = @"{""should_have_value"":""\/Date(1277355600000-0500)\/""}";
  1219. byte[] bytes = global::System.Text.Encoding.UTF8.GetBytes(json);
  1220. Stream inputStream = new MemoryStream(bytes);
  1221. DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DateTest));
  1222. DateTest t = serializer.ReadObject(inputStream) as DateTest;
  1223. Assert.AreEqual (634129344000000000, t.ShouldHaveValue.Value.Ticks, "#1");
  1224. }
  1225. [Test]
  1226. public void NullableFieldsShouldSupportNullValue ()
  1227. {
  1228. string json = @"{""should_have_value"":null}";
  1229. var inputStream = new MemoryStream (Encoding.UTF8.GetBytes (json));
  1230. DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DateTest));
  1231. Console.WriteLine ("# serializer assembly: {0}", serializer.GetType ().Assembly.Location);
  1232. DateTest t = serializer.ReadObject (inputStream) as DateTest;
  1233. Assert.AreEqual (false, t.ShouldHaveValue.HasValue, "#2");
  1234. }
  1235. [Test]
  1236. public void DeserializeNullMember ()
  1237. {
  1238. var ds = new DataContractJsonSerializer (typeof (ClassA));
  1239. var stream = new MemoryStream ();
  1240. var a = new ClassA ();
  1241. ds.WriteObject (stream, a);
  1242. stream.Position = 0;
  1243. a = (ClassA) ds.ReadObject (stream);
  1244. Assert.IsNull (a.B, "#1");
  1245. }
  1246. [Test]
  1247. public void OnDeserializationMethods ()
  1248. {
  1249. var ds = new DataContractJsonSerializer (typeof (GSPlayerListErg));
  1250. var obj = new GSPlayerListErg ();
  1251. var ms = new MemoryStream ();
  1252. ds.WriteObject (ms, obj);
  1253. ms.Position = 0;
  1254. ds.ReadObject (ms);
  1255. Assert.IsTrue (GSPlayerListErg.A, "A");
  1256. Assert.IsTrue (GSPlayerListErg.B, "B");
  1257. Assert.IsTrue (GSPlayerListErg.C, "C");
  1258. }
  1259. [Test]
  1260. public void WriteChar ()
  1261. {
  1262. DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof (CharTest));
  1263. using (MemoryStream ms = new MemoryStream()) {
  1264. serializer.WriteObject(ms, new CharTest ());
  1265. ms.Position = 0L;
  1266. using (StreamReader reader = new StreamReader(ms)) {
  1267. reader.ReadToEnd();
  1268. }
  1269. }
  1270. }
  1271. [Test]
  1272. public void DictionarySerialization ()
  1273. {
  1274. var dict = new MyDictionary<string,string> ();
  1275. dict.Add ("key", "value");
  1276. var serializer = new DataContractJsonSerializer (dict.GetType ());
  1277. var stream = new MemoryStream ();
  1278. serializer.WriteObject (stream, dict);
  1279. stream.Position = 0;
  1280. Assert.AreEqual ("[{\"Key\":\"key\",\"Value\":\"value\"}]", new StreamReader (stream).ReadToEnd (), "#1");
  1281. stream.Position = 0;
  1282. dict = (MyDictionary<string,string>) serializer.ReadObject (stream);
  1283. Assert.AreEqual (1, dict.Count, "#2");
  1284. Assert.AreEqual ("value", dict ["key"], "#3");
  1285. }
  1286. }
  1287. public class CharTest
  1288. {
  1289. public char Foo;
  1290. }
  1291. public class TestData
  1292. {
  1293. public string Foo { get; set; }
  1294. public string Bar { get; set; }
  1295. internal string Baz { get; set; }
  1296. }
  1297. public enum Colors {
  1298. Red, Green, Blue
  1299. }
  1300. [DataContract (Name = "_ColorsWithDC")]
  1301. public enum ColorsWithDC {
  1302. [EnumMember (Value = "_Red")]
  1303. Red,
  1304. [EnumMember]
  1305. Green,
  1306. Blue
  1307. }
  1308. public enum ColorsEnumMemberNoDC {
  1309. [EnumMember (Value = "_Red")]
  1310. Red,
  1311. [EnumMember]
  1312. Green,
  1313. Blue
  1314. }
  1315. [DataContract]
  1316. public class DCWithEnum {
  1317. [DataMember (Name = "_colors")]
  1318. public Colors colors;
  1319. }
  1320. [DataContract]
  1321. public class DCEmpty
  1322. {
  1323. // serializer doesn't touch it.
  1324. public string Foo = "TEST";
  1325. }
  1326. [DataContract]
  1327. public class DCSimple1
  1328. {
  1329. [DataMember]
  1330. public string Foo = "TEST";
  1331. }
  1332. [DataContract]
  1333. public class DCHasNonDC
  1334. {
  1335. [DataMember]
  1336. public NonDC Hoge= new NonDC ();
  1337. }
  1338. public class NonDC
  1339. {
  1340. public string Whee = "whee!";
  1341. }
  1342. [DataContract]
  1343. public class DCHasSerializable
  1344. {
  1345. [DataMember]
  1346. public SimpleSer1 Ser = new SimpleSer1 ();
  1347. }
  1348. [DataContract (Name = "Foo")]
  1349. public class DCWithName
  1350. {
  1351. [DataMember (Name = "FooMember")]
  1352. public string DMWithName = "value";
  1353. }
  1354. [DataContract (Name = "")]
  1355. public class DCWithEmptyName
  1356. {
  1357. [DataMember]
  1358. public string Foo;
  1359. }
  1360. [DataContract (Name = null)]
  1361. public class DCWithNullName
  1362. {
  1363. [DataMember]
  1364. public string Foo;
  1365. }
  1366. [DataContract (Namespace = "")]
  1367. public class DCWithEmptyNamespace
  1368. {
  1369. [DataMember]
  1370. public string Foo;
  1371. }
  1372. [Serializable]
  1373. public class SimpleSer1
  1374. {
  1375. public string Doh = "doh!";
  1376. }
  1377. public class Wrapper
  1378. {
  1379. [DataContract]
  1380. public class DCWrapped
  1381. {
  1382. }
  1383. }
  1384. [DataContract]
  1385. public class CollectionContainer
  1386. {
  1387. Collection<string> items = new Collection<string> ();
  1388. [DataMember]
  1389. public Collection<string> Items {
  1390. get { return items; }
  1391. }
  1392. }
  1393. [CollectionDataContract]
  1394. public class DataCollection<T> : Collection<T>
  1395. {
  1396. }
  1397. [DataContract]
  1398. public class DataCollectionContainer
  1399. {
  1400. DataCollection<string> items = new DataCollection<string> ();
  1401. [DataMember]
  1402. public DataCollection<string> Items {
  1403. get { return items; }
  1404. }
  1405. }
  1406. [DataContract]
  1407. class SerializeNonDCArrayType
  1408. {
  1409. [DataMember]
  1410. public NonDCItem [] IPAddresses = new NonDCItem [0];
  1411. }
  1412. public class NonDCItem
  1413. {
  1414. public byte [] Data { get; set; }
  1415. }
  1416. [DataContract]
  1417. public class VerifyObjectNameTestData
  1418. {
  1419. [DataMember]
  1420. string Member1 = "foo";
  1421. }
  1422. [Serializable]
  1423. public class KeyValueTestData {
  1424. public List<KeyValuePair<string,string>> TestData = new List<KeyValuePair<string,string>>();
  1425. }
  1426. [DataContract] // bug #586169
  1427. public class Query
  1428. {
  1429. [DataMember (Order=1)]
  1430. public DateTime StartDate { get; set; }
  1431. [DataMember (Order=2)]
  1432. public DateTime EndDate { get; set; }
  1433. }
  1434. public class ClassA {
  1435. public ClassB B { get; set; }
  1436. }
  1437. public class ClassB
  1438. {
  1439. }
  1440. public class GSPlayerListErg
  1441. {
  1442. public GSPlayerListErg ()
  1443. {
  1444. Init ();
  1445. }
  1446. void Init ()
  1447. {
  1448. C = true;
  1449. }
  1450. [OnDeserializing]
  1451. public void OnDeserializing (StreamingContext c)
  1452. {
  1453. A = true;
  1454. Init ();
  1455. }
  1456. [OnDeserialized]
  1457. void OnDeserialized (StreamingContext c)
  1458. {
  1459. B = true;
  1460. }
  1461. public static bool A, B, C;
  1462. [DataMember (Name = "T")]
  1463. public long CodedServerTimeUTC { get; set; }
  1464. public DateTime ServerTimeUTC { get; set; }
  1465. }
  1466. }
  1467. [DataContract]
  1468. class GlobalSample1
  1469. {
  1470. }
  1471. public class MyDictionary<K, V> : System.Collections.Generic.IDictionary<K, V>
  1472. {
  1473. Dictionary<K,V> dic = new Dictionary<K,V> ();
  1474. public void Add (K key, V value)
  1475. {
  1476. dic.Add (key, value);
  1477. }
  1478. public bool ContainsKey (K key)
  1479. {
  1480. return dic.ContainsKey (key);
  1481. }
  1482. public ICollection<K> Keys {
  1483. get { return dic.Keys; }
  1484. }
  1485. public bool Remove (K key)
  1486. {
  1487. return dic.Remove (key);
  1488. }
  1489. public bool TryGetValue (K key, out V value)
  1490. {
  1491. return dic.TryGetValue (key, out value);
  1492. }
  1493. public ICollection<V> Values {
  1494. get { return dic.Values; }
  1495. }
  1496. public V this [K key] {
  1497. get { return dic [key]; }
  1498. set { dic [key] = value; }
  1499. }
  1500. IEnumerator IEnumerable.GetEnumerator ()
  1501. {
  1502. return dic.GetEnumerator ();
  1503. }
  1504. ICollection<KeyValuePair<K,V>> Coll {
  1505. get { return (ICollection<KeyValuePair<K,V>>) dic; }
  1506. }
  1507. public void Add (KeyValuePair<K, V> item)
  1508. {
  1509. Coll.Add (item);
  1510. }
  1511. public void Clear ()
  1512. {
  1513. dic.Clear ();
  1514. }
  1515. public bool Contains (KeyValuePair<K, V> item)
  1516. {
  1517. return Coll.Contains (item);
  1518. }
  1519. public void CopyTo (KeyValuePair<K, V> [] array, int arrayIndex)
  1520. {
  1521. Coll.CopyTo (array, arrayIndex);
  1522. }
  1523. public int Count {
  1524. get { return dic.Count; }
  1525. }
  1526. public bool IsReadOnly {
  1527. get { return Coll.IsReadOnly; }
  1528. }
  1529. public bool Remove (KeyValuePair<K, V> item)
  1530. {
  1531. return Coll.Remove (item);
  1532. }
  1533. public IEnumerator<KeyValuePair<K, V>> GetEnumerator ()
  1534. {
  1535. return Coll.GetEnumerator ();
  1536. }
  1537. }