IDictionary`2 serialization support was missing in DataContractJsonSerializer.
[mono-project.git] / mcs / class / System.ServiceModel.Web / Test / System.Runtime.Serialization.Json / DataContractJsonSerializerTest.cs
blob3debe78edb1a3662293be5c3ea7014cff279c2e0
1 //
2 // DataContractJsonSerializerTest.cs
3 //
4 // Author:
5 // Atsushi Enomoto <atsushi@ximian.com>
6 // Ankit Jain <JAnkit@novell.com>
7 //
8 // Copyright (C) 2005-2007 Novell, Inc. http://www.novell.com
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 //
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 //
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 // This test code contains tests for DataContractJsonSerializer, which is
33 // imported from DataContractSerializerTest.cs.
36 using System;
37 using System.Collections;
38 using System.Collections.Generic;
39 using System.Collections.ObjectModel;
40 using System.IO;
41 using System.Net;
42 using System.Runtime.Serialization;
43 using System.Runtime.Serialization.Json;
44 using System.Text;
45 using System.Xml;
46 using NUnit.Framework;
48 namespace MonoTests.System.Runtime.Serialization.Json
50 [TestFixture]
51 public class DataContractJsonSerializerTest
53 static readonly XmlWriterSettings settings;
55 static DataContractJsonSerializerTest ()
57 settings = new XmlWriterSettings ();
58 settings.OmitXmlDeclaration = true;
61 [DataContract]
62 class Sample1
64 [DataMember]
65 public string Member1;
68 [Test]
69 [ExpectedException (typeof (ArgumentNullException))]
70 public void ConstructorTypeNull ()
72 new DataContractJsonSerializer (null);
75 [Test]
76 public void ConstructorKnownTypesNull ()
78 // null knownTypes is allowed.
79 new DataContractJsonSerializer (typeof (Sample1), (IEnumerable<Type>) null);
80 new DataContractJsonSerializer (typeof (Sample1), "Foo", null);
83 [Test]
84 [ExpectedException (typeof (ArgumentNullException))]
85 public void ConstructorNameNull ()
87 new DataContractJsonSerializer (typeof (Sample1), (string) null);
90 [Test]
91 [ExpectedException (typeof (ArgumentOutOfRangeException))]
92 public void ConstructorNegativeMaxObjects ()
94 new DataContractJsonSerializer (typeof (Sample1), "Sample1",
95 null, -1, false, null, false);
98 [Test]
99 public void ConstructorMisc ()
101 new DataContractJsonSerializer (typeof (GlobalSample1)).WriteObject (new MemoryStream (), new GlobalSample1 ());
104 [Test]
105 public void WriteObjectContent ()
107 StringWriter sw = new StringWriter ();
108 using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
109 DataContractJsonSerializer ser =
110 new DataContractJsonSerializer (typeof (string));
111 xw.WriteStartElement ("my-element");
112 ser.WriteObjectContent (xw, "TEST STRING");
113 xw.WriteEndElement ();
115 Assert.AreEqual ("<my-element>TEST STRING</my-element>",
116 sw.ToString ());
119 // int
121 [Test]
122 public void SerializeIntXml ()
124 StringWriter sw = new StringWriter ();
125 SerializeInt (XmlWriter.Create (sw, settings));
126 Assert.AreEqual (
127 @"<root type=""number"">1</root>",
128 sw.ToString ());
131 [Test]
132 public void SerializeIntJson ()
134 MemoryStream ms = new MemoryStream ();
135 SerializeInt (JsonReaderWriterFactory.CreateJsonWriter (ms));
136 Assert.AreEqual (
137 "1",
138 Encoding.UTF8.GetString (ms.ToArray ()));
141 void SerializeInt (XmlWriter writer)
143 DataContractJsonSerializer ser =
144 new DataContractJsonSerializer (typeof (int));
145 using (XmlWriter w = writer) {
146 ser.WriteObject (w, 1);
150 // int, with rootName
152 [Test]
153 public void SerializeIntXmlWithRootName ()
155 StringWriter sw = new StringWriter ();
156 SerializeIntWithRootName (XmlWriter.Create (sw, settings));
157 Assert.AreEqual (
158 @"<myroot type=""number"">1</myroot>",
159 sw.ToString ());
162 [Test]
163 // since JsonWriter supports only "root" as the root name, using
164 // XmlWriter from JsonReaderWriterFactory will always fail with
165 // an explicit rootName.
166 [ExpectedException (typeof (SerializationException))]
167 public void SerializeIntJsonWithRootName ()
169 MemoryStream ms = new MemoryStream ();
170 SerializeIntWithRootName (JsonReaderWriterFactory.CreateJsonWriter (ms));
171 Assert.AreEqual (
172 "1",
173 Encoding.UTF8.GetString (ms.ToArray ()));
176 void SerializeIntWithRootName (XmlWriter writer)
178 DataContractJsonSerializer ser =
179 new DataContractJsonSerializer (typeof (int), "myroot");
180 using (XmlWriter w = writer) {
181 ser.WriteObject (w, 1);
185 // pass typeof(DCEmpty), serialize int
187 [Test]
188 public void SerializeIntForDCEmptyXml ()
190 StringWriter sw = new StringWriter ();
191 SerializeIntForDCEmpty (XmlWriter.Create (sw, settings));
192 Assert.AreEqual (
193 @"<root type=""number"">1</root>",
194 sw.ToString ());
197 [Test]
198 public void SerializeIntForDCEmptyJson ()
200 MemoryStream ms = new MemoryStream ();
201 SerializeIntForDCEmpty (JsonReaderWriterFactory.CreateJsonWriter (ms));
202 Assert.AreEqual (
203 "1",
204 Encoding.UTF8.GetString (ms.ToArray ()));
207 void SerializeIntForDCEmpty (XmlWriter writer)
209 DataContractJsonSerializer ser =
210 new DataContractJsonSerializer (typeof (DCEmpty));
211 using (XmlWriter w = writer) {
212 ser.WriteObject (w, 1);
216 // DCEmpty
218 [Test]
219 public void SerializeEmptyClassXml ()
221 StringWriter sw = new StringWriter ();
222 SerializeEmptyClass (XmlWriter.Create (sw, settings));
223 Assert.AreEqual (
224 @"<root type=""object"" />",
225 sw.ToString ());
228 [Test]
229 public void SerializeEmptyClassJson ()
231 MemoryStream ms = new MemoryStream ();
232 SerializeEmptyClass (JsonReaderWriterFactory.CreateJsonWriter (ms));
233 Assert.AreEqual (
234 "{}",
235 Encoding.UTF8.GetString (ms.ToArray ()));
238 void SerializeEmptyClass (XmlWriter writer)
240 DataContractJsonSerializer ser =
241 new DataContractJsonSerializer (typeof (DCEmpty));
242 using (XmlWriter w = writer) {
243 ser.WriteObject (w, new DCEmpty ());
247 // string (primitive)
249 [Test]
250 public void SerializePrimitiveStringXml ()
252 StringWriter sw = new StringWriter ();
253 SerializePrimitiveString (XmlWriter.Create (sw, settings));
254 Assert.AreEqual (
255 "<root>TEST</root>",
256 sw.ToString ());
259 [Test]
260 public void SerializePrimitiveStringJson ()
262 MemoryStream ms = new MemoryStream ();
263 SerializePrimitiveString (JsonReaderWriterFactory.CreateJsonWriter (ms));
264 Assert.AreEqual (
265 @"""TEST""",
266 Encoding.UTF8.GetString (ms.ToArray ()));
269 void SerializePrimitiveString (XmlWriter writer)
271 XmlObjectSerializer ser =
272 new DataContractJsonSerializer (typeof (string));
273 using (XmlWriter w = writer) {
274 ser.WriteObject (w, "TEST");
278 // QName (primitive but ...)
280 [Test]
281 public void SerializePrimitiveQNameXml ()
283 StringWriter sw = new StringWriter ();
284 SerializePrimitiveQName (XmlWriter.Create (sw, settings));
285 Assert.AreEqual (
286 "<root>foo:urn:foo</root>",
287 sw.ToString ());
290 [Test]
291 public void SerializePrimitiveQNameJson ()
293 MemoryStream ms = new MemoryStream ();
294 SerializePrimitiveQName (JsonReaderWriterFactory.CreateJsonWriter (ms));
295 Assert.AreEqual (
296 @"""foo:urn:foo""",
297 Encoding.UTF8.GetString (ms.ToArray ()));
300 void SerializePrimitiveQName (XmlWriter writer)
302 XmlObjectSerializer ser =
303 new DataContractJsonSerializer (typeof (XmlQualifiedName));
304 using (XmlWriter w = writer) {
305 ser.WriteObject (w, new XmlQualifiedName ("foo", "urn:foo"));
309 // DBNull (primitive)
311 [Test]
312 public void SerializeDBNullXml ()
314 StringWriter sw = new StringWriter ();
315 SerializeDBNull (XmlWriter.Create (sw, settings));
316 Assert.AreEqual (
317 @"<root type=""object"" />",
318 sw.ToString ());
321 [Test]
322 public void SerializeDBNullJson ()
324 MemoryStream ms = new MemoryStream ();
325 SerializeDBNull (JsonReaderWriterFactory.CreateJsonWriter (ms));
326 Assert.AreEqual (
327 "{}",
328 Encoding.UTF8.GetString (ms.ToArray ()));
331 void SerializeDBNull (XmlWriter writer)
333 DataContractJsonSerializer ser =
334 new DataContractJsonSerializer (typeof (DBNull));
335 using (XmlWriter w = writer) {
336 ser.WriteObject (w, DBNull.Value);
340 // DCSimple1
342 [Test]
343 public void SerializeSimpleClass1Xml ()
345 StringWriter sw = new StringWriter ();
346 SerializeSimpleClass1 (XmlWriter.Create (sw, settings));
347 Assert.AreEqual (
348 @"<root type=""object""><Foo>TEST</Foo></root>",
349 sw.ToString ());
352 [Test]
353 public void SerializeSimpleClass1Json ()
355 MemoryStream ms = new MemoryStream ();
356 SerializeSimpleClass1 (JsonReaderWriterFactory.CreateJsonWriter (ms));
357 Assert.AreEqual (
358 @"{""Foo"":""TEST""}",
359 Encoding.UTF8.GetString (ms.ToArray ()));
362 void SerializeSimpleClass1 (XmlWriter writer)
364 DataContractJsonSerializer ser =
365 new DataContractJsonSerializer (typeof (DCSimple1));
366 using (XmlWriter w = writer) {
367 ser.WriteObject (w, new DCSimple1 ());
371 // NonDC
373 [Test]
374 // NonDC is not a DataContract type.
375 public void SerializeNonDCOnlyCtor ()
377 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (NonDC));
380 [Test]
381 //[ExpectedException (typeof (InvalidDataContractException))]
382 // NonDC is not a DataContract type.
383 // UPDATE: non-DataContract types are became valid in RTM.
384 public void SerializeNonDC ()
386 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (NonDC));
387 using (XmlWriter w = XmlWriter.Create (TextWriter.Null, settings)) {
388 ser.WriteObject (w, new NonDC ());
392 // DCHasNonDC
394 [Test]
395 //[ExpectedException (typeof (InvalidDataContractException))]
396 // DCHasNonDC itself is a DataContract type whose field is
397 // marked as DataMember but its type is not DataContract.
398 // UPDATE: non-DataContract types are became valid in RTM.
399 public void SerializeDCHasNonDC ()
401 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCHasNonDC));
402 using (XmlWriter w = XmlWriter.Create (TextWriter.Null, settings)) {
403 ser.WriteObject (w, new DCHasNonDC ());
407 // DCHasSerializable
409 [Test]
410 public void SerializeSimpleSerializable1Xml ()
412 StringWriter sw = new StringWriter ();
413 SerializeSimpleSerializable1 (XmlWriter.Create (sw, settings));
414 Assert.AreEqual (
415 @"<root type=""object""><Ser type=""object""><Doh>doh!</Doh></Ser></root>",
416 sw.ToString ());
419 [Test]
420 public void SerializeSimpleSerializable1Json ()
422 MemoryStream ms = new MemoryStream ();
423 SerializeSimpleSerializable1 (JsonReaderWriterFactory.CreateJsonWriter (ms));
424 Assert.AreEqual (
425 @"{""Ser"":{""Doh"":""doh!""}}",
426 Encoding.UTF8.GetString (ms.ToArray ()));
429 // DCHasSerializable itself is DataContract and has a field
430 // whose type is not contract but serializable.
431 void SerializeSimpleSerializable1 (XmlWriter writer)
433 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCHasSerializable));
434 using (XmlWriter w = writer) {
435 ser.WriteObject (w, new DCHasSerializable ());
439 [Test]
440 public void SerializeDCWithNameXml ()
442 StringWriter sw = new StringWriter ();
443 SerializeDCWithName (XmlWriter.Create (sw, settings));
444 Assert.AreEqual (
445 @"<root type=""object""><FooMember>value</FooMember></root>",
446 sw.ToString ());
449 [Test]
450 public void SerializeDCWithNameJson ()
452 MemoryStream ms = new MemoryStream ();
453 SerializeDCWithName (JsonReaderWriterFactory.CreateJsonWriter (ms));
454 Assert.AreEqual (
455 @"{""FooMember"":""value""}",
456 Encoding.UTF8.GetString (ms.ToArray ()));
459 void SerializeDCWithName (XmlWriter writer)
461 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithName));
462 using (XmlWriter w = writer) {
463 ser.WriteObject (w, new DCWithName ());
467 [Test]
468 public void SerializeDCWithEmptyName1 ()
470 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEmptyName));
471 StringWriter sw = new StringWriter ();
472 DCWithEmptyName dc = new DCWithEmptyName ();
473 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
474 try {
475 ser.WriteObject (w, dc);
476 } catch (InvalidDataContractException) {
477 return;
480 Assert.Fail ("Expected InvalidDataContractException");
483 [Test]
484 public void SerializeDCWithEmptyName2 ()
486 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithName));
487 StringWriter sw = new StringWriter ();
489 /* DataContractAttribute.Name == "", not valid */
490 DCWithEmptyName dc = new DCWithEmptyName ();
491 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
492 try {
493 ser.WriteObject (w, dc);
494 } catch (InvalidDataContractException) {
495 return;
498 Assert.Fail ("Expected InvalidDataContractException");
501 [Test]
502 [Category("NotWorking")]
503 public void SerializeDCWithNullName ()
505 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithNullName));
506 StringWriter sw = new StringWriter ();
507 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
508 try {
509 /* DataContractAttribute.Name == "", not valid */
510 ser.WriteObject (w, new DCWithNullName ());
511 } catch (InvalidDataContractException) {
512 return;
515 Assert.Fail ("Expected InvalidDataContractException");
518 [Test]
519 public void SerializeDCWithEmptyNamespace1 ()
521 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEmptyNamespace));
522 StringWriter sw = new StringWriter ();
523 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
524 ser.WriteObject (w, new DCWithEmptyNamespace ());
528 [Test]
529 public void SerializeWrappedClassXml ()
531 StringWriter sw = new StringWriter ();
532 SerializeWrappedClass (XmlWriter.Create (sw, settings));
533 Assert.AreEqual (
534 @"<root type=""object"" />",
535 sw.ToString ());
538 [Test]
539 public void SerializeWrappedClassJson ()
541 MemoryStream ms = new MemoryStream ();
542 SerializeWrappedClass (JsonReaderWriterFactory.CreateJsonWriter (ms));
543 Assert.AreEqual (
544 "{}",
545 Encoding.UTF8.GetString (ms.ToArray ()));
548 void SerializeWrappedClass (XmlWriter writer)
550 DataContractJsonSerializer ser =
551 new DataContractJsonSerializer (typeof (Wrapper.DCWrapped));
552 using (XmlWriter w = writer) {
553 ser.WriteObject (w, new Wrapper.DCWrapped ());
557 // CollectionContainer : Items must have a setter. (but became valid in RTM).
558 [Test]
559 public void SerializeReadOnlyCollectionMember ()
561 DataContractJsonSerializer ser =
562 new DataContractJsonSerializer (typeof (CollectionContainer));
563 StringWriter sw = new StringWriter ();
564 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
565 ser.WriteObject (w, null);
569 // DataCollectionContainer : Items must have a setter. (but became valid in RTM).
570 [Test]
571 public void SerializeReadOnlyDataCollectionMember ()
573 DataContractJsonSerializer ser =
574 new DataContractJsonSerializer (typeof (DataCollectionContainer));
575 StringWriter sw = new StringWriter ();
576 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
577 ser.WriteObject (w, null);
581 [Test]
582 [Ignore ("https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=409970")]
583 [ExpectedException (typeof (SerializationException))]
584 public void DeserializeReadOnlyDataCollection_NullCollection ()
586 DataContractJsonSerializer ser =
587 new DataContractJsonSerializer (typeof (CollectionContainer));
588 StringWriter sw = new StringWriter ();
589 var c = new CollectionContainer ();
590 c.Items.Add ("foo");
591 c.Items.Add ("bar");
592 using (XmlWriter w = XmlWriter.Create (sw, settings))
593 ser.WriteObject (w, c);
594 // CollectionContainer.Items is null, so it cannot deserialize non-null collection.
595 using (XmlReader r = XmlReader.Create (new StringReader (sw.ToString ())))
596 c = (CollectionContainer) ser.ReadObject (r);
599 [Test]
600 public void SerializeGuidXml ()
602 StringWriter sw = new StringWriter ();
603 SerializeGuid (XmlWriter.Create (sw, settings));
604 Assert.AreEqual (
605 @"<root>00000000-0000-0000-0000-000000000000</root>",
606 sw.ToString ());
609 [Test]
610 public void SerializeGuidJson ()
612 MemoryStream ms = new MemoryStream ();
613 SerializeGuid (JsonReaderWriterFactory.CreateJsonWriter (ms));
614 Assert.AreEqual (
615 @"""00000000-0000-0000-0000-000000000000""",
616 Encoding.UTF8.GetString (ms.ToArray ()));
619 void SerializeGuid (XmlWriter writer)
621 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Guid));
622 using (XmlWriter w = writer) {
623 ser.WriteObject (w, Guid.Empty);
627 [Test]
628 public void SerializeEnumXml ()
630 StringWriter sw = new StringWriter ();
631 SerializeEnum (XmlWriter.Create (sw, settings));
632 Assert.AreEqual (
633 @"<root type=""number"">0</root>",
634 sw.ToString ());
637 [Test]
638 public void SerializeEnumJson ()
640 MemoryStream ms = new MemoryStream ();
641 SerializeEnum (JsonReaderWriterFactory.CreateJsonWriter (ms));
642 Assert.AreEqual (
643 "0",
644 Encoding.UTF8.GetString (ms.ToArray ()));
647 void SerializeEnum (XmlWriter writer)
649 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Colors));
650 using (XmlWriter w = writer) {
651 ser.WriteObject (w, new Colors ());
655 [Test]
656 public void SerializeEnum2Xml ()
658 StringWriter sw = new StringWriter ();
659 SerializeEnum2 (XmlWriter.Create (sw, settings));
660 Assert.AreEqual (
661 @"<root type=""number"">0</root>",
662 sw.ToString ());
665 [Test]
666 public void SerializeEnum2Json ()
668 MemoryStream ms = new MemoryStream ();
669 SerializeEnum2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
670 Assert.AreEqual (
671 "0",
672 Encoding.UTF8.GetString (ms.ToArray ()));
675 void SerializeEnum2 (XmlWriter writer)
677 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Colors));
678 using (XmlWriter w = writer) {
679 ser.WriteObject (w, 0);
683 [Test] // so, DataContract does not affect here.
684 public void SerializeEnumWithDCXml ()
686 StringWriter sw = new StringWriter ();
687 SerializeEnumWithDC (XmlWriter.Create (sw, settings));
688 Assert.AreEqual (
689 @"<root type=""number"">0</root>",
690 sw.ToString ());
693 [Test]
694 public void SerializeEnumWithDCJson ()
696 MemoryStream ms = new MemoryStream ();
697 SerializeEnumWithDC (JsonReaderWriterFactory.CreateJsonWriter (ms));
698 Assert.AreEqual (
699 "0",
700 Encoding.UTF8.GetString (ms.ToArray ()));
703 void SerializeEnumWithDC (XmlWriter writer)
705 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
706 using (XmlWriter w = writer) {
707 ser.WriteObject (w, new ColorsWithDC ());
711 [Test]
712 public void SerializeEnumWithNoDCXml ()
714 StringWriter sw = new StringWriter ();
715 SerializeEnumWithNoDC (XmlWriter.Create (sw, settings));
716 Assert.AreEqual (
717 @"<root type=""number"">0</root>",
718 sw.ToString ());
721 [Test]
722 public void SerializeEnumWithNoDCJson ()
724 MemoryStream ms = new MemoryStream ();
725 SerializeEnumWithNoDC (JsonReaderWriterFactory.CreateJsonWriter (ms));
726 Assert.AreEqual (
727 "0",
728 Encoding.UTF8.GetString (ms.ToArray ()));
731 void SerializeEnumWithNoDC (XmlWriter writer)
733 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsEnumMemberNoDC));
734 using (XmlWriter w = writer) {
735 ser.WriteObject (w, new ColorsEnumMemberNoDC ());
739 [Test]
740 public void SerializeEnumWithDC2Xml ()
742 StringWriter sw = new StringWriter ();
743 SerializeEnumWithDC2 (XmlWriter.Create (sw, settings));
744 Assert.AreEqual (
745 @"<root type=""number"">3</root>",
746 sw.ToString ());
749 [Test]
750 public void SerializeEnumWithDC2Json ()
752 MemoryStream ms = new MemoryStream ();
753 SerializeEnumWithDC2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
754 Assert.AreEqual (
755 "3",
756 Encoding.UTF8.GetString (ms.ToArray ()));
759 void SerializeEnumWithDC2 (XmlWriter writer)
761 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
762 using (XmlWriter w = writer) {
763 ser.WriteObject (w, 3);
768 [Test]
769 [ExpectedException (typeof (SerializationException))]
770 public void SerializeEnumWithDCInvalid ()
772 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
773 StringWriter sw = new StringWriter ();
774 ColorsWithDC cdc = ColorsWithDC.Blue;
775 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
776 ser.WriteObject (w, cdc);
781 [Test]
782 public void SerializeDCWithEnumXml ()
784 StringWriter sw = new StringWriter ();
785 SerializeDCWithEnum (XmlWriter.Create (sw, settings));
786 Assert.AreEqual (
787 @"<root type=""object""><_colors type=""number"">0</_colors></root>",
788 sw.ToString ());
791 [Test]
792 public void SerializeDCWithEnumJson ()
794 MemoryStream ms = new MemoryStream ();
795 SerializeDCWithEnum (JsonReaderWriterFactory.CreateJsonWriter (ms));
796 Assert.AreEqual (
797 @"{""_colors"":0}",
798 Encoding.UTF8.GetString (ms.ToArray ()));
801 void SerializeDCWithEnum (XmlWriter writer)
803 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEnum));
804 using (XmlWriter w = writer) {
805 ser.WriteObject (w, new DCWithEnum ());
809 [Test]
810 public void SerializerDCArrayXml ()
812 StringWriter sw = new StringWriter ();
813 SerializerDCArray (XmlWriter.Create (sw, settings));
814 Assert.AreEqual (
815 @"<root type=""array""><item type=""object""><_colors type=""number"">0</_colors></item><item type=""object""><_colors type=""number"">1</_colors></item></root>",
816 sw.ToString ());
819 [Test]
820 public void SerializerDCArrayJson ()
822 MemoryStream ms = new MemoryStream ();
823 SerializerDCArray (JsonReaderWriterFactory.CreateJsonWriter (ms));
824 Assert.AreEqual (
825 @"[{""_colors"":0},{""_colors"":1}]",
826 Encoding.UTF8.GetString (ms.ToArray ()));
829 void SerializerDCArray (XmlWriter writer)
831 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEnum []));
832 DCWithEnum [] arr = new DCWithEnum [2];
833 arr [0] = new DCWithEnum (); arr [0].colors = Colors.Red;
834 arr [1] = new DCWithEnum (); arr [1].colors = Colors.Green;
835 using (XmlWriter w = writer) {
836 ser.WriteObject (w, arr);
840 [Test]
841 public void SerializerDCArray2Xml ()
843 StringWriter sw = new StringWriter ();
844 SerializerDCArray2 (XmlWriter.Create (sw, settings));
845 Assert.AreEqual (
846 @"<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>",
847 sw.ToString ());
850 [Test]
851 public void SerializerDCArray2Json ()
853 MemoryStream ms = new MemoryStream ();
854 SerializerDCArray2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
855 Assert.AreEqual (
856 @"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0},{""__type"":""DCSimple1:#MonoTests.System.Runtime.Serialization.Json"",""Foo"":""hello""}]",
857 Encoding.UTF8.GetString (ms.ToArray ()));
860 void SerializerDCArray2 (XmlWriter writer)
862 List<Type> known = new List<Type> ();
863 known.Add (typeof (DCWithEnum));
864 known.Add (typeof (DCSimple1));
865 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (object []), known);
866 object [] arr = new object [2];
867 arr [0] = new DCWithEnum (); ((DCWithEnum)arr [0]).colors = Colors.Red;
868 arr [1] = new DCSimple1 (); ((DCSimple1) arr [1]).Foo = "hello";
870 using (XmlWriter w = writer) {
871 ser.WriteObject (w, arr);
875 [Test]
876 public void SerializerDCArray3Xml ()
878 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (int []));
879 StringWriter sw = new StringWriter ();
880 int [] arr = new int [2];
881 arr [0] = 1; arr [1] = 2;
883 using (XmlWriter w = XmlWriter.Create (sw, settings)) {
884 ser.WriteObject (w, arr);
887 Assert.AreEqual (
888 @"<root type=""array""><item type=""number"">1</item><item type=""number"">2</item></root>",
889 sw.ToString ());
892 [Test]
893 public void SerializerDCArray3Json ()
895 MemoryStream ms = new MemoryStream ();
896 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (int []));
897 int [] arr = new int [2];
898 arr [0] = 1; arr [1] = 2;
900 using (XmlWriter w = JsonReaderWriterFactory.CreateJsonWriter (ms)) {
901 ser.WriteObject (w, arr);
904 Assert.AreEqual (
905 @"[1,2]",
906 Encoding.UTF8.GetString (ms.ToArray ()));
909 [Test]
910 // ... so, non-JSON XmlWriter is still accepted.
911 public void SerializeNonDCArrayXml ()
913 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
914 StringWriter sw = new StringWriter ();
915 using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
916 ser.WriteObject (xw, new SerializeNonDCArrayType ());
918 Assert.AreEqual (@"<root type=""object""><IPAddresses type=""array"" /></root>",
919 sw.ToString ());
922 [Test]
923 public void SerializeNonDCArrayJson ()
925 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
926 MemoryStream ms = new MemoryStream ();
927 using (XmlWriter xw = JsonReaderWriterFactory.CreateJsonWriter (ms)) {
928 ser.WriteObject (xw, new SerializeNonDCArrayType ());
930 Assert.AreEqual (@"{""IPAddresses"":[]}",
931 Encoding.UTF8.GetString (ms.ToArray ()));
934 [Test]
935 public void SerializeNonDCArrayItems ()
937 DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
938 StringWriter sw = new StringWriter ();
939 using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
940 SerializeNonDCArrayType obj = new SerializeNonDCArrayType ();
941 obj.IPAddresses = new NonDCItem [] {new NonDCItem () { Data = new byte [] {1, 2, 3, 4} } };
942 ser.WriteObject (xw, obj);
945 XmlDocument doc = new XmlDocument ();
946 doc.LoadXml (sw.ToString ());
947 XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
948 nsmgr.AddNamespace ("s", "http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization");
949 nsmgr.AddNamespace ("n", "http://schemas.datacontract.org/2004/07/System.Net");
950 nsmgr.AddNamespace ("a", "http://schemas.microsoft.com/2003/10/Serialization/Arrays");
952 Assert.AreEqual (1, doc.SelectNodes ("/root/IPAddresses/item", nsmgr).Count, "#1");
953 XmlElement el = doc.SelectSingleNode ("/root/IPAddresses/item/Data", nsmgr) as XmlElement;
954 Assert.IsNotNull (el, "#3");
955 Assert.AreEqual (4, el.SelectNodes ("item", nsmgr).Count, "#4");
958 [Test]
959 public void MaxItemsInObjectGraph1 ()
961 // object count == maximum
962 DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCEmpty), null, 1, false, null, false);
963 s.WriteObject (XmlWriter.Create (TextWriter.Null), new DCEmpty ());
966 [Test]
967 [ExpectedException (typeof (SerializationException))]
968 public void MaxItemsInObjectGraph2 ()
970 // object count > maximum
971 DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCSimple1), null, 1, false, null, false);
972 s.WriteObject (XmlWriter.Create (TextWriter.Null), new DCSimple1 ());
975 [Test]
976 public void DeserializeString ()
978 Assert.AreEqual ("ABC", Deserialize ("\"ABC\"", typeof (string)));
981 [Test]
982 public void DeserializeInt ()
984 Assert.AreEqual (5, Deserialize ("5", typeof (int)));
987 [Test]
988 public void DeserializeArray ()
990 int [] ret = (int []) Deserialize ("[5,6,7]", typeof (int []));
991 Assert.AreEqual (5, ret [0], "#1");
992 Assert.AreEqual (6, ret [1], "#2");
993 Assert.AreEqual (7, ret [2], "#3");
996 [Test]
997 public void DeserializeArrayUntyped ()
999 object [] ret = (object []) Deserialize ("[5,6,7]", typeof (object []));
1000 Assert.AreEqual (5, ret [0], "#1");
1001 Assert.AreEqual (6, ret [1], "#2");
1002 Assert.AreEqual (7, ret [2], "#3");
1005 [Test]
1006 public void DeserializeMixedArray ()
1008 object [] ret = (object []) Deserialize ("[5,\"6\",false]", typeof (object []));
1009 Assert.AreEqual (5, ret [0], "#1");
1010 Assert.AreEqual ("6", ret [1], "#2");
1011 Assert.AreEqual (false, ret [2], "#3");
1014 [Test]
1015 [ExpectedException (typeof (SerializationException))]
1016 public void DeserializeEmptyAsString ()
1018 // it somehow expects "root" which should have been already consumed.
1019 Deserialize ("", typeof (string));
1022 [Test]
1023 [ExpectedException (typeof (SerializationException))]
1024 public void DeserializeEmptyAsInt ()
1026 // it somehow expects "root" which should have been already consumed.
1027 Deserialize ("", typeof (int));
1030 [Test]
1031 [ExpectedException (typeof (SerializationException))]
1032 public void DeserializeEmptyAsDBNull ()
1034 // it somehow expects "root" which should have been already consumed.
1035 Deserialize ("", typeof (DBNull));
1038 [Test]
1039 public void DeserializeEmptyObjectAsString ()
1041 // looks like it is converted to ""
1042 Assert.AreEqual (String.Empty, Deserialize ("{}", typeof (string)));
1045 [Test]
1046 [ExpectedException (typeof (SerializationException))]
1047 public void DeserializeEmptyObjectAsInt ()
1049 Deserialize ("{}", typeof (int));
1052 [Test]
1053 public void DeserializeEmptyObjectAsDBNull ()
1055 Assert.AreEqual (DBNull.Value, Deserialize ("{}", typeof (DBNull)));
1058 [Test]
1059 [ExpectedException (typeof (SerializationException))]
1060 public void DeserializeEnumByName ()
1062 // enum is parsed into long
1063 Deserialize (@"""Red""", typeof (Colors));
1066 [Test]
1067 public void DeserializeEnum2 ()
1069 object o = Deserialize ("0", typeof (Colors));
1071 Assert.AreEqual (typeof (Colors), o.GetType (), "#de3");
1072 Colors c = (Colors) o;
1073 Assert.AreEqual (Colors.Red, c, "#de4");
1076 [Test]
1077 [ExpectedException (typeof (SerializationException))]
1078 public void DeserializeEnumInvalid ()
1080 Deserialize ("", typeof (Colors));
1083 [Test]
1084 [ExpectedException (typeof (SerializationException))]
1085 [Category ("NotDotNet")] // 0.0 is an invalid Colors value.
1086 public void DeserializeEnumInvalid3 ()
1088 //"0.0" instead of "0"
1089 Deserialize (
1090 "0.0",
1091 typeof (Colors));
1094 [Test]
1095 public void DeserializeEnumWithDC ()
1097 object o = Deserialize ("0", typeof (ColorsWithDC));
1099 Assert.AreEqual (typeof (ColorsWithDC), o.GetType (), "#de5");
1100 ColorsWithDC cdc = (ColorsWithDC) o;
1101 Assert.AreEqual (ColorsWithDC.Red, o, "#de6");
1104 [Test]
1105 [ExpectedException (typeof (SerializationException))]
1106 [Category ("NotDotNet")] // 4 is an invalid Colors value.
1107 [Category ("NotWorking")]
1108 public void DeserializeEnumWithDCInvalid ()
1110 Deserialize (
1111 "4",
1112 typeof (ColorsWithDC));
1115 [Test]
1116 public void DeserializeDCWithEnum ()
1118 object o = Deserialize (
1119 "{\"_colors\":0}",
1120 typeof (DCWithEnum));
1122 Assert.AreEqual (typeof (DCWithEnum), o.GetType (), "#de7");
1123 DCWithEnum dc = (DCWithEnum) o;
1124 Assert.AreEqual (Colors.Red, dc.colors, "#de8");
1127 [Test]
1128 public void ReadObjectVerifyObjectNameFalse ()
1130 string xml = @"<any><Member1>bar</Member1></any>";
1131 object o = new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1132 .ReadObject (XmlReader.Create (new StringReader (xml)), false);
1133 Assert.IsTrue (o is VerifyObjectNameTestData, "#1");
1135 string xml2 = @"<any><x:Member1 xmlns:x=""http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"">bar</x:Member1></any>";
1136 o = new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1137 .ReadObject (XmlReader.Create (new StringReader (xml2)), false);
1138 Assert.IsTrue (o is VerifyObjectNameTestData, "#2");
1141 [Test]
1142 [ExpectedException (typeof (SerializationException))]
1143 public void ReadObjectVerifyObjectNameTrue ()
1145 string xml = @"<any><Member1>bar</Member1></any>";
1146 new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1147 .ReadObject (XmlReader.Create (new StringReader (xml)), true);
1150 [Test] // member name is out of scope
1151 public void ReadObjectVerifyObjectNameTrue2 ()
1153 string xml = @"<root><Member2>bar</Member2></root>";
1154 new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1155 .ReadObject (XmlReader.Create (new StringReader (xml)), true);
1158 [Test]
1159 public void ReadTypedObjectJson ()
1161 object o = Deserialize (@"{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0}", typeof (DCWithEnum));
1162 Assert.AreEqual (typeof (DCWithEnum), o.GetType ());
1165 [Test]
1166 public void ReadObjectDCArrayJson ()
1168 object o = Deserialize (@"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0}]",
1169 typeof (object []), typeof (DCWithEnum));
1170 Assert.AreEqual (typeof (object []), o.GetType (), "#1");
1171 object [] arr = (object []) o;
1172 Assert.AreEqual (typeof (DCWithEnum), arr [0].GetType (), "#2");
1175 [Test]
1176 public void ReadObjectDCArray2Json ()
1178 object o = Deserialize (@"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0},{""__type"":""DCSimple1:#MonoTests.System.Runtime.Serialization.Json"",""Foo"":""hello""}]",
1179 typeof (object []), typeof (DCWithEnum), typeof (DCSimple1));
1180 Assert.AreEqual (typeof (object []), o.GetType (), "#1");
1181 object [] arr = (object []) o;
1182 Assert.AreEqual (typeof (DCWithEnum), arr [0].GetType (), "#2");
1183 Assert.AreEqual (typeof (DCSimple1), arr [1].GetType (), "#3");
1186 private object Deserialize (string xml, Type type, params Type [] knownTypes)
1188 DataContractJsonSerializer ser = new DataContractJsonSerializer (type, knownTypes);
1189 XmlReader xr = JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (xml), new XmlDictionaryReaderQuotas ());
1190 return ser.ReadObject (xr);
1193 [Test]
1194 public void IsStartObject ()
1196 DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCSimple1));
1197 Assert.IsTrue (s.IsStartObject (XmlReader.Create (new StringReader ("<root></root>"))), "#1");
1198 Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<dummy></dummy>"))), "#2");
1199 Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<Foo></Foo>"))), "#3");
1200 Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<root xmlns='urn:foo'></root>"))), "#4");
1203 [Test]
1204 public void SerializeNonDC2 ()
1206 var ser = new DataContractJsonSerializer (typeof (TestData));
1207 StringWriter sw = new StringWriter ();
1208 var obj = new TestData () { Foo = "foo", Bar = "bar", Baz = "baz" };
1210 // XML
1211 using (var xw = XmlWriter.Create (sw))
1212 ser.WriteObject (xw, obj);
1213 var s = sw.ToString ();
1214 // since the order is not preserved, we compare only contents.
1215 Assert.IsTrue (s.IndexOf ("<Foo>foo</Foo>") > 0, "#1-1");
1216 Assert.IsTrue (s.IndexOf ("<Bar>bar</Bar>") > 0, "#1-2");
1217 Assert.IsFalse (s.IndexOf ("<Baz>baz</Baz>") > 0, "#1-3");
1219 // JSON
1220 MemoryStream ms = new MemoryStream ();
1221 using (var xw = JsonReaderWriterFactory.CreateJsonWriter (ms))
1222 ser.WriteObject (ms, obj);
1223 s = new StreamReader (new MemoryStream (ms.ToArray ())).ReadToEnd ().Replace ('"', '/');
1224 // since the order is not preserved, we compare only contents.
1225 Assert.IsTrue (s.IndexOf ("/Foo/:/foo/") > 0, "#2-1");
1226 Assert.IsTrue (s.IndexOf ("/Bar/:/bar/") > 0, "#2-2");
1227 Assert.IsFalse (s.IndexOf ("/Baz/:/baz/") > 0, "#2-3");
1230 [Test]
1231 public void AlwaysEmitTypeInformation ()
1233 var ms = new MemoryStream ();
1234 var ds = new DataContractJsonSerializer (typeof (string), "root", null, 10, false, null, true);
1235 ds.WriteObject (ms, "foobar");
1236 var s = Encoding.UTF8.GetString (ms.ToArray ());
1237 Assert.AreEqual ("\"foobar\"", s, "#1");
1240 [Test]
1241 public void AlwaysEmitTypeInformation2 ()
1243 var ms = new MemoryStream ();
1244 var ds = new DataContractJsonSerializer (typeof (TestData), "root", null, 10, false, null, true);
1245 ds.WriteObject (ms, new TestData () { Foo = "foo"});
1246 var s = Encoding.UTF8.GetString (ms.ToArray ());
1247 Assert.AreEqual (@"{""__type"":""TestData:#MonoTests.System.Runtime.Serialization.Json"",""Bar"":null,""Foo"":""foo""}", s, "#1");
1250 [Test]
1251 public void AlwaysEmitTypeInformation3 ()
1253 var ms = new MemoryStream ();
1254 var ds = new DataContractJsonSerializer (typeof (TestData), "root", null, 10, false, null, false);
1255 ds.WriteObject (ms, new TestData () { Foo = "foo"});
1256 var s = Encoding.UTF8.GetString (ms.ToArray ());
1257 Assert.AreEqual (@"{""Bar"":null,""Foo"":""foo""}", s, "#1");
1260 [Test]
1261 public void TestNonpublicDeserialization ()
1263 string s1= @"{""Bar"":""bar"", ""Foo"":""foo"", ""Baz"":""baz""}";
1264 TestData o1 = ((TestData)(new DataContractJsonSerializer (typeof (TestData)).ReadObject (JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (s1), new XmlDictionaryReaderQuotas ()))));
1266 Assert.AreEqual (null, o1.Baz, "#1");
1268 string s2 = @"{""TestData"":[{""key"":""key1"",""value"":""value1""}]}";
1269 KeyValueTestData o2 = ((KeyValueTestData)(new DataContractJsonSerializer (typeof (KeyValueTestData)).ReadObject (JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (s2), new XmlDictionaryReaderQuotas ()))));
1271 Assert.AreEqual (1, o2.TestData.Count, "#2");
1272 Assert.AreEqual ("key1", o2.TestData[0].Key, "#3");
1273 Assert.AreEqual ("value1", o2.TestData[0].Value, "#4");
1276 // [Test] use this case if you want to check lame silverlight parser behavior. Seealso #549756
1277 public void QuotelessDeserialization ()
1279 string s1 = @"{FooMember:""value""}";
1280 var ds = new DataContractJsonSerializer (typeof (DCWithName));
1281 ds.ReadObject (new MemoryStream (Encoding.UTF8.GetBytes (s1)));
1283 string s2 = @"{FooMember:"" \""{dummy:string}\""""}";
1284 ds.ReadObject (new MemoryStream (Encoding.UTF8.GetBytes (s2)));
1287 [Test]
1288 [Category ("NotWorking")]
1289 public void TypeIsNotPartsOfKnownTypes ()
1291 var dcs = new DataContractSerializer (typeof (string));
1292 Assert.AreEqual (0, dcs.KnownTypes.Count, "KnownTypes #1");
1293 var dcjs = new DataContractJsonSerializer (typeof (string));
1294 Assert.AreEqual (0, dcjs.KnownTypes.Count, "KnownTypes #2");
1297 [Test]
1298 public void ReadWriteNullObject ()
1300 DataContractJsonSerializer dcjs = new DataContractJsonSerializer (typeof (string));
1301 using (MemoryStream ms = new MemoryStream ()) {
1302 dcjs.WriteObject (ms, null);
1303 ms.Position = 0;
1304 using (StreamReader sr = new StreamReader (ms)) {
1305 string data = sr.ReadToEnd ();
1306 Assert.AreEqual ("null", data, "WriteObject(stream,null)");
1308 ms.Position = 0;
1309 Assert.IsNull (dcjs.ReadObject (ms), "ReadObject(stream)");
1314 object ReadWriteObject (Type type, object obj, string expected)
1316 using (MemoryStream ms = new MemoryStream ()) {
1317 DataContractJsonSerializer dcjs = new DataContractJsonSerializer (type);
1318 dcjs.WriteObject (ms, obj);
1319 ms.Position = 0;
1320 using (StreamReader sr = new StreamReader (ms)) {
1321 Assert.AreEqual (expected, sr.ReadToEnd (), "WriteObject");
1323 ms.Position = 0;
1324 return dcjs.ReadObject (ms);
1329 [Test]
1330 [Ignore ("Wrong test case. See bug #573691")]
1331 public void ReadWriteObject_Single_SpecialCases ()
1333 Assert.IsTrue (Single.IsNaN ((float) ReadWriteObject (typeof (float), Single.NaN, "NaN")));
1334 Assert.IsTrue (Single.IsNegativeInfinity ((float) ReadWriteObject (typeof (float), Single.NegativeInfinity, "-INF")));
1335 Assert.IsTrue (Single.IsPositiveInfinity ((float) ReadWriteObject (typeof (float), Single.PositiveInfinity, "INF")));
1338 [Test]
1339 [Ignore ("Wrong test case. See bug #573691")]
1340 public void ReadWriteObject_Double_SpecialCases ()
1342 Assert.IsTrue (Double.IsNaN ((double) ReadWriteObject (typeof (double), Double.NaN, "NaN")));
1343 Assert.IsTrue (Double.IsNegativeInfinity ((double) ReadWriteObject (typeof (double), Double.NegativeInfinity, "-INF")));
1344 Assert.IsTrue (Double.IsPositiveInfinity ((double) ReadWriteObject (typeof (double), Double.PositiveInfinity, "INF")));
1347 [Test]
1348 public void ReadWriteDateTime ()
1350 var ms = new MemoryStream ();
1351 DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (Query));
1352 Query query = new Query () {
1353 StartDate = new DateTime (2010, 3, 4, 5, 6, 7),
1354 EndDate = new DateTime (2010, 4, 5, 6, 7, 8)
1356 serializer.WriteObject (ms, query);
1357 Assert.AreEqual ("{\"StartDate\":\"\\/Date(1267679167000)\\/\",\"EndDate\":\"\\/Date(1270447628000)\\/\"}", Encoding.UTF8.GetString (ms.ToArray ()), "#1");
1358 ms.Position = 0;
1359 Console.WriteLine (new StreamReader (ms).ReadToEnd ());
1360 ms.Position = 0;
1361 var q = (Query) serializer.ReadObject(ms);
1362 Assert.AreEqual (query.StartDate, q.StartDate, "#2");
1363 Assert.AreEqual (query.EndDate, q.EndDate, "#3");
1366 [Test]
1367 public void DeserializeNullMember ()
1369 var ds = new DataContractJsonSerializer (typeof (ClassA));
1370 var stream = new MemoryStream ();
1371 var a = new ClassA ();
1372 ds.WriteObject (stream, a);
1373 stream.Position = 0;
1374 a = (ClassA) ds.ReadObject (stream);
1375 Assert.IsNull (a.B, "#1");
1378 [Test]
1379 public void OnDeserializationMethods ()
1381 var ds = new DataContractJsonSerializer (typeof (GSPlayerListErg));
1382 var obj = new GSPlayerListErg ();
1383 var ms = new MemoryStream ();
1384 ds.WriteObject (ms, obj);
1385 ms.Position = 0;
1386 ds.ReadObject (ms);
1387 Assert.IsTrue (GSPlayerListErg.A, "A");
1388 Assert.IsTrue (GSPlayerListErg.B, "B");
1389 Assert.IsTrue (GSPlayerListErg.C, "C");
1392 [Test]
1393 public void WriteChar ()
1395 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof (CharTest));
1396 using (MemoryStream ms = new MemoryStream()) {
1397 serializer.WriteObject(ms, new CharTest ());
1398 ms.Position = 0L;
1399 using (StreamReader reader = new StreamReader(ms)) {
1400 reader.ReadToEnd();
1405 [Test]
1406 public void DictionarySerialization ()
1408 var dict = new MyDictionary<string,string> ();
1409 dict.Add ("key", "value");
1410 var serializer = new DataContractJsonSerializer (dict.GetType ());
1411 var stream = new MemoryStream ();
1412 serializer.WriteObject (stream, dict);
1413 stream.Position = 0;
1415 Assert.AreEqual ("[{\"Key\":\"key\",\"Value\":\"value\"}]", new StreamReader (stream).ReadToEnd (), "#1");
1416 stream.Position = 0;
1417 dict = (MyDictionary<string,string>) serializer.ReadObject (stream);
1418 Assert.AreEqual (1, dict.Count, "#2");
1419 Assert.AreEqual ("value", dict ["key"], "#3");
1423 public class CharTest
1425 public char Foo;
1428 public class TestData
1430 public string Foo { get; set; }
1431 public string Bar { get; set; }
1432 internal string Baz { get; set; }
1435 public enum Colors {
1436 Red, Green, Blue
1439 [DataContract (Name = "_ColorsWithDC")]
1440 public enum ColorsWithDC {
1442 [EnumMember (Value = "_Red")]
1443 Red,
1444 [EnumMember]
1445 Green,
1446 Blue
1450 public enum ColorsEnumMemberNoDC {
1451 [EnumMember (Value = "_Red")]
1452 Red,
1453 [EnumMember]
1454 Green,
1455 Blue
1458 [DataContract]
1459 public class DCWithEnum {
1460 [DataMember (Name = "_colors")]
1461 public Colors colors;
1464 [DataContract]
1465 public class DCEmpty
1467 // serializer doesn't touch it.
1468 public string Foo = "TEST";
1471 [DataContract]
1472 public class DCSimple1
1474 [DataMember]
1475 public string Foo = "TEST";
1478 [DataContract]
1479 public class DCHasNonDC
1481 [DataMember]
1482 public NonDC Hoge= new NonDC ();
1485 public class NonDC
1487 public string Whee = "whee!";
1490 [DataContract]
1491 public class DCHasSerializable
1493 [DataMember]
1494 public SimpleSer1 Ser = new SimpleSer1 ();
1497 [DataContract (Name = "Foo")]
1498 public class DCWithName
1500 [DataMember (Name = "FooMember")]
1501 public string DMWithName = "value";
1504 [DataContract (Name = "")]
1505 public class DCWithEmptyName
1507 [DataMember]
1508 public string Foo;
1511 [DataContract (Name = null)]
1512 public class DCWithNullName
1514 [DataMember]
1515 public string Foo;
1518 [DataContract (Namespace = "")]
1519 public class DCWithEmptyNamespace
1521 [DataMember]
1522 public string Foo;
1525 [Serializable]
1526 public class SimpleSer1
1528 public string Doh = "doh!";
1531 public class Wrapper
1533 [DataContract]
1534 public class DCWrapped
1539 [DataContract]
1540 public class CollectionContainer
1542 Collection<string> items = new Collection<string> ();
1544 [DataMember]
1545 public Collection<string> Items {
1546 get { return items; }
1550 [CollectionDataContract]
1551 public class DataCollection<T> : Collection<T>
1555 [DataContract]
1556 public class DataCollectionContainer
1558 DataCollection<string> items = new DataCollection<string> ();
1560 [DataMember]
1561 public DataCollection<string> Items {
1562 get { return items; }
1566 [DataContract]
1567 class SerializeNonDCArrayType
1569 [DataMember]
1570 public NonDCItem [] IPAddresses = new NonDCItem [0];
1573 public class NonDCItem
1575 public byte [] Data { get; set; }
1578 [DataContract]
1579 public class VerifyObjectNameTestData
1581 [DataMember]
1582 string Member1 = "foo";
1585 [Serializable]
1586 public class KeyValueTestData {
1587 public List<KeyValuePair<string,string>> TestData = new List<KeyValuePair<string,string>>();
1590 [DataContract] // bug #586169
1591 public class Query
1593 [DataMember (Order=1)]
1594 public DateTime StartDate { get; set; }
1595 [DataMember (Order=2)]
1596 public DateTime EndDate { get; set; }
1599 public class ClassA {
1600 public ClassB B { get; set; }
1603 public class ClassB
1607 public class GSPlayerListErg
1609 public GSPlayerListErg ()
1611 Init ();
1614 void Init ()
1616 C = true;
1619 [OnDeserializing]
1620 public void OnDeserializing (StreamingContext c)
1622 A = true;
1623 Init ();
1626 [OnDeserialized]
1627 void OnDeserialized (StreamingContext c)
1629 B = true;
1632 public static bool A, B, C;
1634 [DataMember (Name = "T")]
1635 public long CodedServerTimeUTC { get; set; }
1636 public DateTime ServerTimeUTC { get; set; }
1640 [DataContract]
1641 class GlobalSample1
1646 public class MyDictionary<K, V> : System.Collections.Generic.IDictionary<K, V>
1648 Dictionary<K,V> dic = new Dictionary<K,V> ();
1650 public void Add (K key, V value)
1652 dic.Add (key, value);
1655 public bool ContainsKey (K key)
1657 return dic.ContainsKey (key);
1660 public ICollection<K> Keys {
1661 get { return dic.Keys; }
1664 public bool Remove (K key)
1666 return dic.Remove (key);
1669 public bool TryGetValue (K key, out V value)
1671 return dic.TryGetValue (key, out value);
1674 public ICollection<V> Values {
1675 get { return dic.Values; }
1678 public V this [K key] {
1679 get { return dic [key]; }
1680 set { dic [key] = value; }
1683 IEnumerator IEnumerable.GetEnumerator ()
1685 return dic.GetEnumerator ();
1688 ICollection<KeyValuePair<K,V>> Coll {
1689 get { return (ICollection<KeyValuePair<K,V>>) dic; }
1692 public void Add (KeyValuePair<K, V> item)
1694 Coll.Add (item);
1697 public void Clear ()
1699 dic.Clear ();
1702 public bool Contains (KeyValuePair<K, V> item)
1704 return Coll.Contains (item);
1707 public void CopyTo (KeyValuePair<K, V> [] array, int arrayIndex)
1709 Coll.CopyTo (array, arrayIndex);
1712 public int Count {
1713 get { return dic.Count; }
1716 public bool IsReadOnly {
1717 get { return Coll.IsReadOnly; }
1720 public bool Remove (KeyValuePair<K, V> item)
1722 return Coll.Remove (item);
1725 public IEnumerator<KeyValuePair<K, V>> GetEnumerator ()
1727 return Coll.GetEnumerator ();