[S.R.Serialization] fix default value comparison.
[mono-project.git] / mcs / class / System.ServiceModel.Web / Test / System.Runtime.Serialization.Json / DataContractJsonSerializerTest.cs
blobbede256b8c947ef6598f1906468e823fff50d072
1 //
2 // DataContractJsonSerializerTest.cs
3 //
4 // Author:
5 // Atsushi Enomoto <atsushi@ximian.com>
6 // Ankit Jain <JAnkit@novell.com>
7 // Antoine Cailliau <antoinecailliau@gmail.com>
8 //
9 // Copyright (C) 2005-2007 Novell, Inc. http://www.novell.com
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 //
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 //
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 // This test code contains tests for DataContractJsonSerializer, which is
34 // imported from DataContractSerializerTest.cs.
37 using System;
38 using System.Collections;
39 using System.Collections.Generic;
40 using System.Collections.ObjectModel;
41 using System.IO;
42 using System.Net;
43 using System.Runtime.Serialization;
44 using System.Runtime.Serialization.Json;
45 using System.Text;
46 using System.Xml;
47 using NUnit.Framework;
49 namespace MonoTests.System.Runtime.Serialization.Json
51 [TestFixture]
52 public class DataContractJsonSerializerTest
54 static readonly XmlWriterSettings settings;
56 static DataContractJsonSerializerTest ()
58 settings = new XmlWriterSettings ();
59 settings.OmitXmlDeclaration = true;
62 [DataContract]
63 class Sample1
65 [DataMember]
66 public string Member1;
69 [Test]
70 [ExpectedException (typeof (ArgumentNullException))]
71 public void ConstructorTypeNull ()
73 new DataContractJsonSerializer (null);
76 [Test]
77 public void ConstructorKnownTypesNull ()
79 // null knownTypes is allowed.
80 new DataContractJsonSerializer (typeof (Sample1), (IEnumerable<Type>) null);
81 new DataContractJsonSerializer (typeof (Sample1), "Foo", null);
84 [Test]
85 [ExpectedException (typeof (ArgumentNullException))]
86 public void ConstructorNameNull ()
88 new DataContractJsonSerializer (typeof (Sample1), (string) null);
91 [Test]
92 [ExpectedException (typeof (ArgumentOutOfRangeException))]
93 public void ConstructorNegativeMaxObjects ()
95 new DataContractJsonSerializer (typeof (Sample1), "Sample1",
96 null, -1, false, null, false);
99 [Test]
100 public void ConstructorMisc ()
102 new DataContractJsonSerializer (typeof (GlobalSample1)).WriteObject (new MemoryStream (), new GlobalSample1 ());
105 [Test]
106 public void WriteObjectContent ()
108 StringWriter sw = new StringWriter ();
109 using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
110 DataContractJsonSerializer ser =
111 new DataContractJsonSerializer (typeof (string));
112 xw.WriteStartElement ("my-element");
113 ser.WriteObjectContent (xw, "TEST STRING");
114 xw.WriteEndElement ();
116 Assert.AreEqual ("<my-element>TEST STRING</my-element>",
117 sw.ToString ());
120 // int
122 [Test]
123 public void SerializeIntXml ()
125 StringWriter sw = new StringWriter ();
126 SerializeInt (XmlWriter.Create (sw, settings));
127 Assert.AreEqual (
128 @"<root type=""number"">1</root>",
129 sw.ToString ());
132 [Test]
133 public void SerializeIntJson ()
135 MemoryStream ms = new MemoryStream ();
136 SerializeInt (JsonReaderWriterFactory.CreateJsonWriter (ms));
137 Assert.AreEqual (
138 "1",
139 Encoding.UTF8.GetString (ms.ToArray ()));
142 void SerializeInt (XmlWriter writer)
144 DataContractJsonSerializer ser =
145 new DataContractJsonSerializer (typeof (int));
146 using (XmlWriter w = writer) {
147 ser.WriteObject (w, 1);
151 // int, with rootName
153 [Test]
154 public void SerializeIntXmlWithRootName ()
156 StringWriter sw = new StringWriter ();
157 SerializeIntWithRootName (XmlWriter.Create (sw, settings));
158 Assert.AreEqual (
159 @"<myroot type=""number"">1</myroot>",
160 sw.ToString ());
163 [Test]
164 // since JsonWriter supports only "root" as the root name, using
165 // XmlWriter from JsonReaderWriterFactory will always fail with
166 // an explicit rootName.
167 [ExpectedException (typeof (SerializationException))]
168 public void SerializeIntJsonWithRootName ()
170 MemoryStream ms = new MemoryStream ();
171 SerializeIntWithRootName (JsonReaderWriterFactory.CreateJsonWriter (ms));
172 Assert.AreEqual (
173 "1",
174 Encoding.UTF8.GetString (ms.ToArray ()));
177 void SerializeIntWithRootName (XmlWriter writer)
179 DataContractJsonSerializer ser =
180 new DataContractJsonSerializer (typeof (int), "myroot");
181 using (XmlWriter w = writer) {
182 ser.WriteObject (w, 1);
186 // pass typeof(DCEmpty), serialize int
188 [Test]
189 public void SerializeIntForDCEmptyXml ()
191 StringWriter sw = new StringWriter ();
192 SerializeIntForDCEmpty (XmlWriter.Create (sw, settings));
193 Assert.AreEqual (
194 @"<root type=""number"">1</root>",
195 sw.ToString ());
198 [Test]
199 public void SerializeIntForDCEmptyJson ()
201 MemoryStream ms = new MemoryStream ();
202 SerializeIntForDCEmpty (JsonReaderWriterFactory.CreateJsonWriter (ms));
203 Assert.AreEqual (
204 "1",
205 Encoding.UTF8.GetString (ms.ToArray ()));
208 void SerializeIntForDCEmpty (XmlWriter writer)
210 DataContractJsonSerializer ser =
211 new DataContractJsonSerializer (typeof (DCEmpty));
212 using (XmlWriter w = writer) {
213 ser.WriteObject (w, 1);
217 // DCEmpty
219 [Test]
220 public void SerializeEmptyClassXml ()
222 StringWriter sw = new StringWriter ();
223 SerializeEmptyClass (XmlWriter.Create (sw, settings));
224 Assert.AreEqual (
225 @"<root type=""object"" />",
226 sw.ToString ());
229 [Test]
230 public void SerializeEmptyClassJson ()
232 MemoryStream ms = new MemoryStream ();
233 SerializeEmptyClass (JsonReaderWriterFactory.CreateJsonWriter (ms));
234 Assert.AreEqual (
235 "{}",
236 Encoding.UTF8.GetString (ms.ToArray ()));
239 void SerializeEmptyClass (XmlWriter writer)
241 DataContractJsonSerializer ser =
242 new DataContractJsonSerializer (typeof (DCEmpty));
243 using (XmlWriter w = writer) {
244 ser.WriteObject (w, new DCEmpty ());
248 // string (primitive)
250 [Test]
251 public void SerializePrimitiveStringXml ()
253 StringWriter sw = new StringWriter ();
254 SerializePrimitiveString (XmlWriter.Create (sw, settings));
255 Assert.AreEqual (
256 "<root>TEST</root>",
257 sw.ToString ());
260 [Test]
261 public void SerializePrimitiveStringJson ()
263 MemoryStream ms = new MemoryStream ();
264 SerializePrimitiveString (JsonReaderWriterFactory.CreateJsonWriter (ms));
265 Assert.AreEqual (
266 @"""TEST""",
267 Encoding.UTF8.GetString (ms.ToArray ()));
270 void SerializePrimitiveString (XmlWriter writer)
272 XmlObjectSerializer ser =
273 new DataContractJsonSerializer (typeof (string));
274 using (XmlWriter w = writer) {
275 ser.WriteObject (w, "TEST");
279 // QName (primitive but ...)
281 [Test]
282 public void SerializePrimitiveQNameXml ()
284 StringWriter sw = new StringWriter ();
285 SerializePrimitiveQName (XmlWriter.Create (sw, settings));
286 Assert.AreEqual (
287 "<root>foo:urn:foo</root>",
288 sw.ToString ());
291 [Test]
292 public void SerializePrimitiveQNameJson ()
294 MemoryStream ms = new MemoryStream ();
295 SerializePrimitiveQName (JsonReaderWriterFactory.CreateJsonWriter (ms));
296 Assert.AreEqual (
297 @"""foo:urn:foo""",
298 Encoding.UTF8.GetString (ms.ToArray ()));
301 void SerializePrimitiveQName (XmlWriter writer)
303 XmlObjectSerializer ser =
304 new DataContractJsonSerializer (typeof (XmlQualifiedName));
305 using (XmlWriter w = writer) {
306 ser.WriteObject (w, new XmlQualifiedName ("foo", "urn:foo"));
310 // DBNull (primitive)
312 [Test]
313 public void SerializeDBNullXml ()
315 StringWriter sw = new StringWriter ();
316 SerializeDBNull (XmlWriter.Create (sw, settings));
317 Assert.AreEqual (
318 @"<root type=""object"" />",
319 sw.ToString ());
322 [Test]
323 public void SerializeDBNullJson ()
325 MemoryStream ms = new MemoryStream ();
326 SerializeDBNull (JsonReaderWriterFactory.CreateJsonWriter (ms));
327 Assert.AreEqual (
328 "{}",
329 Encoding.UTF8.GetString (ms.ToArray ()));
332 void SerializeDBNull (XmlWriter writer)
334 DataContractJsonSerializer ser =
335 new DataContractJsonSerializer (typeof (DBNull));
336 using (XmlWriter w = writer) {
337 ser.WriteObject (w, DBNull.Value);
341 // DCSimple1
343 [Test]
344 public void SerializeSimpleClass1Xml ()
346 StringWriter sw = new StringWriter ();
347 SerializeSimpleClass1 (XmlWriter.Create (sw, settings));
348 Assert.AreEqual (
349 @"<root type=""object""><Foo>TEST</Foo></root>",
350 sw.ToString ());
353 [Test]
354 public void SerializeSimpleClass1Json ()
356 MemoryStream ms = new MemoryStream ();
357 SerializeSimpleClass1 (JsonReaderWriterFactory.CreateJsonWriter (ms));
358 Assert.AreEqual (
359 @"{""Foo"":""TEST""}",
360 Encoding.UTF8.GetString (ms.ToArray ()));
363 void SerializeSimpleClass1 (XmlWriter writer)
365 DataContractJsonSerializer ser =
366 new DataContractJsonSerializer (typeof (DCSimple1));
367 using (XmlWriter w = writer) {
368 ser.WriteObject (w, new DCSimple1 ());
372 // NonDC
374 [Test]
375 // NonDC is not a DataContract type.
376 public void SerializeNonDCOnlyCtor ()
378 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (NonDC));
381 [Test]
382 //[ExpectedException (typeof (InvalidDataContractException))]
383 // NonDC is not a DataContract type.
384 // UPDATE: non-DataContract types are became valid in RTM.
385 public void SerializeNonDC ()
387 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (NonDC));
388 using (XmlWriter w = XmlWriter.Create (TextWriter.Null, settings)) {
389 ser.WriteObject (w, new NonDC ());
393 // DCHasNonDC
395 [Test]
396 //[ExpectedException (typeof (InvalidDataContractException))]
397 // DCHasNonDC itself is a DataContract type whose field is
398 // marked as DataMember but its type is not DataContract.
399 // UPDATE: non-DataContract types are became valid in RTM.
400 public void SerializeDCHasNonDC ()
402 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCHasNonDC));
403 using (XmlWriter w = XmlWriter.Create (TextWriter.Null, settings)) {
404 ser.WriteObject (w, new DCHasNonDC ());
408 // DCHasSerializable
410 [Test]
411 public void SerializeSimpleSerializable1Xml ()
413 StringWriter sw = new StringWriter ();
414 SerializeSimpleSerializable1 (XmlWriter.Create (sw, settings));
415 Assert.AreEqual (
416 @"<root type=""object""><Ser type=""object""><Doh>doh!</Doh></Ser></root>",
417 sw.ToString ());
420 [Test]
421 public void SerializeSimpleSerializable1Json ()
423 MemoryStream ms = new MemoryStream ();
424 SerializeSimpleSerializable1 (JsonReaderWriterFactory.CreateJsonWriter (ms));
425 Assert.AreEqual (
426 @"{""Ser"":{""Doh"":""doh!""}}",
427 Encoding.UTF8.GetString (ms.ToArray ()));
430 // DCHasSerializable itself is DataContract and has a field
431 // whose type is not contract but serializable.
432 void SerializeSimpleSerializable1 (XmlWriter writer)
434 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCHasSerializable));
435 using (XmlWriter w = writer) {
436 ser.WriteObject (w, new DCHasSerializable ());
440 [Test]
441 public void SerializeDCWithNameXml ()
443 StringWriter sw = new StringWriter ();
444 SerializeDCWithName (XmlWriter.Create (sw, settings));
445 Assert.AreEqual (
446 @"<root type=""object""><FooMember>value</FooMember></root>",
447 sw.ToString ());
450 [Test]
451 public void SerializeDCWithNameJson ()
453 MemoryStream ms = new MemoryStream ();
454 SerializeDCWithName (JsonReaderWriterFactory.CreateJsonWriter (ms));
455 Assert.AreEqual (
456 @"{""FooMember"":""value""}",
457 Encoding.UTF8.GetString (ms.ToArray ()));
460 void SerializeDCWithName (XmlWriter writer)
462 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithName));
463 using (XmlWriter w = writer) {
464 ser.WriteObject (w, new DCWithName ());
468 [Test]
469 public void SerializeDCWithEmptyName1 ()
471 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEmptyName));
472 StringWriter sw = new StringWriter ();
473 DCWithEmptyName dc = new DCWithEmptyName ();
474 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
475 try {
476 ser.WriteObject (w, dc);
477 } catch (InvalidDataContractException) {
478 return;
481 Assert.Fail ("Expected InvalidDataContractException");
484 [Test]
485 public void SerializeDCWithEmptyName2 ()
487 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithName));
488 StringWriter sw = new StringWriter ();
490 /* DataContractAttribute.Name == "", not valid */
491 DCWithEmptyName dc = new DCWithEmptyName ();
492 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
493 try {
494 ser.WriteObject (w, dc);
495 } catch (InvalidDataContractException) {
496 return;
499 Assert.Fail ("Expected InvalidDataContractException");
502 [Test]
503 [Category("NotWorking")]
504 public void SerializeDCWithNullName ()
506 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithNullName));
507 StringWriter sw = new StringWriter ();
508 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
509 try {
510 /* DataContractAttribute.Name == "", not valid */
511 ser.WriteObject (w, new DCWithNullName ());
512 } catch (InvalidDataContractException) {
513 return;
516 Assert.Fail ("Expected InvalidDataContractException");
519 [Test]
520 public void SerializeDCWithEmptyNamespace1 ()
522 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEmptyNamespace));
523 StringWriter sw = new StringWriter ();
524 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
525 ser.WriteObject (w, new DCWithEmptyNamespace ());
529 [Test]
530 public void SerializeWrappedClassXml ()
532 StringWriter sw = new StringWriter ();
533 SerializeWrappedClass (XmlWriter.Create (sw, settings));
534 Assert.AreEqual (
535 @"<root type=""object"" />",
536 sw.ToString ());
539 [Test]
540 public void SerializeWrappedClassJson ()
542 MemoryStream ms = new MemoryStream ();
543 SerializeWrappedClass (JsonReaderWriterFactory.CreateJsonWriter (ms));
544 Assert.AreEqual (
545 "{}",
546 Encoding.UTF8.GetString (ms.ToArray ()));
549 void SerializeWrappedClass (XmlWriter writer)
551 DataContractJsonSerializer ser =
552 new DataContractJsonSerializer (typeof (Wrapper.DCWrapped));
553 using (XmlWriter w = writer) {
554 ser.WriteObject (w, new Wrapper.DCWrapped ());
558 // CollectionContainer : Items must have a setter. (but became valid in RTM).
559 [Test]
560 public void SerializeReadOnlyCollectionMember ()
562 DataContractJsonSerializer ser =
563 new DataContractJsonSerializer (typeof (CollectionContainer));
564 StringWriter sw = new StringWriter ();
565 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
566 ser.WriteObject (w, null);
570 // DataCollectionContainer : Items must have a setter. (but became valid in RTM).
571 [Test]
572 public void SerializeReadOnlyDataCollectionMember ()
574 DataContractJsonSerializer ser =
575 new DataContractJsonSerializer (typeof (DataCollectionContainer));
576 StringWriter sw = new StringWriter ();
577 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
578 ser.WriteObject (w, null);
582 [Test]
583 [Ignore ("https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=409970")]
584 [ExpectedException (typeof (SerializationException))]
585 public void DeserializeReadOnlyDataCollection_NullCollection ()
587 DataContractJsonSerializer ser =
588 new DataContractJsonSerializer (typeof (CollectionContainer));
589 StringWriter sw = new StringWriter ();
590 var c = new CollectionContainer ();
591 c.Items.Add ("foo");
592 c.Items.Add ("bar");
593 using (XmlWriter w = XmlWriter.Create (sw, settings))
594 ser.WriteObject (w, c);
595 // CollectionContainer.Items is null, so it cannot deserialize non-null collection.
596 using (XmlReader r = XmlReader.Create (new StringReader (sw.ToString ())))
597 c = (CollectionContainer) ser.ReadObject (r);
600 [Test]
601 public void SerializeGuidXml ()
603 StringWriter sw = new StringWriter ();
604 SerializeGuid (XmlWriter.Create (sw, settings));
605 Assert.AreEqual (
606 @"<root>00000000-0000-0000-0000-000000000000</root>",
607 sw.ToString ());
610 [Test]
611 public void SerializeGuidJson ()
613 MemoryStream ms = new MemoryStream ();
614 SerializeGuid (JsonReaderWriterFactory.CreateJsonWriter (ms));
615 Assert.AreEqual (
616 @"""00000000-0000-0000-0000-000000000000""",
617 Encoding.UTF8.GetString (ms.ToArray ()));
620 void SerializeGuid (XmlWriter writer)
622 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Guid));
623 using (XmlWriter w = writer) {
624 ser.WriteObject (w, Guid.Empty);
628 [Test]
629 public void SerializeEnumXml ()
631 StringWriter sw = new StringWriter ();
632 SerializeEnum (XmlWriter.Create (sw, settings));
633 Assert.AreEqual (
634 @"<root type=""number"">0</root>",
635 sw.ToString ());
638 [Test]
639 public void SerializeEnumJson ()
641 MemoryStream ms = new MemoryStream ();
642 SerializeEnum (JsonReaderWriterFactory.CreateJsonWriter (ms));
643 Assert.AreEqual (
644 "0",
645 Encoding.UTF8.GetString (ms.ToArray ()));
648 void SerializeEnum (XmlWriter writer)
650 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Colors));
651 using (XmlWriter w = writer) {
652 ser.WriteObject (w, new Colors ());
656 [Test]
657 public void SerializeEnum2Xml ()
659 StringWriter sw = new StringWriter ();
660 SerializeEnum2 (XmlWriter.Create (sw, settings));
661 Assert.AreEqual (
662 @"<root type=""number"">0</root>",
663 sw.ToString ());
666 [Test]
667 public void SerializeEnum2Json ()
669 MemoryStream ms = new MemoryStream ();
670 SerializeEnum2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
671 Assert.AreEqual (
672 "0",
673 Encoding.UTF8.GetString (ms.ToArray ()));
676 void SerializeEnum2 (XmlWriter writer)
678 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Colors));
679 using (XmlWriter w = writer) {
680 ser.WriteObject (w, 0);
684 [Test] // so, DataContract does not affect here.
685 public void SerializeEnumWithDCXml ()
687 StringWriter sw = new StringWriter ();
688 SerializeEnumWithDC (XmlWriter.Create (sw, settings));
689 Assert.AreEqual (
690 @"<root type=""number"">0</root>",
691 sw.ToString ());
694 [Test]
695 public void SerializeEnumWithDCJson ()
697 MemoryStream ms = new MemoryStream ();
698 SerializeEnumWithDC (JsonReaderWriterFactory.CreateJsonWriter (ms));
699 Assert.AreEqual (
700 "0",
701 Encoding.UTF8.GetString (ms.ToArray ()));
704 void SerializeEnumWithDC (XmlWriter writer)
706 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
707 using (XmlWriter w = writer) {
708 ser.WriteObject (w, new ColorsWithDC ());
712 [Test]
713 public void SerializeEnumWithNoDCXml ()
715 StringWriter sw = new StringWriter ();
716 SerializeEnumWithNoDC (XmlWriter.Create (sw, settings));
717 Assert.AreEqual (
718 @"<root type=""number"">0</root>",
719 sw.ToString ());
722 [Test]
723 public void SerializeEnumWithNoDCJson ()
725 MemoryStream ms = new MemoryStream ();
726 SerializeEnumWithNoDC (JsonReaderWriterFactory.CreateJsonWriter (ms));
727 Assert.AreEqual (
728 "0",
729 Encoding.UTF8.GetString (ms.ToArray ()));
732 void SerializeEnumWithNoDC (XmlWriter writer)
734 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsEnumMemberNoDC));
735 using (XmlWriter w = writer) {
736 ser.WriteObject (w, new ColorsEnumMemberNoDC ());
740 [Test]
741 public void SerializeEnumWithDC2Xml ()
743 StringWriter sw = new StringWriter ();
744 SerializeEnumWithDC2 (XmlWriter.Create (sw, settings));
745 Assert.AreEqual (
746 @"<root type=""number"">3</root>",
747 sw.ToString ());
750 [Test]
751 public void SerializeEnumWithDC2Json ()
753 MemoryStream ms = new MemoryStream ();
754 SerializeEnumWithDC2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
755 Assert.AreEqual (
756 "3",
757 Encoding.UTF8.GetString (ms.ToArray ()));
760 void SerializeEnumWithDC2 (XmlWriter writer)
762 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
763 using (XmlWriter w = writer) {
764 ser.WriteObject (w, 3);
769 [Test]
770 [ExpectedException (typeof (SerializationException))]
771 public void SerializeEnumWithDCInvalid ()
773 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
774 StringWriter sw = new StringWriter ();
775 ColorsWithDC cdc = ColorsWithDC.Blue;
776 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
777 ser.WriteObject (w, cdc);
782 [Test]
783 public void SerializeDCWithEnumXml ()
785 StringWriter sw = new StringWriter ();
786 SerializeDCWithEnum (XmlWriter.Create (sw, settings));
787 Assert.AreEqual (
788 @"<root type=""object""><_colors type=""number"">0</_colors></root>",
789 sw.ToString ());
792 [Test]
793 public void SerializeDCWithEnumJson ()
795 MemoryStream ms = new MemoryStream ();
796 SerializeDCWithEnum (JsonReaderWriterFactory.CreateJsonWriter (ms));
797 Assert.AreEqual (
798 @"{""_colors"":0}",
799 Encoding.UTF8.GetString (ms.ToArray ()));
802 void SerializeDCWithEnum (XmlWriter writer)
804 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEnum));
805 using (XmlWriter w = writer) {
806 ser.WriteObject (w, new DCWithEnum ());
810 [Test]
811 public void SerializerDCArrayXml ()
813 StringWriter sw = new StringWriter ();
814 SerializerDCArray (XmlWriter.Create (sw, settings));
815 Assert.AreEqual (
816 @"<root type=""array""><item type=""object""><_colors type=""number"">0</_colors></item><item type=""object""><_colors type=""number"">1</_colors></item></root>",
817 sw.ToString ());
820 [Test]
821 public void SerializerDCArrayJson ()
823 MemoryStream ms = new MemoryStream ();
824 SerializerDCArray (JsonReaderWriterFactory.CreateJsonWriter (ms));
825 Assert.AreEqual (
826 @"[{""_colors"":0},{""_colors"":1}]",
827 Encoding.UTF8.GetString (ms.ToArray ()));
830 void SerializerDCArray (XmlWriter writer)
832 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEnum []));
833 DCWithEnum [] arr = new DCWithEnum [2];
834 arr [0] = new DCWithEnum (); arr [0].colors = Colors.Red;
835 arr [1] = new DCWithEnum (); arr [1].colors = Colors.Green;
836 using (XmlWriter w = writer) {
837 ser.WriteObject (w, arr);
841 [Test]
842 public void SerializerDCArray2Xml ()
844 StringWriter sw = new StringWriter ();
845 SerializerDCArray2 (XmlWriter.Create (sw, settings));
846 Assert.AreEqual (
847 @"<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>",
848 sw.ToString ());
851 [Test]
852 public void SerializerDCArray2Json ()
854 MemoryStream ms = new MemoryStream ();
855 SerializerDCArray2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
856 Assert.AreEqual (
857 @"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0},{""__type"":""DCSimple1:#MonoTests.System.Runtime.Serialization.Json"",""Foo"":""hello""}]",
858 Encoding.UTF8.GetString (ms.ToArray ()));
861 void SerializerDCArray2 (XmlWriter writer)
863 List<Type> known = new List<Type> ();
864 known.Add (typeof (DCWithEnum));
865 known.Add (typeof (DCSimple1));
866 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (object []), known);
867 object [] arr = new object [2];
868 arr [0] = new DCWithEnum (); ((DCWithEnum)arr [0]).colors = Colors.Red;
869 arr [1] = new DCSimple1 (); ((DCSimple1) arr [1]).Foo = "hello";
871 using (XmlWriter w = writer) {
872 ser.WriteObject (w, arr);
876 [Test]
877 public void SerializerDCArray3Xml ()
879 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (int []));
880 StringWriter sw = new StringWriter ();
881 int [] arr = new int [2];
882 arr [0] = 1; arr [1] = 2;
884 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
885 ser.WriteObject (w, arr);
888 Assert.AreEqual (
889 @"<root type=""array""><item type=""number"">1</item><item type=""number"">2</item></root>",
890 sw.ToString ());
893 [Test]
894 public void SerializerDCArray3Json ()
896 MemoryStream ms = new MemoryStream ();
897 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (int []));
898 int [] arr = new int [2];
899 arr [0] = 1; arr [1] = 2;
901 using (XmlWriter w = JsonReaderWriterFactory.CreateJsonWriter (ms)) {
902 ser.WriteObject (w, arr);
905 Assert.AreEqual (
906 @"[1,2]",
907 Encoding.UTF8.GetString (ms.ToArray ()));
910 [Test]
911 // ... so, non-JSON XmlWriter is still accepted.
912 public void SerializeNonDCArrayXml ()
914 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
915 StringWriter sw = new StringWriter ();
916 using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
917 ser.WriteObject (xw, new SerializeNonDCArrayType ());
919 Assert.AreEqual (@"<root type=""object""><IPAddresses type=""array"" /></root>",
920 sw.ToString ());
923 [Test]
924 public void SerializeNonDCArrayJson ()
926 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
927 MemoryStream ms = new MemoryStream ();
928 using (XmlWriter xw = JsonReaderWriterFactory.CreateJsonWriter (ms)) {
929 ser.WriteObject (xw, new SerializeNonDCArrayType ());
931 Assert.AreEqual (@"{""IPAddresses"":[]}",
932 Encoding.UTF8.GetString (ms.ToArray ()));
935 [Test]
936 public void SerializeNonDCArrayItems ()
938 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
939 StringWriter sw = new StringWriter ();
940 using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
941 SerializeNonDCArrayType obj = new SerializeNonDCArrayType ();
942 obj.IPAddresses = new NonDCItem [] {new NonDCItem () { Data = new byte [] {1, 2, 3, 4} } };
943 ser.WriteObject (xw, obj);
946 XmlDocument doc = new XmlDocument ();
947 doc.LoadXml (sw.ToString ());
948 XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
949 nsmgr.AddNamespace ("s", "http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization");
950 nsmgr.AddNamespace ("n", "http://schemas.datacontract.org/2004/07/System.Net");
951 nsmgr.AddNamespace ("a", "http://schemas.microsoft.com/2003/10/Serialization/Arrays");
953 Assert.AreEqual (1, doc.SelectNodes ("/root/IPAddresses/item", nsmgr).Count, "#1");
954 XmlElement el = doc.SelectSingleNode ("/root/IPAddresses/item/Data", nsmgr) as XmlElement;
955 Assert.IsNotNull (el, "#3");
956 Assert.AreEqual (4, el.SelectNodes ("item", nsmgr).Count, "#4");
959 [Test]
960 public void MaxItemsInObjectGraph1 ()
962 // object count == maximum
963 DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCEmpty), null, 1, false, null, false);
964 s.WriteObject (XmlWriter.Create (TextWriter.Null), new DCEmpty ());
967 [Test]
968 [ExpectedException (typeof (SerializationException))]
969 public void MaxItemsInObjectGraph2 ()
971 // object count > maximum
972 DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCSimple1), null, 1, false, null, false);
973 s.WriteObject (XmlWriter.Create (TextWriter.Null), new DCSimple1 ());
976 [Test]
977 public void DeserializeString ()
979 Assert.AreEqual ("ABC", Deserialize ("\"ABC\"", typeof (string)));
982 [Test]
983 public void DeserializeInt ()
985 Assert.AreEqual (5, Deserialize ("5", typeof (int)));
988 [Test]
989 public void DeserializeArray ()
991 int [] ret = (int []) Deserialize ("[5,6,7]", typeof (int []));
992 Assert.AreEqual (5, ret [0], "#1");
993 Assert.AreEqual (6, ret [1], "#2");
994 Assert.AreEqual (7, ret [2], "#3");
997 [Test]
998 public void DeserializeArrayUntyped ()
1000 object [] ret = (object []) Deserialize ("[5,6,7]", typeof (object []));
1001 Assert.AreEqual (5, ret [0], "#1");
1002 Assert.AreEqual (6, ret [1], "#2");
1003 Assert.AreEqual (7, ret [2], "#3");
1006 [Test]
1007 public void DeserializeMixedArray ()
1009 object [] ret = (object []) Deserialize ("[5,\"6\",false]", typeof (object []));
1010 Assert.AreEqual (5, ret [0], "#1");
1011 Assert.AreEqual ("6", ret [1], "#2");
1012 Assert.AreEqual (false, ret [2], "#3");
1015 [Test]
1016 [ExpectedException (typeof (SerializationException))]
1017 public void DeserializeEmptyAsString ()
1019 // it somehow expects "root" which should have been already consumed.
1020 Deserialize ("", typeof (string));
1023 [Test]
1024 [ExpectedException (typeof (SerializationException))]
1025 public void DeserializeEmptyAsInt ()
1027 // it somehow expects "root" which should have been already consumed.
1028 Deserialize ("", typeof (int));
1031 [Test]
1032 [ExpectedException (typeof (SerializationException))]
1033 public void DeserializeEmptyAsDBNull ()
1035 // it somehow expects "root" which should have been already consumed.
1036 Deserialize ("", typeof (DBNull));
1039 [Test]
1040 public void DeserializeEmptyObjectAsString ()
1042 // looks like it is converted to ""
1043 Assert.AreEqual (String.Empty, Deserialize ("{}", typeof (string)));
1046 [Test]
1047 [ExpectedException (typeof (SerializationException))]
1048 public void DeserializeEmptyObjectAsInt ()
1050 Deserialize ("{}", typeof (int));
1053 [Test]
1054 public void DeserializeEmptyObjectAsDBNull ()
1056 Assert.AreEqual (DBNull.Value, Deserialize ("{}", typeof (DBNull)));
1059 [Test]
1060 [ExpectedException (typeof (SerializationException))]
1061 public void DeserializeEnumByName ()
1063 // enum is parsed into long
1064 Deserialize (@"""Red""", typeof (Colors));
1067 [Test]
1068 public void DeserializeEnum2 ()
1070 object o = Deserialize ("0", typeof (Colors));
1072 Assert.AreEqual (typeof (Colors), o.GetType (), "#de3");
1073 Colors c = (Colors) o;
1074 Assert.AreEqual (Colors.Red, c, "#de4");
1077 [Test]
1078 [ExpectedException (typeof (SerializationException))]
1079 public void DeserializeEnumInvalid ()
1081 Deserialize ("", typeof (Colors));
1084 [Test]
1085 [ExpectedException (typeof (SerializationException))]
1086 [Ignore ("NotDotNet")] // 0.0 is an invalid Colors value.
1087 public void DeserializeEnumInvalid3 ()
1089 //"0.0" instead of "0"
1090 Deserialize (
1091 "0.0",
1092 typeof (Colors));
1095 [Test]
1096 public void DeserializeEnumWithDC ()
1098 object o = Deserialize ("0", typeof (ColorsWithDC));
1100 Assert.AreEqual (typeof (ColorsWithDC), o.GetType (), "#de5");
1101 ColorsWithDC cdc = (ColorsWithDC) o;
1102 Assert.AreEqual (ColorsWithDC.Red, o, "#de6");
1105 [Test]
1106 [ExpectedException (typeof (SerializationException))]
1107 [Ignore ("NotDotNet")] // 4 is an invalid Colors value.
1108 [Category ("NotWorking")]
1109 public void DeserializeEnumWithDCInvalid ()
1111 Deserialize (
1112 "4",
1113 typeof (ColorsWithDC));
1116 [Test]
1117 public void DeserializeDCWithEnum ()
1119 object o = Deserialize (
1120 "{\"_colors\":0}",
1121 typeof (DCWithEnum));
1123 Assert.AreEqual (typeof (DCWithEnum), o.GetType (), "#de7");
1124 DCWithEnum dc = (DCWithEnum) o;
1125 Assert.AreEqual (Colors.Red, dc.colors, "#de8");
1128 [Test]
1129 public void ReadObjectVerifyObjectNameFalse ()
1131 string xml = @"<any><Member1>bar</Member1></any>";
1132 object o = new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1133 .ReadObject (XmlReader.Create (new StringReader (xml)), false);
1134 Assert.IsTrue (o is VerifyObjectNameTestData, "#1");
1136 string xml2 = @"<any><x:Member1 xmlns:x=""http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"">bar</x:Member1></any>";
1137 o = new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1138 .ReadObject (XmlReader.Create (new StringReader (xml2)), false);
1139 Assert.IsTrue (o is VerifyObjectNameTestData, "#2");
1142 [Test]
1143 [ExpectedException (typeof (SerializationException))]
1144 public void ReadObjectVerifyObjectNameTrue ()
1146 string xml = @"<any><Member1>bar</Member1></any>";
1147 new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1148 .ReadObject (XmlReader.Create (new StringReader (xml)), true);
1151 [Test] // member name is out of scope
1152 public void ReadObjectVerifyObjectNameTrue2 ()
1154 string xml = @"<root><Member2>bar</Member2></root>";
1155 new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1156 .ReadObject (XmlReader.Create (new StringReader (xml)), true);
1159 [Test]
1160 public void ReadTypedObjectJson ()
1162 object o = Deserialize (@"{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0}", typeof (DCWithEnum));
1163 Assert.AreEqual (typeof (DCWithEnum), o.GetType ());
1166 [Test]
1167 public void ReadObjectDCArrayJson ()
1169 object o = Deserialize (@"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0}]",
1170 typeof (object []), typeof (DCWithEnum));
1171 Assert.AreEqual (typeof (object []), o.GetType (), "#1");
1172 object [] arr = (object []) o;
1173 Assert.AreEqual (typeof (DCWithEnum), arr [0].GetType (), "#2");
1176 [Test]
1177 public void ReadObjectDCArray2Json ()
1179 object o = Deserialize (@"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0},{""__type"":""DCSimple1:#MonoTests.System.Runtime.Serialization.Json"",""Foo"":""hello""}]",
1180 typeof (object []), typeof (DCWithEnum), typeof (DCSimple1));
1181 Assert.AreEqual (typeof (object []), o.GetType (), "#1");
1182 object [] arr = (object []) o;
1183 Assert.AreEqual (typeof (DCWithEnum), arr [0].GetType (), "#2");
1184 Assert.AreEqual (typeof (DCSimple1), arr [1].GetType (), "#3");
1187 private object Deserialize (string xml, Type type, params Type [] knownTypes)
1189 DataContractJsonSerializer ser = new DataContractJsonSerializer (type, knownTypes);
1190 XmlReader xr = JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (xml), new XmlDictionaryReaderQuotas ());
1191 return ser.ReadObject (xr);
1194 public T Deserialize<T>(string json)
1196 var bytes = Encoding.Unicode.GetBytes (json);
1197 using (MemoryStream stream = new MemoryStream (bytes)) {
1198 var serializer = new DataContractJsonSerializer (typeof(T));
1199 return (T)serializer.ReadObject (stream);
1203 [Test]
1204 public void IsStartObject ()
1206 DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCSimple1));
1207 Assert.IsTrue (s.IsStartObject (XmlReader.Create (new StringReader ("<root></root>"))), "#1");
1208 Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<dummy></dummy>"))), "#2");
1209 Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<Foo></Foo>"))), "#3");
1210 Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<root xmlns='urn:foo'></root>"))), "#4");
1213 [Test]
1214 public void SerializeNonDC2 ()
1216 var ser = new DataContractJsonSerializer (typeof (TestData));
1217 StringWriter sw = new StringWriter ();
1218 var obj = new TestData () { Foo = "foo", Bar = "bar", Baz = "baz" };
1220 // XML
1221 using (var xw = XmlWriter.Create (sw))
1222 ser.WriteObject (xw, obj);
1223 var s = sw.ToString ();
1224 // since the order is not preserved, we compare only contents.
1225 Assert.IsTrue (s.IndexOf ("<Foo>foo</Foo>") > 0, "#1-1");
1226 Assert.IsTrue (s.IndexOf ("<Bar>bar</Bar>") > 0, "#1-2");
1227 Assert.IsFalse (s.IndexOf ("<Baz>baz</Baz>") > 0, "#1-3");
1229 // JSON
1230 MemoryStream ms = new MemoryStream ();
1231 using (var xw = JsonReaderWriterFactory.CreateJsonWriter (ms))
1232 ser.WriteObject (ms, obj);
1233 s = new StreamReader (new MemoryStream (ms.ToArray ())).ReadToEnd ().Replace ('"', '/');
1234 // since the order is not preserved, we compare only contents.
1235 Assert.IsTrue (s.IndexOf ("/Foo/:/foo/") > 0, "#2-1");
1236 Assert.IsTrue (s.IndexOf ("/Bar/:/bar/") > 0, "#2-2");
1237 Assert.IsFalse (s.IndexOf ("/Baz/:/baz/") > 0, "#2-3");
1240 [Test]
1241 public void AlwaysEmitTypeInformation ()
1243 var ms = new MemoryStream ();
1244 var ds = new DataContractJsonSerializer (typeof (string), "root", null, 10, false, null, true);
1245 ds.WriteObject (ms, "foobar");
1246 var s = Encoding.UTF8.GetString (ms.ToArray ());
1247 Assert.AreEqual ("\"foobar\"", s, "#1");
1250 [Test]
1251 public void AlwaysEmitTypeInformation2 ()
1253 var ms = new MemoryStream ();
1254 var ds = new DataContractJsonSerializer (typeof (TestData), "root", null, 10, false, null, true);
1255 ds.WriteObject (ms, new TestData () { Foo = "foo"});
1256 var s = Encoding.UTF8.GetString (ms.ToArray ());
1257 Assert.AreEqual (@"{""__type"":""TestData:#MonoTests.System.Runtime.Serialization.Json"",""Bar"":null,""Foo"":""foo""}", s, "#1");
1260 [Test]
1261 public void AlwaysEmitTypeInformation3 ()
1263 var ms = new MemoryStream ();
1264 var ds = new DataContractJsonSerializer (typeof (TestData), "root", null, 10, false, null, false);
1265 ds.WriteObject (ms, new TestData () { Foo = "foo"});
1266 var s = Encoding.UTF8.GetString (ms.ToArray ());
1267 Assert.AreEqual (@"{""Bar"":null,""Foo"":""foo""}", s, "#1");
1270 [Test]
1271 public void TestNonpublicDeserialization ()
1273 string s1= @"{""Bar"":""bar"", ""Foo"":""foo"", ""Baz"":""baz""}";
1274 TestData o1 = ((TestData)(new DataContractJsonSerializer (typeof (TestData)).ReadObject (JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (s1), new XmlDictionaryReaderQuotas ()))));
1276 Assert.AreEqual (null, o1.Baz, "#1");
1278 string s2 = @"{""TestData"":[{""key"":""key1"",""value"":""value1""}]}";
1279 KeyValueTestData o2 = ((KeyValueTestData)(new DataContractJsonSerializer (typeof (KeyValueTestData)).ReadObject (JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (s2), new XmlDictionaryReaderQuotas ()))));
1281 Assert.AreEqual (1, o2.TestData.Count, "#2");
1282 Assert.AreEqual ("key1", o2.TestData[0].Key, "#3");
1283 Assert.AreEqual ("value1", o2.TestData[0].Value, "#4");
1286 // [Test] use this case if you want to check lame silverlight parser behavior. Seealso #549756
1287 public void QuotelessDeserialization ()
1289 string s1 = @"{FooMember:""value""}";
1290 var ds = new DataContractJsonSerializer (typeof (DCWithName));
1291 ds.ReadObject (new MemoryStream (Encoding.UTF8.GetBytes (s1)));
1293 string s2 = @"{FooMember:"" \""{dummy:string}\""""}";
1294 ds.ReadObject (new MemoryStream (Encoding.UTF8.GetBytes (s2)));
1297 [Test]
1298 [Category ("NotWorking")]
1299 public void TypeIsNotPartsOfKnownTypes ()
1301 var dcs = new DataContractSerializer (typeof (string));
1302 Assert.AreEqual (0, dcs.KnownTypes.Count, "KnownTypes #1");
1303 var dcjs = new DataContractJsonSerializer (typeof (string));
1304 Assert.AreEqual (0, dcjs.KnownTypes.Count, "KnownTypes #2");
1307 [Test]
1308 public void ReadWriteNullObject ()
1310 DataContractJsonSerializer dcjs = new DataContractJsonSerializer (typeof (string));
1311 using (MemoryStream ms = new MemoryStream ()) {
1312 dcjs.WriteObject (ms, null);
1313 ms.Position = 0;
1314 using (StreamReader sr = new StreamReader (ms)) {
1315 string data = sr.ReadToEnd ();
1316 Assert.AreEqual ("null", data, "WriteObject(stream,null)");
1318 ms.Position = 0;
1319 Assert.IsNull (dcjs.ReadObject (ms), "ReadObject(stream)");
1324 object ReadWriteObject (Type type, object obj, string expected)
1326 using (MemoryStream ms = new MemoryStream ()) {
1327 DataContractJsonSerializer dcjs = new DataContractJsonSerializer (type);
1328 dcjs.WriteObject (ms, obj);
1329 ms.Position = 0;
1330 using (StreamReader sr = new StreamReader (ms)) {
1331 Assert.AreEqual (expected, sr.ReadToEnd (), "WriteObject");
1333 ms.Position = 0;
1334 return dcjs.ReadObject (ms);
1339 [Test]
1340 [Ignore ("Wrong test case. See bug #573691")]
1341 public void ReadWriteObject_Single_SpecialCases ()
1343 Assert.IsTrue (Single.IsNaN ((float) ReadWriteObject (typeof (float), Single.NaN, "NaN")));
1344 Assert.IsTrue (Single.IsNegativeInfinity ((float) ReadWriteObject (typeof (float), Single.NegativeInfinity, "-INF")));
1345 Assert.IsTrue (Single.IsPositiveInfinity ((float) ReadWriteObject (typeof (float), Single.PositiveInfinity, "INF")));
1348 [Test]
1349 [Ignore ("Wrong test case. See bug #573691")]
1350 public void ReadWriteObject_Double_SpecialCases ()
1352 Assert.IsTrue (Double.IsNaN ((double) ReadWriteObject (typeof (double), Double.NaN, "NaN")));
1353 Assert.IsTrue (Double.IsNegativeInfinity ((double) ReadWriteObject (typeof (double), Double.NegativeInfinity, "-INF")));
1354 Assert.IsTrue (Double.IsPositiveInfinity ((double) ReadWriteObject (typeof (double), Double.PositiveInfinity, "INF")));
1357 [Test]
1358 public void ReadWriteDateTime ()
1360 var ms = new MemoryStream ();
1361 DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (Query));
1362 Query query = new Query () {
1363 StartDate = DateTime.SpecifyKind (new DateTime (2010, 3, 4, 5, 6, 7), DateTimeKind.Utc),
1364 EndDate = DateTime.SpecifyKind (new DateTime (2010, 4, 5, 6, 7, 8), DateTimeKind.Utc)
1366 serializer.WriteObject (ms, query);
1367 Assert.AreEqual ("{\"StartDate\":\"\\/Date(1267679167000)\\/\",\"EndDate\":\"\\/Date(1270447628000)\\/\"}", Encoding.UTF8.GetString (ms.ToArray ()), "#1");
1368 ms.Position = 0;
1369 Console.WriteLine (new StreamReader (ms).ReadToEnd ());
1370 ms.Position = 0;
1371 var q = (Query) serializer.ReadObject(ms);
1372 Assert.AreEqual (query.StartDate, q.StartDate, "#2");
1373 Assert.AreEqual (query.EndDate, q.EndDate, "#3");
1376 [DataContract(Name = "DateTest")]
1377 public class DateTest
1379 [DataMember(Name = "should_have_value")]
1380 public DateTime? ShouldHaveValue { get; set; }
1384 // This tests both the extended format "number-0500" as well
1385 // as the nullable field in the structure
1386 [Test]
1387 public void BugXamarin163 ()
1389 string json = @"{""should_have_value"":""\/Date(1277355600000)\/""}";
1391 byte[] bytes = global::System.Text.Encoding.UTF8.GetBytes(json);
1392 Stream inputStream = new MemoryStream(bytes);
1394 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DateTest));
1395 DateTest t = serializer.ReadObject(inputStream) as DateTest;
1396 Assert.AreEqual (634129524000000000, t.ShouldHaveValue.Value.Ticks, "#1");
1399 [Test]
1400 public void NullableFieldsShouldSupportNullValue ()
1402 string json = @"{""should_have_value"":null}";
1403 var inputStream = new MemoryStream (Encoding.UTF8.GetBytes (json));
1404 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DateTest));
1405 Console.WriteLine ("# serializer assembly: {0}", serializer.GetType ().Assembly.Location);
1406 DateTest t = serializer.ReadObject (inputStream) as DateTest;
1407 Assert.AreEqual (false, t.ShouldHaveValue.HasValue, "#2");
1410 [Test]
1411 public void DeserializeNullMember ()
1413 var ds = new DataContractJsonSerializer (typeof (ClassA));
1414 var stream = new MemoryStream ();
1415 var a = new ClassA ();
1416 ds.WriteObject (stream, a);
1417 stream.Position = 0;
1418 a = (ClassA) ds.ReadObject (stream);
1419 Assert.IsNull (a.B, "#1");
1422 [Test]
1423 public void OnDeserializationMethods ()
1425 var ds = new DataContractJsonSerializer (typeof (GSPlayerListErg));
1426 var obj = new GSPlayerListErg ();
1427 var ms = new MemoryStream ();
1428 ds.WriteObject (ms, obj);
1429 ms.Position = 0;
1430 ds.ReadObject (ms);
1431 Assert.IsTrue (GSPlayerListErg.A, "A");
1432 Assert.IsTrue (GSPlayerListErg.B, "B");
1433 Assert.IsTrue (GSPlayerListErg.C, "C");
1436 [Test]
1437 public void WriteChar ()
1439 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof (CharTest));
1440 using (MemoryStream ms = new MemoryStream()) {
1441 serializer.WriteObject(ms, new CharTest ());
1442 ms.Position = 0L;
1443 using (StreamReader reader = new StreamReader(ms)) {
1444 reader.ReadToEnd();
1449 [Test]
1450 public void DictionarySerialization ()
1452 var dict = new MyDictionary<string,string> ();
1453 dict.Add ("key", "value");
1454 var serializer = new DataContractJsonSerializer (dict.GetType ());
1455 var stream = new MemoryStream ();
1456 serializer.WriteObject (stream, dict);
1457 stream.Position = 0;
1459 Assert.AreEqual ("[{\"Key\":\"key\",\"Value\":\"value\"}]", new StreamReader (stream).ReadToEnd (), "#1");
1460 stream.Position = 0;
1461 dict = (MyDictionary<string,string>) serializer.ReadObject (stream);
1462 Assert.AreEqual (1, dict.Count, "#2");
1463 Assert.AreEqual ("value", dict ["key"], "#3");
1466 [Test]
1467 public void ExplicitCustomDictionarySerialization ()
1469 var dict = new MyExplicitDictionary<string,string> ();
1470 dict.Add ("key", "value");
1471 var serializer = new DataContractJsonSerializer (dict.GetType ());
1472 var stream = new MemoryStream ();
1473 serializer.WriteObject (stream, dict);
1474 stream.Position = 0;
1476 Assert.AreEqual ("[{\"Key\":\"key\",\"Value\":\"value\"}]", new StreamReader (stream).ReadToEnd (), "#1");
1477 stream.Position = 0;
1478 dict = (MyExplicitDictionary<string,string>) serializer.ReadObject (stream);
1479 Assert.AreEqual (1, dict.Count, "#2");
1480 Assert.AreEqual ("value", dict ["key"], "#3");
1483 [Test]
1484 public void Bug13485 ()
1486 const string json = "{ \"Name\" : \"Test\", \"Value\" : \"ValueA\" }";
1488 string result = string.Empty;
1489 var serializer = new DataContractJsonSerializer (typeof (Bug13485Type));
1490 Bug13485Type entity;
1491 using (var stream = new MemoryStream (Encoding.UTF8.GetBytes (json)))
1492 entity = (Bug13485Type) serializer.ReadObject (stream);
1494 result = entity.GetValue;
1495 Assert.AreEqual ("ValueA", result, "#1");
1498 [DataContract(Name = "UriTest")]
1499 public class UriTest
1501 [DataMember(Name = "members")]
1502 public Uri MembersRelativeLink { get; set; }
1505 [Test]
1506 public void Bug15169 ()
1508 const string json = "{\"members\":\"foo/bar/members\"}";
1509 var serializer = new DataContractJsonSerializer (typeof (UriTest));
1510 UriTest entity;
1511 using (var stream = new MemoryStream (Encoding.UTF8.GetBytes (json)))
1512 entity = (UriTest) serializer.ReadObject (stream);
1514 Assert.AreEqual ("foo/bar/members", entity.MembersRelativeLink.ToString ());
1517 #region Test methods for collection serialization
1519 [Test]
1520 public void TestArrayListSerialization ()
1522 var collection = new ArrayListContainer ();
1523 var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
1524 var expectedItemsCount = 4;
1526 var serializer = new DataContractJsonSerializer (collection.GetType ());
1527 var stream = new MemoryStream ();
1528 serializer.WriteObject (stream, collection);
1530 stream.Position = 0;
1531 Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1533 stream.Position = 0;
1534 collection = (ArrayListContainer) serializer.ReadObject (stream);
1536 Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
1539 [Test]
1540 [ExpectedException (typeof (InvalidDataContractException))]
1541 public void TestBitArraySerialization ()
1543 var collection = new BitArrayContainer ();
1544 var serializer = new DataContractJsonSerializer (collection.GetType ());
1545 var stream = new MemoryStream ();
1546 serializer.WriteObject (stream, collection);
1549 [Test]
1550 public void TestHashtableSerialization ()
1552 var collection = new HashtableContainer ();
1553 var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
1555 var serializer = new DataContractJsonSerializer (collection.GetType ());
1556 var stream = new MemoryStream ();
1557 serializer.WriteObject (stream, collection);
1559 stream.Position = 0;
1560 Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1563 [Test]
1564 [ExpectedException (typeof (ArgumentException))]
1565 public void TestHashtableDeserialization ()
1567 var collection = new HashtableContainer ();
1568 var serializer = new DataContractJsonSerializer (collection.GetType ());
1569 var stream = new MemoryStream ();
1570 serializer.WriteObject (stream, collection);
1572 stream.Position = 0;
1573 serializer.ReadObject (stream);
1576 [Test]
1577 [ExpectedException (typeof (InvalidDataContractException))]
1578 public void TestQueueSerialization ()
1580 var collection = new QueueContainer ();
1581 var serializer = new DataContractJsonSerializer (collection.GetType ());
1582 var stream = new MemoryStream ();
1583 serializer.WriteObject (stream, collection);
1586 [Test]
1587 public void TestSortedListSerialization ()
1589 var collection = new SortedListContainer ();
1590 var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
1592 var serializer = new DataContractJsonSerializer (collection.GetType ());
1593 var stream = new MemoryStream ();
1594 serializer.WriteObject (stream, collection);
1596 stream.Position = 0;
1597 Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1600 [Test]
1601 [ExpectedException (typeof (ArgumentException))]
1602 public void TestSortedListDeserialization ()
1604 var collection = new SortedListContainer ();
1605 var serializer = new DataContractJsonSerializer (collection.GetType ());
1606 var stream = new MemoryStream ();
1607 serializer.WriteObject (stream, collection);
1609 stream.Position = 0;
1610 serializer.ReadObject (stream);
1613 [Test]
1614 [ExpectedException (typeof (InvalidDataContractException))]
1615 public void TestStackSerialization ()
1617 var collection = new StackContainer ();
1618 var serializer = new DataContractJsonSerializer (collection.GetType ());
1619 var stream = new MemoryStream ();
1620 serializer.WriteObject (stream, collection);
1623 [Test]
1624 public void TestEnumerableWithAddSerialization ()
1626 var collection = new EnumerableWithAddContainer ();
1627 var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
1628 var expectedItemsCount = 4;
1630 var serializer = new DataContractJsonSerializer (collection.GetType ());
1631 var stream = new MemoryStream ();
1632 serializer.WriteObject (stream, collection);
1634 stream.Position = 0;
1635 Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1637 stream.Position = 0;
1638 collection = (EnumerableWithAddContainer) serializer.ReadObject (stream);
1640 Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
1643 [Test]
1644 [ExpectedException (typeof (InvalidDataContractException))]
1645 public void TestEnumerableWithSpecialAddSerialization ()
1647 var collection = new EnumerableWithSpecialAddContainer ();
1648 var serializer = new DataContractJsonSerializer (collection.GetType ());
1649 var stream = new MemoryStream ();
1650 serializer.WriteObject (stream, collection);
1653 [Test]
1654 public void TestHashSetSerialization ()
1656 var collection = new GenericHashSetContainer ();
1657 var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
1658 var expectedItemsCount = 2;
1660 var serializer = new DataContractJsonSerializer (collection.GetType ());
1661 var stream = new MemoryStream ();
1662 serializer.WriteObject (stream, collection);
1664 stream.Position = 0;
1665 Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1667 stream.Position = 0;
1668 collection = (GenericHashSetContainer) serializer.ReadObject (stream);
1670 Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
1673 [Test]
1674 public void TestLinkedListSerialization ()
1676 var collection = new GenericLinkedListContainer ();
1677 var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
1678 var expectedItemsCount = 4;
1680 var serializer = new DataContractJsonSerializer (collection.GetType ());
1681 var stream = new MemoryStream ();
1682 serializer.WriteObject (stream, collection);
1684 stream.Position = 0;
1685 Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1687 stream.Position = 0;
1688 collection = (GenericLinkedListContainer) serializer.ReadObject (stream);
1690 Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
1693 [Test]
1694 [ExpectedException (typeof (InvalidDataContractException))]
1695 public void TestGenericQueueSerialization ()
1697 var collection = new GenericQueueContainer ();
1698 var serializer = new DataContractJsonSerializer (collection.GetType ());
1699 var stream = new MemoryStream ();
1700 serializer.WriteObject (stream, collection);
1703 [Test]
1704 [ExpectedException (typeof (InvalidDataContractException))]
1705 public void TestGenericStackSerialization ()
1707 var collection = new GenericStackContainer ();
1708 var serializer = new DataContractJsonSerializer (collection.GetType ());
1709 var stream = new MemoryStream ();
1710 serializer.WriteObject (stream, collection);
1713 [Test]
1714 public void TestGenericDictionarySerialization ()
1716 var collection = new GenericDictionaryContainer ();
1717 var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
1718 var serializer = new DataContractJsonSerializer (collection.GetType ());
1719 var stream = new MemoryStream ();
1720 serializer.WriteObject (stream, collection);
1722 stream.Position = 0;
1723 Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1726 [Test]
1727 [ExpectedException (typeof (ArgumentException))]
1728 public void TestGenericDictionaryDeserialization ()
1730 var collection = new GenericDictionaryContainer ();
1731 var serializer = new DataContractJsonSerializer (collection.GetType ());
1732 var stream = new MemoryStream ();
1733 serializer.WriteObject (stream, collection);
1735 stream.Position = 0;
1736 serializer.ReadObject (stream);
1739 [Test]
1740 public void TestGenericSortedListSerialization ()
1742 var collection = new GenericSortedListContainer ();
1743 var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
1744 var serializer = new DataContractJsonSerializer (collection.GetType ());
1745 var stream = new MemoryStream ();
1746 serializer.WriteObject (stream, collection);
1748 stream.Position = 0;
1749 Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1752 [Test]
1753 [ExpectedException (typeof (ArgumentException))]
1754 public void TestGenericSortedListDeserialization ()
1756 var collection = new GenericSortedListContainer ();
1757 var serializer = new DataContractJsonSerializer (collection.GetType ());
1758 var stream = new MemoryStream ();
1759 serializer.WriteObject (stream, collection);
1761 stream.Position = 0;
1762 serializer.ReadObject (stream);
1765 [Test]
1766 public void TestGenericSortedDictionarySerialization ()
1768 var collection = new GenericSortedDictionaryContainer ();
1769 var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
1770 var serializer = new DataContractJsonSerializer (collection.GetType ());
1771 var stream = new MemoryStream ();
1772 serializer.WriteObject (stream, collection);
1774 stream.Position = 0;
1775 Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1778 [Test]
1779 [ExpectedException (typeof (ArgumentException))]
1780 public void TestGenericSortedDictionaryDeserialization ()
1782 var collection = new GenericSortedDictionaryContainer ();
1783 var serializer = new DataContractJsonSerializer (collection.GetType ());
1784 var stream = new MemoryStream ();
1785 serializer.WriteObject (stream, collection);
1787 stream.Position = 0;
1788 serializer.ReadObject (stream);
1791 [Test]
1792 public void TestGenericEnumerableWithAddSerialization ()
1794 var collection = new GenericEnumerableWithAddContainer ();
1795 var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
1796 var expectedItemsCount = 4;
1798 var serializer = new DataContractJsonSerializer (collection.GetType ());
1799 var stream = new MemoryStream ();
1800 serializer.WriteObject (stream, collection);
1802 stream.Position = 0;
1803 Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1805 stream.Position = 0;
1806 collection = (GenericEnumerableWithAddContainer) serializer.ReadObject (stream);
1808 Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
1811 [Test]
1812 [ExpectedException (typeof (InvalidDataContractException))]
1813 public void TestGenericEnumerableWithSpecialAddSerialization ()
1815 var collection = new GenericEnumerableWithSpecialAddContainer ();
1816 var serializer = new DataContractJsonSerializer (collection.GetType ());
1817 var stream = new MemoryStream ();
1818 serializer.WriteObject (stream, collection);
1821 [Test]
1822 [ExpectedException (typeof (InvalidDataContractException))]
1823 public void TestNonCollectionGetOnlyProperty ()
1825 var o = new NonCollectionGetOnlyContainer ();
1826 var serializer = new DataContractJsonSerializer (o.GetType ());
1827 var stream = new MemoryStream ();
1828 serializer.WriteObject (stream, o);
1831 // properly deserialize object with a polymorphic property (known derived type)
1832 [Test]
1833 public void Bug23058()
1835 string serializedObj = @"{""PolymorphicProperty"":{""__type"":""KnownDerivedType:#MonoTests.System.Runtime.Serialization.Json"",""BaseTypeProperty"":""Base"",""DerivedProperty"":""Derived 1""},""Name"":""Parent2""}";
1836 ParentType deserializedObj = Deserialize<ParentType> (serializedObj);
1838 Assert.AreEqual (deserializedObj.PolymorphicProperty.GetType ().FullName, "MonoTests.System.Runtime.Serialization.Json.KnownDerivedType");
1839 Assert.AreEqual (deserializedObj.PolymorphicProperty.BaseTypeProperty, "Base");
1840 Assert.AreEqual ((deserializedObj.PolymorphicProperty as KnownDerivedType).DerivedProperty, "Derived 1");
1841 Assert.AreEqual (deserializedObj.Name, "Parent2");
1844 // properly deserialize object with a polymorphic property (base type with __type hint)
1845 [Test]
1846 public void DeserializeBaseTypePropHint()
1848 string serializedObj = @"{""PolymorphicProperty"":{""__type"":""BaseType:#MonoTests.System.Runtime.Serialization.Json"",""BaseTypeProperty"":""Base""},""Name"":""Parent2""}";
1849 ParentType deserializedObj = Deserialize<ParentType> (serializedObj);
1851 Assert.AreEqual (deserializedObj.PolymorphicProperty.GetType ().FullName, "MonoTests.System.Runtime.Serialization.Json.BaseType");
1852 Assert.AreEqual (deserializedObj.PolymorphicProperty.BaseTypeProperty, "Base");
1855 // properly deserialize object with a polymorphic property (base type with __type hint)
1856 [Test]
1857 public void DeserializeBaseTypePropNoHint()
1859 string serializedObj = @"{""PolymorphicProperty"":{""BaseTypeProperty"":""Base""},""Name"":""Parent2""}";
1860 ParentType deserializedObj = Deserialize<ParentType> (serializedObj);
1862 Assert.AreEqual (deserializedObj.PolymorphicProperty.GetType ().FullName, "MonoTests.System.Runtime.Serialization.Json.BaseType");
1863 Assert.AreEqual (deserializedObj.PolymorphicProperty.BaseTypeProperty, "Base");
1866 // properly fail deserializing object with a polymorphic property (unknown derived type)
1867 [ExpectedException (typeof (SerializationException))]
1868 [Test]
1869 public void FailDeserializingUnknownTypeProp()
1871 string serializedObj = @"{""PolymorphicProperty"":{""__type"":""UnknownDerivedType:#MonoTests.System.Runtime.Serialization.Json"",""BaseTypeProperty"":""Base"",""DerivedProperty"":""Derived 1""},""Name"":""Parent2""}";
1872 ParentType deserializedObj = Deserialize<ParentType> (serializedObj);
1875 [Test]
1876 public void SubclassTest ()
1878 var knownTypes = new List<Type> { typeof(IntList) };
1879 var serializer = new DataContractJsonSerializer(typeof(ListOfNumbers), knownTypes);
1881 string json = "{\"Numbers\": [85]}";
1882 using (var stream = new MemoryStream(UTF8Encoding.Default.GetBytes(json)))
1884 var nums = (ListOfNumbers)serializer.ReadObject(stream);
1885 Assert.AreEqual (1, nums.Numbers.Count);
1888 [DataContract]
1889 public class ListOfNumbers
1891 [DataMember]
1892 public IntList Numbers;
1895 public class IntList : List<int>{}
1896 #endregion
1898 [Test]
1899 public void DefaultValueDeserialization ()
1901 // value type
1902 var person = new Person { name = "John" };
1903 using (var ms = new MemoryStream()) {
1904 var serializer = new DataContractJsonSerializer (typeof (Person), new DataContractJsonSerializerSettings {
1905 SerializeReadOnlyTypes = true,
1906 UseSimpleDictionaryFormat = true
1908 serializer.WriteObject (ms, person);
1911 // reference type
1912 var person2 = new PersonWithContact {
1913 name = "Jane",
1914 contact = new Contact { url = "localhost", email = "jane@localhost" } };
1915 using (var ms = new MemoryStream ()) {
1916 var serializer = new DataContractJsonSerializer (typeof (PersonWithContact), new DataContractJsonSerializerSettings {
1917 SerializeReadOnlyTypes = true,
1918 UseSimpleDictionaryFormat = true
1920 serializer.WriteObject (ms, person2);
1925 public class CharTest
1927 public char Foo;
1930 public class TestData
1932 public string Foo { get; set; }
1933 public string Bar { get; set; }
1934 internal string Baz { get; set; }
1937 public enum Colors {
1938 Red, Green, Blue
1941 [DataContract (Name = "_ColorsWithDC")]
1942 public enum ColorsWithDC {
1944 [EnumMember (Value = "_Red")]
1945 Red,
1946 [EnumMember]
1947 Green,
1948 Blue
1952 public enum ColorsEnumMemberNoDC {
1953 [EnumMember (Value = "_Red")]
1954 Red,
1955 [EnumMember]
1956 Green,
1957 Blue
1960 [DataContract]
1961 public class DCWithEnum {
1962 [DataMember (Name = "_colors")]
1963 public Colors colors;
1966 [DataContract]
1967 public class DCEmpty
1969 // serializer doesn't touch it.
1970 public string Foo = "TEST";
1973 [DataContract]
1974 public class DCSimple1
1976 [DataMember]
1977 public string Foo = "TEST";
1980 [DataContract]
1981 public class DCHasNonDC
1983 [DataMember]
1984 public NonDC Hoge= new NonDC ();
1987 public class NonDC
1989 public string Whee = "whee!";
1992 [DataContract]
1993 public class DCHasSerializable
1995 [DataMember]
1996 public SimpleSer1 Ser = new SimpleSer1 ();
1999 [DataContract (Name = "Foo")]
2000 public class DCWithName
2002 [DataMember (Name = "FooMember")]
2003 public string DMWithName = "value";
2006 [DataContract (Name = "")]
2007 public class DCWithEmptyName
2009 [DataMember]
2010 public string Foo;
2013 [DataContract (Name = null)]
2014 public class DCWithNullName
2016 [DataMember]
2017 public string Foo;
2020 [DataContract (Namespace = "")]
2021 public class DCWithEmptyNamespace
2023 [DataMember]
2024 public string Foo;
2027 [Serializable]
2028 public class SimpleSer1
2030 public string Doh = "doh!";
2033 public class Wrapper
2035 [DataContract]
2036 public class DCWrapped
2041 [DataContract]
2042 public class CollectionContainer
2044 Collection<string> items = new Collection<string> ();
2046 [DataMember]
2047 public Collection<string> Items {
2048 get { return items; }
2052 [CollectionDataContract]
2053 public class DataCollection<T> : Collection<T>
2057 [DataContract]
2058 public class DataCollectionContainer
2060 DataCollection<string> items = new DataCollection<string> ();
2062 [DataMember]
2063 public DataCollection<string> Items {
2064 get { return items; }
2068 [DataContract]
2069 class SerializeNonDCArrayType
2071 [DataMember]
2072 public NonDCItem [] IPAddresses = new NonDCItem [0];
2075 public class NonDCItem
2077 public byte [] Data { get; set; }
2080 [DataContract]
2081 public class VerifyObjectNameTestData
2083 [DataMember]
2084 string Member1 = "foo";
2087 [Serializable]
2088 public class KeyValueTestData {
2089 public List<KeyValuePair<string,string>> TestData = new List<KeyValuePair<string,string>>();
2092 [DataContract] // bug #586169
2093 public class Query
2095 [DataMember (Order=1)]
2096 public DateTime StartDate { get; set; }
2097 [DataMember (Order=2)]
2098 public DateTime EndDate { get; set; }
2101 public class ClassA {
2102 public ClassB B { get; set; }
2105 public class ClassB
2109 public class GSPlayerListErg
2111 public GSPlayerListErg ()
2113 Init ();
2116 void Init ()
2118 C = true;
2119 ServerTimeUTC = DateTime.SpecifyKind (DateTime.MinValue, DateTimeKind.Utc);
2122 [OnDeserializing]
2123 public void OnDeserializing (StreamingContext c)
2125 A = true;
2126 Init ();
2129 [OnDeserialized]
2130 void OnDeserialized (StreamingContext c)
2132 B = true;
2135 public static bool A, B, C;
2137 [DataMember (Name = "T")]
2138 public long CodedServerTimeUTC { get; set; }
2139 public DateTime ServerTimeUTC { get; set; }
2142 #region polymorphism test helper classes
2144 [DataContract]
2145 [KnownType (typeof (KnownDerivedType))]
2146 public class ParentType
2148 [DataMember]
2149 public string Name { get; set; }
2151 [DataMember]
2152 public BaseType PolymorphicProperty { get; set; }
2155 [DataContract]
2156 public class BaseType
2158 [DataMember]
2159 public string BaseTypeProperty { get; set; }
2162 [DataContract]
2163 public class KnownDerivedType : BaseType
2165 [DataMemberAttribute]
2166 public string DerivedProperty { get; set; }
2169 [DataContract]
2170 public class UnknownDerivedType : BaseType
2172 [DataMember]
2173 public string DerivedProperty { get; set; }
2176 #endregion
2179 [DataContract]
2180 class GlobalSample1
2185 public class MyDictionary<K, V> : System.Collections.Generic.IDictionary<K, V>
2187 Dictionary<K,V> dic = new Dictionary<K,V> ();
2189 public void Add (K key, V value)
2191 dic.Add (key, value);
2194 public bool ContainsKey (K key)
2196 return dic.ContainsKey (key);
2199 public ICollection<K> Keys {
2200 get { return dic.Keys; }
2203 public bool Remove (K key)
2205 return dic.Remove (key);
2208 public bool TryGetValue (K key, out V value)
2210 return dic.TryGetValue (key, out value);
2213 public ICollection<V> Values {
2214 get { return dic.Values; }
2217 public V this [K key] {
2218 get { return dic [key]; }
2219 set { dic [key] = value; }
2222 IEnumerator IEnumerable.GetEnumerator ()
2224 return dic.GetEnumerator ();
2227 ICollection<KeyValuePair<K,V>> Coll {
2228 get { return (ICollection<KeyValuePair<K,V>>) dic; }
2231 public void Add (KeyValuePair<K, V> item)
2233 Coll.Add (item);
2236 public void Clear ()
2238 dic.Clear ();
2241 public bool Contains (KeyValuePair<K, V> item)
2243 return Coll.Contains (item);
2246 public void CopyTo (KeyValuePair<K, V> [] array, int arrayIndex)
2248 Coll.CopyTo (array, arrayIndex);
2251 public int Count {
2252 get { return dic.Count; }
2255 public bool IsReadOnly {
2256 get { return Coll.IsReadOnly; }
2259 public bool Remove (KeyValuePair<K, V> item)
2261 return Coll.Remove (item);
2264 public IEnumerator<KeyValuePair<K, V>> GetEnumerator ()
2266 return Coll.GetEnumerator ();
2270 public class MyExplicitDictionary<K, V> : IDictionary<K, V> {
2272 Dictionary<K,V> dic = new Dictionary<K,V> ();
2274 public void Add (K key, V value)
2276 dic.Add (key, value);
2279 public bool ContainsKey (K key)
2281 return dic.ContainsKey (key);
2284 ICollection<K> IDictionary<K, V>.Keys {
2285 get { return dic.Keys; }
2288 public bool Remove (K key)
2290 return dic.Remove (key);
2293 public bool TryGetValue (K key, out V value)
2295 return dic.TryGetValue (key, out value);
2298 ICollection<V> IDictionary<K, V>.Values {
2299 get { return dic.Values; }
2302 public V this [K key] {
2303 get { return dic [key]; }
2304 set { dic [key] = value; }
2307 IEnumerator IEnumerable.GetEnumerator ()
2309 return dic.GetEnumerator ();
2312 ICollection<KeyValuePair<K,V>> Coll {
2313 get { return (ICollection<KeyValuePair<K,V>>) dic; }
2316 public void Add (KeyValuePair<K, V> item)
2318 Coll.Add (item);
2321 public void Clear ()
2323 dic.Clear ();
2326 public bool Contains (KeyValuePair<K, V> item)
2328 return Coll.Contains (item);
2331 public void CopyTo (KeyValuePair<K, V> [] array, int arrayIndex)
2333 Coll.CopyTo (array, arrayIndex);
2336 public int Count {
2337 get { return dic.Count; }
2340 public bool IsReadOnly {
2341 get { return Coll.IsReadOnly; }
2344 public bool Remove (KeyValuePair<K, V> item)
2346 return Coll.Remove (item);
2349 public IEnumerator<KeyValuePair<K, V>> GetEnumerator ()
2351 return Coll.GetEnumerator ();
2355 [DataContract]
2356 public class Bug13485Type
2358 [DataMember]
2359 public string Name { get; set; }
2361 [DataMember (Name = "Value")]
2362 private string Value { get; set; }
2364 public string GetValue { get { return this.Value; } }
2367 #region Test classes for Collection serialization
2369 [DataContract]
2370 public abstract class CollectionContainer <V>
2372 V items;
2374 [DataMember]
2375 public V Items
2377 get {
2378 if (items == null) items = Init ();
2379 return items;
2383 public CollectionContainer ()
2385 Init ();
2388 protected abstract V Init ();
2391 [DataContract]
2392 public class ArrayListContainer : CollectionContainer<ArrayList> {
2393 protected override ArrayList Init ()
2395 return new ArrayList { "banana", "apple" };
2399 [DataContract]
2400 public class BitArrayContainer : CollectionContainer<BitArray> {
2401 protected override BitArray Init ()
2403 return new BitArray (new [] { false, true });
2407 [DataContract]
2408 public class HashtableContainer : CollectionContainer<Hashtable> {
2409 protected override Hashtable Init ()
2411 var ht = new Hashtable ();
2412 ht.Add ("key1", "banana");
2413 ht.Add ("key2", "apple");
2414 return ht;
2418 [DataContract]
2419 public class QueueContainer : CollectionContainer<Queue> {
2420 protected override Queue Init ()
2422 var q = new Queue ();
2423 q.Enqueue ("banana");
2424 q.Enqueue ("apple");
2425 return q;
2429 [DataContract]
2430 public class SortedListContainer : CollectionContainer<SortedList> {
2431 protected override SortedList Init ()
2433 var l = new SortedList ();
2434 l.Add ("key1", "banana");
2435 l.Add ("key2", "apple");
2436 return l;
2440 [DataContract]
2441 public class StackContainer : CollectionContainer<Stack> {
2442 protected override Stack Init ()
2444 var s = new Stack ();
2445 s.Push ("banana");
2446 s.Push ("apple");
2447 return s;
2451 public class EnumerableWithAdd : IEnumerable
2453 private ArrayList items;
2455 public EnumerableWithAdd()
2457 items = new ArrayList();
2460 public IEnumerator GetEnumerator()
2462 return items.GetEnumerator();
2465 public void Add(object value)
2467 items.Add(value);
2470 public int Count
2472 get {
2473 return items.Count;
2478 public class EnumerableWithSpecialAdd : IEnumerable
2480 private ArrayList items;
2482 public EnumerableWithSpecialAdd()
2484 items = new ArrayList();
2487 public IEnumerator GetEnumerator()
2489 return items.GetEnumerator();
2492 public void Add(object value, int index)
2494 items.Add(value);
2497 public int Count
2501 return items.Count;
2506 [DataContract]
2507 public class EnumerableWithAddContainer : CollectionContainer<EnumerableWithAdd>
2509 protected override EnumerableWithAdd Init()
2511 var s = new EnumerableWithAdd();
2512 s.Add ("banana");
2513 s.Add ("apple");
2514 return s;
2518 [DataContract]
2519 public class EnumerableWithSpecialAddContainer : CollectionContainer<EnumerableWithSpecialAdd>
2521 protected override EnumerableWithSpecialAdd Init()
2523 var s = new EnumerableWithSpecialAdd();
2524 s.Add("banana", 0);
2525 s.Add("apple", 0);
2526 return s;
2530 [DataContract]
2531 public class GenericDictionaryContainer : CollectionContainer<Dictionary<string, string>> {
2532 protected override Dictionary<string, string> Init ()
2534 var d = new Dictionary<string, string> ();
2535 d.Add ("key1", "banana");
2536 d.Add ("key2", "apple");
2537 return d;
2541 [DataContract]
2542 public class GenericHashSetContainer : CollectionContainer<HashSet<string>> {
2543 protected override HashSet<string> Init ()
2545 return new HashSet<string> { "banana", "apple" };
2549 [DataContract]
2550 public class GenericLinkedListContainer : CollectionContainer<LinkedList<string>> {
2551 protected override LinkedList<string> Init ()
2553 var l = new LinkedList<string> ();
2554 l.AddFirst ("apple");
2555 l.AddFirst ("banana");
2556 return l;
2560 [DataContract]
2561 public class GenericListContainer : CollectionContainer<List<string>> {
2562 protected override List<string> Init ()
2564 return new List<string> { "banana", "apple" };
2568 [DataContract]
2569 public class GenericQueueContainer : CollectionContainer<Queue<string>> {
2570 protected override Queue<string> Init ()
2572 var q = new Queue<string> ();
2573 q.Enqueue ("banana");
2574 q.Enqueue ("apple" );
2575 return q;
2579 [DataContract]
2580 public class GenericSortedDictionaryContainer : CollectionContainer<SortedDictionary<string, string>> {
2581 protected override SortedDictionary<string, string> Init ()
2583 var d = new SortedDictionary<string, string> ();
2584 d.Add ("key1", "banana");
2585 d.Add ("key2", "apple");
2586 return d;
2590 [DataContract]
2591 public class GenericSortedListContainer : CollectionContainer<SortedList<string, string>> {
2592 protected override SortedList<string, string> Init ()
2594 var d = new SortedList<string, string> ();
2595 d.Add ("key1", "banana");
2596 d.Add ("key2", "apple");
2597 return d;
2601 [DataContract]
2602 public class GenericStackContainer : CollectionContainer<Stack<string>> {
2603 protected override Stack<string> Init ()
2605 var s = new Stack<string> ();
2606 s.Push ("banana");
2607 s.Push ("apple" );
2608 return s;
2612 public class GenericEnumerableWithAdd : IEnumerable<string>
2614 private List<string> items;
2616 public GenericEnumerableWithAdd()
2618 items = new List<string>();
2621 IEnumerator IEnumerable.GetEnumerator()
2623 return items.GetEnumerator ();
2626 public IEnumerator<string> GetEnumerator()
2628 return items.GetEnumerator ();
2631 public void Add(string value)
2633 items.Add(value);
2636 public int Count
2638 get {
2639 return items.Count;
2644 public class GenericEnumerableWithSpecialAdd : IEnumerable<string>
2646 private List<string> items;
2648 public GenericEnumerableWithSpecialAdd()
2650 items = new List<string>();
2653 IEnumerator IEnumerable.GetEnumerator()
2655 return items.GetEnumerator ();
2658 public IEnumerator<string> GetEnumerator()
2660 return items.GetEnumerator ();
2663 public void Add(string value, int index)
2665 items.Add(value);
2668 public int Count
2672 return items.Count;
2677 [DataContract]
2678 public class GenericEnumerableWithAddContainer : CollectionContainer<GenericEnumerableWithAdd>
2680 protected override GenericEnumerableWithAdd Init()
2682 var s = new GenericEnumerableWithAdd();
2683 s.Add ("banana");
2684 s.Add ("apple");
2685 return s;
2689 [DataContract]
2690 public class GenericEnumerableWithSpecialAddContainer : CollectionContainer<GenericEnumerableWithSpecialAdd>
2692 protected override GenericEnumerableWithSpecialAdd Init()
2694 var s = new GenericEnumerableWithSpecialAdd();
2695 s.Add("banana", 0);
2696 s.Add("apple", 0);
2697 return s;
2701 [DataContract]
2702 public class NonCollectionGetOnlyContainer
2704 string _test = "my string";
2706 [DataMember]
2707 public string MyString {
2708 get {
2709 return _test;
2714 #endregion
2716 #region DefaultValueDeserialization
2717 [DataContract]
2718 public class Person
2720 [DataMember(EmitDefaultValue = false)]
2721 public string name { get; set; }
2724 [DataContract]
2725 public class PersonWithContact
2727 [DataMember(EmitDefaultValue = false)]
2728 public string name { get; set; }
2730 [DataMember(EmitDefaultValue = false)]
2731 public Contact contact { get; set; }
2734 [DataContract]
2735 public class Contact
2737 [DataMember(EmitDefaultValue = false)]
2738 public string url { get; set; }
2740 [DataMember(EmitDefaultValue = false)]
2741 public string email{ get; set; }
2743 #endregion