| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667 |
- //
- // DataContractJsonSerializerTest.cs
- //
- // Author:
- // Atsushi Enomoto <[email protected]>
- // Ankit Jain <[email protected]>
- // Antoine Cailliau <[email protected]>
- //
- // Copyright (C) 2005-2007 Novell, Inc. http://www.novell.com
- //
- // Permission is hereby granted, free of charge, to any person obtaining
- // a copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to
- // permit persons to whom the Software is furnished to do so, subject to
- // the following conditions:
- //
- // The above copyright notice and this permission notice shall be
- // included in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- //
- //
- // This test code contains tests for DataContractJsonSerializer, which is
- // imported from DataContractSerializerTest.cs.
- //
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.IO;
- using System.Net;
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Json;
- using System.Text;
- using System.Xml;
- using NUnit.Framework;
- namespace MonoTests.System.Runtime.Serialization.Json
- {
- [TestFixture]
- public class DataContractJsonSerializerTest
- {
- static readonly XmlWriterSettings settings;
- static DataContractJsonSerializerTest ()
- {
- settings = new XmlWriterSettings ();
- settings.OmitXmlDeclaration = true;
- }
- [DataContract]
- class Sample1
- {
- [DataMember]
- public string Member1;
- }
- [Test]
- [ExpectedException (typeof (ArgumentNullException))]
- public void ConstructorTypeNull ()
- {
- new DataContractJsonSerializer (null);
- }
- [Test]
- public void ConstructorKnownTypesNull ()
- {
- // null knownTypes is allowed.
- new DataContractJsonSerializer (typeof (Sample1), (IEnumerable<Type>) null);
- new DataContractJsonSerializer (typeof (Sample1), "Foo", null);
- }
- [Test]
- [ExpectedException (typeof (ArgumentNullException))]
- public void ConstructorNameNull ()
- {
- new DataContractJsonSerializer (typeof (Sample1), (string) null);
- }
- [Test]
- [ExpectedException (typeof (ArgumentOutOfRangeException))]
- public void ConstructorNegativeMaxObjects ()
- {
- new DataContractJsonSerializer (typeof (Sample1), "Sample1",
- null, -1, false, null, false);
- }
- [Test]
- public void ConstructorMisc ()
- {
- new DataContractJsonSerializer (typeof (GlobalSample1)).WriteObject (new MemoryStream (), new GlobalSample1 ());
- }
- [Test]
- public void WriteObjectContent ()
- {
- StringWriter sw = new StringWriter ();
- using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
- DataContractJsonSerializer ser =
- new DataContractJsonSerializer (typeof (string));
- xw.WriteStartElement ("my-element");
- ser.WriteObjectContent (xw, "TEST STRING");
- xw.WriteEndElement ();
- }
- Assert.AreEqual ("<my-element>TEST STRING</my-element>",
- sw.ToString ());
- }
- // int
- [Test]
- public void SerializeIntXml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeInt (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""number"">1</root>",
- sw.ToString ());
- }
- [Test]
- public void SerializeIntJson ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeInt (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- "1",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeInt (XmlWriter writer)
- {
- DataContractJsonSerializer ser =
- new DataContractJsonSerializer (typeof (int));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, 1);
- }
- }
- // int, with rootName
- [Test]
- public void SerializeIntXmlWithRootName ()
- {
- StringWriter sw = new StringWriter ();
- SerializeIntWithRootName (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<myroot type=""number"">1</myroot>",
- sw.ToString ());
- }
- [Test]
- // since JsonWriter supports only "root" as the root name, using
- // XmlWriter from JsonReaderWriterFactory will always fail with
- // an explicit rootName.
- [ExpectedException (typeof (SerializationException))]
- public void SerializeIntJsonWithRootName ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeIntWithRootName (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- "1",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeIntWithRootName (XmlWriter writer)
- {
- DataContractJsonSerializer ser =
- new DataContractJsonSerializer (typeof (int), "myroot");
- using (XmlWriter w = writer) {
- ser.WriteObject (w, 1);
- }
- }
- // pass typeof(DCEmpty), serialize int
- [Test]
- public void SerializeIntForDCEmptyXml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeIntForDCEmpty (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""number"">1</root>",
- sw.ToString ());
- }
- [Test]
- public void SerializeIntForDCEmptyJson ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeIntForDCEmpty (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- "1",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeIntForDCEmpty (XmlWriter writer)
- {
- DataContractJsonSerializer ser =
- new DataContractJsonSerializer (typeof (DCEmpty));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, 1);
- }
- }
- // DCEmpty
- [Test]
- public void SerializeEmptyClassXml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeEmptyClass (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""object"" />",
- sw.ToString ());
- }
- [Test]
- public void SerializeEmptyClassJson ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeEmptyClass (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- "{}",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeEmptyClass (XmlWriter writer)
- {
- DataContractJsonSerializer ser =
- new DataContractJsonSerializer (typeof (DCEmpty));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, new DCEmpty ());
- }
- }
- // string (primitive)
- [Test]
- public void SerializePrimitiveStringXml ()
- {
- StringWriter sw = new StringWriter ();
- SerializePrimitiveString (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- "<root>TEST</root>",
- sw.ToString ());
- }
- [Test]
- public void SerializePrimitiveStringJson ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializePrimitiveString (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- @"""TEST""",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializePrimitiveString (XmlWriter writer)
- {
- XmlObjectSerializer ser =
- new DataContractJsonSerializer (typeof (string));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, "TEST");
- }
- }
- // QName (primitive but ...)
- [Test]
- public void SerializePrimitiveQNameXml ()
- {
- StringWriter sw = new StringWriter ();
- SerializePrimitiveQName (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- "<root>foo:urn:foo</root>",
- sw.ToString ());
- }
- [Test]
- public void SerializePrimitiveQNameJson ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializePrimitiveQName (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- @"""foo:urn:foo""",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializePrimitiveQName (XmlWriter writer)
- {
- XmlObjectSerializer ser =
- new DataContractJsonSerializer (typeof (XmlQualifiedName));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, new XmlQualifiedName ("foo", "urn:foo"));
- }
- }
- // DBNull (primitive)
- [Test]
- public void SerializeDBNullXml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeDBNull (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""object"" />",
- sw.ToString ());
- }
- [Test]
- public void SerializeDBNullJson ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeDBNull (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- "{}",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeDBNull (XmlWriter writer)
- {
- DataContractJsonSerializer ser =
- new DataContractJsonSerializer (typeof (DBNull));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, DBNull.Value);
- }
- }
- // DCSimple1
- [Test]
- public void SerializeSimpleClass1Xml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeSimpleClass1 (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""object""><Foo>TEST</Foo></root>",
- sw.ToString ());
- }
- [Test]
- public void SerializeSimpleClass1Json ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeSimpleClass1 (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- @"{""Foo"":""TEST""}",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeSimpleClass1 (XmlWriter writer)
- {
- DataContractJsonSerializer ser =
- new DataContractJsonSerializer (typeof (DCSimple1));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, new DCSimple1 ());
- }
- }
- // NonDC
- [Test]
- // NonDC is not a DataContract type.
- public void SerializeNonDCOnlyCtor ()
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (NonDC));
- }
- [Test]
- //[ExpectedException (typeof (InvalidDataContractException))]
- // NonDC is not a DataContract type.
- // UPDATE: non-DataContract types are became valid in RTM.
- public void SerializeNonDC ()
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (NonDC));
- using (XmlWriter w = XmlWriter.Create (TextWriter.Null, settings)) {
- ser.WriteObject (w, new NonDC ());
- }
- }
- // DCHasNonDC
- [Test]
- //[ExpectedException (typeof (InvalidDataContractException))]
- // DCHasNonDC itself is a DataContract type whose field is
- // marked as DataMember but its type is not DataContract.
- // UPDATE: non-DataContract types are became valid in RTM.
- public void SerializeDCHasNonDC ()
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCHasNonDC));
- using (XmlWriter w = XmlWriter.Create (TextWriter.Null, settings)) {
- ser.WriteObject (w, new DCHasNonDC ());
- }
- }
- // DCHasSerializable
- [Test]
- public void SerializeSimpleSerializable1Xml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeSimpleSerializable1 (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""object""><Ser type=""object""><Doh>doh!</Doh></Ser></root>",
- sw.ToString ());
- }
- [Test]
- public void SerializeSimpleSerializable1Json ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeSimpleSerializable1 (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- @"{""Ser"":{""Doh"":""doh!""}}",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- // DCHasSerializable itself is DataContract and has a field
- // whose type is not contract but serializable.
- void SerializeSimpleSerializable1 (XmlWriter writer)
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCHasSerializable));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, new DCHasSerializable ());
- }
- }
- [Test]
- public void SerializeDCWithNameXml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeDCWithName (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""object""><FooMember>value</FooMember></root>",
- sw.ToString ());
- }
- [Test]
- public void SerializeDCWithNameJson ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeDCWithName (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- @"{""FooMember"":""value""}",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeDCWithName (XmlWriter writer)
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithName));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, new DCWithName ());
- }
- }
- [Test]
- public void SerializeDCWithEmptyName1 ()
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEmptyName));
- StringWriter sw = new StringWriter ();
- DCWithEmptyName dc = new DCWithEmptyName ();
- using (XmlWriter w = XmlWriter.Create (sw, settings)) {
- try {
- ser.WriteObject (w, dc);
- } catch (InvalidDataContractException) {
- return;
- }
- }
- Assert.Fail ("Expected InvalidDataContractException");
- }
- [Test]
- public void SerializeDCWithEmptyName2 ()
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithName));
- StringWriter sw = new StringWriter ();
- /* DataContractAttribute.Name == "", not valid */
- DCWithEmptyName dc = new DCWithEmptyName ();
- using (XmlWriter w = XmlWriter.Create (sw, settings)) {
- try {
- ser.WriteObject (w, dc);
- } catch (InvalidDataContractException) {
- return;
- }
- }
- Assert.Fail ("Expected InvalidDataContractException");
- }
- [Test]
- [Category("NotWorking")]
- public void SerializeDCWithNullName ()
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithNullName));
- StringWriter sw = new StringWriter ();
- using (XmlWriter w = XmlWriter.Create (sw, settings)) {
- try {
- /* DataContractAttribute.Name == "", not valid */
- ser.WriteObject (w, new DCWithNullName ());
- } catch (InvalidDataContractException) {
- return;
- }
- }
- Assert.Fail ("Expected InvalidDataContractException");
- }
- [Test]
- public void SerializeDCWithEmptyNamespace1 ()
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEmptyNamespace));
- StringWriter sw = new StringWriter ();
- using (XmlWriter w = XmlWriter.Create (sw, settings)) {
- ser.WriteObject (w, new DCWithEmptyNamespace ());
- }
- }
- [Test]
- public void SerializeWrappedClassXml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeWrappedClass (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""object"" />",
- sw.ToString ());
- }
- [Test]
- public void SerializeWrappedClassJson ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeWrappedClass (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- "{}",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeWrappedClass (XmlWriter writer)
- {
- DataContractJsonSerializer ser =
- new DataContractJsonSerializer (typeof (Wrapper.DCWrapped));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, new Wrapper.DCWrapped ());
- }
- }
- // CollectionContainer : Items must have a setter. (but became valid in RTM).
- [Test]
- public void SerializeReadOnlyCollectionMember ()
- {
- DataContractJsonSerializer ser =
- new DataContractJsonSerializer (typeof (CollectionContainer));
- StringWriter sw = new StringWriter ();
- using (XmlWriter w = XmlWriter.Create (sw, settings)) {
- ser.WriteObject (w, null);
- }
- }
- // DataCollectionContainer : Items must have a setter. (but became valid in RTM).
- [Test]
- public void SerializeReadOnlyDataCollectionMember ()
- {
- DataContractJsonSerializer ser =
- new DataContractJsonSerializer (typeof (DataCollectionContainer));
- StringWriter sw = new StringWriter ();
- using (XmlWriter w = XmlWriter.Create (sw, settings)) {
- ser.WriteObject (w, null);
- }
- }
- [Test]
- [Ignore ("https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=409970")]
- [ExpectedException (typeof (SerializationException))]
- public void DeserializeReadOnlyDataCollection_NullCollection ()
- {
- DataContractJsonSerializer ser =
- new DataContractJsonSerializer (typeof (CollectionContainer));
- StringWriter sw = new StringWriter ();
- var c = new CollectionContainer ();
- c.Items.Add ("foo");
- c.Items.Add ("bar");
- using (XmlWriter w = XmlWriter.Create (sw, settings))
- ser.WriteObject (w, c);
- // CollectionContainer.Items is null, so it cannot deserialize non-null collection.
- using (XmlReader r = XmlReader.Create (new StringReader (sw.ToString ())))
- c = (CollectionContainer) ser.ReadObject (r);
- }
- [Test]
- public void SerializeGuidXml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeGuid (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root>00000000-0000-0000-0000-000000000000</root>",
- sw.ToString ());
- }
- [Test]
- public void SerializeGuidJson ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeGuid (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- @"""00000000-0000-0000-0000-000000000000""",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeGuid (XmlWriter writer)
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Guid));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, Guid.Empty);
- }
- }
- [Test]
- public void SerializeEnumXml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeEnum (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""number"">0</root>",
- sw.ToString ());
- }
- [Test]
- public void SerializeEnumJson ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeEnum (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- "0",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeEnum (XmlWriter writer)
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Colors));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, new Colors ());
- }
- }
- [Test]
- public void SerializeEnum2Xml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeEnum2 (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""number"">0</root>",
- sw.ToString ());
- }
- [Test]
- public void SerializeEnum2Json ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeEnum2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- "0",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeEnum2 (XmlWriter writer)
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Colors));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, 0);
- }
- }
- [Test] // so, DataContract does not affect here.
- public void SerializeEnumWithDCXml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeEnumWithDC (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""number"">0</root>",
- sw.ToString ());
- }
- [Test]
- public void SerializeEnumWithDCJson ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeEnumWithDC (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- "0",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeEnumWithDC (XmlWriter writer)
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, new ColorsWithDC ());
- }
- }
- [Test]
- public void SerializeEnumWithNoDCXml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeEnumWithNoDC (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""number"">0</root>",
- sw.ToString ());
- }
- [Test]
- public void SerializeEnumWithNoDCJson ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeEnumWithNoDC (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- "0",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeEnumWithNoDC (XmlWriter writer)
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsEnumMemberNoDC));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, new ColorsEnumMemberNoDC ());
- }
- }
- [Test]
- public void SerializeEnumWithDC2Xml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeEnumWithDC2 (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""number"">3</root>",
- sw.ToString ());
- }
- [Test]
- public void SerializeEnumWithDC2Json ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeEnumWithDC2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- "3",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeEnumWithDC2 (XmlWriter writer)
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, 3);
- }
- }
- /*
- [Test]
- [ExpectedException (typeof (SerializationException))]
- public void SerializeEnumWithDCInvalid ()
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
- StringWriter sw = new StringWriter ();
- ColorsWithDC cdc = ColorsWithDC.Blue;
- using (XmlWriter w = XmlWriter.Create (sw, settings)) {
- ser.WriteObject (w, cdc);
- }
- }
- */
- [Test]
- public void SerializeDCWithEnumXml ()
- {
- StringWriter sw = new StringWriter ();
- SerializeDCWithEnum (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""object""><_colors type=""number"">0</_colors></root>",
- sw.ToString ());
- }
- [Test]
- public void SerializeDCWithEnumJson ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializeDCWithEnum (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- @"{""_colors"":0}",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializeDCWithEnum (XmlWriter writer)
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEnum));
- using (XmlWriter w = writer) {
- ser.WriteObject (w, new DCWithEnum ());
- }
- }
- [Test]
- public void SerializerDCArrayXml ()
- {
- StringWriter sw = new StringWriter ();
- SerializerDCArray (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<root type=""array""><item type=""object""><_colors type=""number"">0</_colors></item><item type=""object""><_colors type=""number"">1</_colors></item></root>",
- sw.ToString ());
- }
- [Test]
- public void SerializerDCArrayJson ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializerDCArray (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- @"[{""_colors"":0},{""_colors"":1}]",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializerDCArray (XmlWriter writer)
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEnum []));
- DCWithEnum [] arr = new DCWithEnum [2];
- arr [0] = new DCWithEnum (); arr [0].colors = Colors.Red;
- arr [1] = new DCWithEnum (); arr [1].colors = Colors.Green;
- using (XmlWriter w = writer) {
- ser.WriteObject (w, arr);
- }
- }
- [Test]
- public void SerializerDCArray2Xml ()
- {
- StringWriter sw = new StringWriter ();
- SerializerDCArray2 (XmlWriter.Create (sw, settings));
- Assert.AreEqual (
- @"<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>",
- sw.ToString ());
- }
- [Test]
- public void SerializerDCArray2Json ()
- {
- MemoryStream ms = new MemoryStream ();
- SerializerDCArray2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
- Assert.AreEqual (
- @"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0},{""__type"":""DCSimple1:#MonoTests.System.Runtime.Serialization.Json"",""Foo"":""hello""}]",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- void SerializerDCArray2 (XmlWriter writer)
- {
- List<Type> known = new List<Type> ();
- known.Add (typeof (DCWithEnum));
- known.Add (typeof (DCSimple1));
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (object []), known);
- object [] arr = new object [2];
- arr [0] = new DCWithEnum (); ((DCWithEnum)arr [0]).colors = Colors.Red;
- arr [1] = new DCSimple1 (); ((DCSimple1) arr [1]).Foo = "hello";
- using (XmlWriter w = writer) {
- ser.WriteObject (w, arr);
- }
- }
- [Test]
- public void SerializerDCArray3Xml ()
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (int []));
- StringWriter sw = new StringWriter ();
- int [] arr = new int [2];
- arr [0] = 1; arr [1] = 2;
- using (XmlWriter w = XmlWriter.Create (sw, settings)) {
- ser.WriteObject (w, arr);
- }
- Assert.AreEqual (
- @"<root type=""array""><item type=""number"">1</item><item type=""number"">2</item></root>",
- sw.ToString ());
- }
- [Test]
- public void SerializerDCArray3Json ()
- {
- MemoryStream ms = new MemoryStream ();
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (int []));
- int [] arr = new int [2];
- arr [0] = 1; arr [1] = 2;
- using (XmlWriter w = JsonReaderWriterFactory.CreateJsonWriter (ms)) {
- ser.WriteObject (w, arr);
- }
- Assert.AreEqual (
- @"[1,2]",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- [Test]
- // ... so, non-JSON XmlWriter is still accepted.
- public void SerializeNonDCArrayXml ()
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
- StringWriter sw = new StringWriter ();
- using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
- ser.WriteObject (xw, new SerializeNonDCArrayType ());
- }
- Assert.AreEqual (@"<root type=""object""><IPAddresses type=""array"" /></root>",
- sw.ToString ());
- }
- [Test]
- public void SerializeNonDCArrayJson ()
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
- MemoryStream ms = new MemoryStream ();
- using (XmlWriter xw = JsonReaderWriterFactory.CreateJsonWriter (ms)) {
- ser.WriteObject (xw, new SerializeNonDCArrayType ());
- }
- Assert.AreEqual (@"{""IPAddresses"":[]}",
- Encoding.UTF8.GetString (ms.ToArray ()));
- }
- [Test]
- public void SerializeNonDCArrayItems ()
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
- StringWriter sw = new StringWriter ();
- using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
- SerializeNonDCArrayType obj = new SerializeNonDCArrayType ();
- obj.IPAddresses = new NonDCItem [] {new NonDCItem () { Data = new byte [] {1, 2, 3, 4} } };
- ser.WriteObject (xw, obj);
- }
- XmlDocument doc = new XmlDocument ();
- doc.LoadXml (sw.ToString ());
- XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
- nsmgr.AddNamespace ("s", "http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization");
- nsmgr.AddNamespace ("n", "http://schemas.datacontract.org/2004/07/System.Net");
- nsmgr.AddNamespace ("a", "http://schemas.microsoft.com/2003/10/Serialization/Arrays");
- Assert.AreEqual (1, doc.SelectNodes ("/root/IPAddresses/item", nsmgr).Count, "#1");
- XmlElement el = doc.SelectSingleNode ("/root/IPAddresses/item/Data", nsmgr) as XmlElement;
- Assert.IsNotNull (el, "#3");
- Assert.AreEqual (4, el.SelectNodes ("item", nsmgr).Count, "#4");
- }
- [Test]
- public void MaxItemsInObjectGraph1 ()
- {
- // object count == maximum
- DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCEmpty), null, 1, false, null, false);
- s.WriteObject (XmlWriter.Create (TextWriter.Null), new DCEmpty ());
- }
- [Test]
- [ExpectedException (typeof (SerializationException))]
- public void MaxItemsInObjectGraph2 ()
- {
- // object count > maximum
- DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCSimple1), null, 1, false, null, false);
- s.WriteObject (XmlWriter.Create (TextWriter.Null), new DCSimple1 ());
- }
- [Test]
- public void DeserializeString ()
- {
- Assert.AreEqual ("ABC", Deserialize ("\"ABC\"", typeof (string)));
- }
- [Test]
- public void DeserializeInt ()
- {
- Assert.AreEqual (5, Deserialize ("5", typeof (int)));
- }
- [Test]
- public void DeserializeArray ()
- {
- int [] ret = (int []) Deserialize ("[5,6,7]", typeof (int []));
- Assert.AreEqual (5, ret [0], "#1");
- Assert.AreEqual (6, ret [1], "#2");
- Assert.AreEqual (7, ret [2], "#3");
- }
- [Test]
- public void DeserializeArrayUntyped ()
- {
- object [] ret = (object []) Deserialize ("[5,6,7]", typeof (object []));
- Assert.AreEqual (5, ret [0], "#1");
- Assert.AreEqual (6, ret [1], "#2");
- Assert.AreEqual (7, ret [2], "#3");
- }
- [Test]
- public void DeserializeMixedArray ()
- {
- object [] ret = (object []) Deserialize ("[5,\"6\",false]", typeof (object []));
- Assert.AreEqual (5, ret [0], "#1");
- Assert.AreEqual ("6", ret [1], "#2");
- Assert.AreEqual (false, ret [2], "#3");
- }
- [Test]
- [ExpectedException (typeof (SerializationException))]
- public void DeserializeEmptyAsString ()
- {
- // it somehow expects "root" which should have been already consumed.
- Deserialize ("", typeof (string));
- }
- [Test]
- [ExpectedException (typeof (SerializationException))]
- public void DeserializeEmptyAsInt ()
- {
- // it somehow expects "root" which should have been already consumed.
- Deserialize ("", typeof (int));
- }
- [Test]
- [ExpectedException (typeof (SerializationException))]
- public void DeserializeEmptyAsDBNull ()
- {
- // it somehow expects "root" which should have been already consumed.
- Deserialize ("", typeof (DBNull));
- }
- [Test]
- public void DeserializeEmptyObjectAsString ()
- {
- // looks like it is converted to ""
- Assert.AreEqual (String.Empty, Deserialize ("{}", typeof (string)));
- }
- [Test]
- [ExpectedException (typeof (SerializationException))]
- public void DeserializeEmptyObjectAsInt ()
- {
- Deserialize ("{}", typeof (int));
- }
- [Test]
- public void DeserializeEmptyObjectAsDBNull ()
- {
- Assert.AreEqual (DBNull.Value, Deserialize ("{}", typeof (DBNull)));
- }
- [Test]
- [ExpectedException (typeof (SerializationException))]
- public void DeserializeEnumByName ()
- {
- // enum is parsed into long
- Deserialize (@"""Red""", typeof (Colors));
- }
- [Test]
- public void DeserializeEnum2 ()
- {
- object o = Deserialize ("0", typeof (Colors));
- Assert.AreEqual (typeof (Colors), o.GetType (), "#de3");
- Colors c = (Colors) o;
- Assert.AreEqual (Colors.Red, c, "#de4");
- }
-
- [Test]
- [ExpectedException (typeof (SerializationException))]
- public void DeserializeEnumInvalid ()
- {
- Deserialize ("", typeof (Colors));
- }
- [Test]
- [ExpectedException (typeof (SerializationException))]
- [Ignore ("NotDotNet")] // 0.0 is an invalid Colors value.
- public void DeserializeEnumInvalid3 ()
- {
- //"0.0" instead of "0"
- Deserialize (
- "0.0",
- typeof (Colors));
- }
- [Test]
- public void DeserializeEnumWithDC ()
- {
- object o = Deserialize ("0", typeof (ColorsWithDC));
-
- Assert.AreEqual (typeof (ColorsWithDC), o.GetType (), "#de5");
- ColorsWithDC cdc = (ColorsWithDC) o;
- Assert.AreEqual (ColorsWithDC.Red, o, "#de6");
- }
- [Test]
- [ExpectedException (typeof (SerializationException))]
- [Ignore ("NotDotNet")] // 4 is an invalid Colors value.
- [Category ("NotWorking")]
- public void DeserializeEnumWithDCInvalid ()
- {
- Deserialize (
- "4",
- typeof (ColorsWithDC));
- }
- [Test]
- public void DeserializeDCWithEnum ()
- {
- object o = Deserialize (
- "{\"_colors\":0}",
- typeof (DCWithEnum));
- Assert.AreEqual (typeof (DCWithEnum), o.GetType (), "#de7");
- DCWithEnum dc = (DCWithEnum) o;
- Assert.AreEqual (Colors.Red, dc.colors, "#de8");
- }
- [Test]
- public void ReadObjectVerifyObjectNameFalse ()
- {
- string xml = @"<any><Member1>bar</Member1></any>";
- object o = new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
- .ReadObject (XmlReader.Create (new StringReader (xml)), false);
- Assert.IsTrue (o is VerifyObjectNameTestData, "#1");
- string xml2 = @"<any><x:Member1 xmlns:x=""http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"">bar</x:Member1></any>";
- o = new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
- .ReadObject (XmlReader.Create (new StringReader (xml2)), false);
- Assert.IsTrue (o is VerifyObjectNameTestData, "#2");
- }
- [Test]
- [ExpectedException (typeof (SerializationException))]
- public void ReadObjectVerifyObjectNameTrue ()
- {
- string xml = @"<any><Member1>bar</Member1></any>";
- new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
- .ReadObject (XmlReader.Create (new StringReader (xml)), true);
- }
- [Test] // member name is out of scope
- public void ReadObjectVerifyObjectNameTrue2 ()
- {
- string xml = @"<root><Member2>bar</Member2></root>";
- new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
- .ReadObject (XmlReader.Create (new StringReader (xml)), true);
- }
- [Test]
- public void ReadTypedObjectJson ()
- {
- object o = Deserialize (@"{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0}", typeof (DCWithEnum));
- Assert.AreEqual (typeof (DCWithEnum), o.GetType ());
- }
- [Test]
- public void ReadObjectDCArrayJson ()
- {
- object o = Deserialize (@"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0}]",
- typeof (object []), typeof (DCWithEnum));
- Assert.AreEqual (typeof (object []), o.GetType (), "#1");
- object [] arr = (object []) o;
- Assert.AreEqual (typeof (DCWithEnum), arr [0].GetType (), "#2");
- }
- [Test]
- public void ReadObjectDCArray2Json ()
- {
- object o = Deserialize (@"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0},{""__type"":""DCSimple1:#MonoTests.System.Runtime.Serialization.Json"",""Foo"":""hello""}]",
- typeof (object []), typeof (DCWithEnum), typeof (DCSimple1));
- Assert.AreEqual (typeof (object []), o.GetType (), "#1");
- object [] arr = (object []) o;
- Assert.AreEqual (typeof (DCWithEnum), arr [0].GetType (), "#2");
- Assert.AreEqual (typeof (DCSimple1), arr [1].GetType (), "#3");
- }
- private object Deserialize (string xml, Type type, params Type [] knownTypes)
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer (type, knownTypes);
- XmlReader xr = JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (xml), new XmlDictionaryReaderQuotas ());
- return ser.ReadObject (xr);
- }
- public T Deserialize<T>(string json)
- {
- var bytes = Encoding.Unicode.GetBytes (json);
- using (MemoryStream stream = new MemoryStream (bytes)) {
- var serializer = new DataContractJsonSerializer (typeof(T));
- return (T)serializer.ReadObject (stream);
- }
- }
- [Test]
- public void IsStartObject ()
- {
- DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCSimple1));
- Assert.IsTrue (s.IsStartObject (XmlReader.Create (new StringReader ("<root></root>"))), "#1");
- Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<dummy></dummy>"))), "#2");
- Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<Foo></Foo>"))), "#3");
- Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<root xmlns='urn:foo'></root>"))), "#4");
- }
- [Test]
- public void SerializeNonDC2 ()
- {
- var ser = new DataContractJsonSerializer (typeof (TestData));
- StringWriter sw = new StringWriter ();
- var obj = new TestData () { Foo = "foo", Bar = "bar", Baz = "baz" };
- // XML
- using (var xw = XmlWriter.Create (sw))
- ser.WriteObject (xw, obj);
- var s = sw.ToString ();
- // since the order is not preserved, we compare only contents.
- Assert.IsTrue (s.IndexOf ("<Foo>foo</Foo>") > 0, "#1-1");
- Assert.IsTrue (s.IndexOf ("<Bar>bar</Bar>") > 0, "#1-2");
- Assert.IsFalse (s.IndexOf ("<Baz>baz</Baz>") > 0, "#1-3");
- // JSON
- MemoryStream ms = new MemoryStream ();
- using (var xw = JsonReaderWriterFactory.CreateJsonWriter (ms))
- ser.WriteObject (ms, obj);
- s = new StreamReader (new MemoryStream (ms.ToArray ())).ReadToEnd ().Replace ('"', '/');
- // since the order is not preserved, we compare only contents.
- Assert.IsTrue (s.IndexOf ("/Foo/:/foo/") > 0, "#2-1");
- Assert.IsTrue (s.IndexOf ("/Bar/:/bar/") > 0, "#2-2");
- Assert.IsFalse (s.IndexOf ("/Baz/:/baz/") > 0, "#2-3");
- }
- [Test]
- public void AlwaysEmitTypeInformation ()
- {
- var ms = new MemoryStream ();
- var ds = new DataContractJsonSerializer (typeof (string), "root", null, 10, false, null, true);
- ds.WriteObject (ms, "foobar");
- var s = Encoding.UTF8.GetString (ms.ToArray ());
- Assert.AreEqual ("\"foobar\"", s, "#1");
- }
- [Test]
- public void AlwaysEmitTypeInformation2 ()
- {
- var ms = new MemoryStream ();
- var ds = new DataContractJsonSerializer (typeof (TestData), "root", null, 10, false, null, true);
- ds.WriteObject (ms, new TestData () { Foo = "foo"});
- var s = Encoding.UTF8.GetString (ms.ToArray ());
- Assert.AreEqual (@"{""__type"":""TestData:#MonoTests.System.Runtime.Serialization.Json"",""Bar"":null,""Foo"":""foo""}", s, "#1");
- }
- [Test]
- public void AlwaysEmitTypeInformation3 ()
- {
- var ms = new MemoryStream ();
- var ds = new DataContractJsonSerializer (typeof (TestData), "root", null, 10, false, null, false);
- ds.WriteObject (ms, new TestData () { Foo = "foo"});
- var s = Encoding.UTF8.GetString (ms.ToArray ());
- Assert.AreEqual (@"{""Bar"":null,""Foo"":""foo""}", s, "#1");
- }
- [Test]
- public void TestNonpublicDeserialization ()
- {
- string s1= @"{""Bar"":""bar"", ""Foo"":""foo"", ""Baz"":""baz""}";
- TestData o1 = ((TestData)(new DataContractJsonSerializer (typeof (TestData)).ReadObject (JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (s1), new XmlDictionaryReaderQuotas ()))));
- Assert.AreEqual (null, o1.Baz, "#1");
- string s2 = @"{""TestData"":[{""key"":""key1"",""value"":""value1""}]}";
- KeyValueTestData o2 = ((KeyValueTestData)(new DataContractJsonSerializer (typeof (KeyValueTestData)).ReadObject (JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (s2), new XmlDictionaryReaderQuotas ()))));
- Assert.AreEqual (1, o2.TestData.Count, "#2");
- Assert.AreEqual ("key1", o2.TestData[0].Key, "#3");
- Assert.AreEqual ("value1", o2.TestData[0].Value, "#4");
- }
- // [Test] use this case if you want to check lame silverlight parser behavior. Seealso #549756
- public void QuotelessDeserialization ()
- {
- string s1 = @"{FooMember:""value""}";
- var ds = new DataContractJsonSerializer (typeof (DCWithName));
- ds.ReadObject (new MemoryStream (Encoding.UTF8.GetBytes (s1)));
- string s2 = @"{FooMember:"" \""{dummy:string}\""""}";
- ds.ReadObject (new MemoryStream (Encoding.UTF8.GetBytes (s2)));
- }
- [Test]
- [Category ("NotWorking")]
- public void TypeIsNotPartsOfKnownTypes ()
- {
- var dcs = new DataContractSerializer (typeof (string));
- Assert.AreEqual (0, dcs.KnownTypes.Count, "KnownTypes #1");
- var dcjs = new DataContractJsonSerializer (typeof (string));
- Assert.AreEqual (0, dcjs.KnownTypes.Count, "KnownTypes #2");
- }
- [Test]
- public void ReadWriteNullObject ()
- {
- DataContractJsonSerializer dcjs = new DataContractJsonSerializer (typeof (string));
- using (MemoryStream ms = new MemoryStream ()) {
- dcjs.WriteObject (ms, null);
- ms.Position = 0;
- using (StreamReader sr = new StreamReader (ms)) {
- string data = sr.ReadToEnd ();
- Assert.AreEqual ("null", data, "WriteObject(stream,null)");
- ms.Position = 0;
- Assert.IsNull (dcjs.ReadObject (ms), "ReadObject(stream)");
- }
- };
- }
- object ReadWriteObject (Type type, object obj, string expected)
- {
- using (MemoryStream ms = new MemoryStream ()) {
- DataContractJsonSerializer dcjs = new DataContractJsonSerializer (type);
- dcjs.WriteObject (ms, obj);
- ms.Position = 0;
- using (StreamReader sr = new StreamReader (ms)) {
- Assert.AreEqual (expected, sr.ReadToEnd (), "WriteObject");
- ms.Position = 0;
- return dcjs.ReadObject (ms);
- }
- }
- }
- [Test]
- [Ignore ("Wrong test case. See bug #573691")]
- public void ReadWriteObject_Single_SpecialCases ()
- {
- Assert.IsTrue (Single.IsNaN ((float) ReadWriteObject (typeof (float), Single.NaN, "NaN")));
- Assert.IsTrue (Single.IsNegativeInfinity ((float) ReadWriteObject (typeof (float), Single.NegativeInfinity, "-INF")));
- Assert.IsTrue (Single.IsPositiveInfinity ((float) ReadWriteObject (typeof (float), Single.PositiveInfinity, "INF")));
- }
- [Test]
- [Ignore ("Wrong test case. See bug #573691")]
- public void ReadWriteObject_Double_SpecialCases ()
- {
- Assert.IsTrue (Double.IsNaN ((double) ReadWriteObject (typeof (double), Double.NaN, "NaN")));
- Assert.IsTrue (Double.IsNegativeInfinity ((double) ReadWriteObject (typeof (double), Double.NegativeInfinity, "-INF")));
- Assert.IsTrue (Double.IsPositiveInfinity ((double) ReadWriteObject (typeof (double), Double.PositiveInfinity, "INF")));
- }
- [Test]
- public void ReadWriteDateTime ()
- {
- var ms = new MemoryStream ();
- DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (Query));
- Query query = new Query () {
- StartDate = DateTime.SpecifyKind (new DateTime (2010, 3, 4, 5, 6, 7), DateTimeKind.Utc),
- EndDate = DateTime.SpecifyKind (new DateTime (2010, 4, 5, 6, 7, 8), DateTimeKind.Utc)
- };
- serializer.WriteObject (ms, query);
- Assert.AreEqual ("{\"StartDate\":\"\\/Date(1267679167000)\\/\",\"EndDate\":\"\\/Date(1270447628000)\\/\"}", Encoding.UTF8.GetString (ms.ToArray ()), "#1");
- ms.Position = 0;
- Console.WriteLine (new StreamReader (ms).ReadToEnd ());
- ms.Position = 0;
- var q = (Query) serializer.ReadObject(ms);
- Assert.AreEqual (query.StartDate, q.StartDate, "#2");
- Assert.AreEqual (query.EndDate, q.EndDate, "#3");
- }
- [DataContract(Name = "DateTest")]
- public class DateTest
- {
- [DataMember(Name = "should_have_value")]
- public DateTime? ShouldHaveValue { get; set; }
- }
- //
- // This tests both the extended format "number-0500" as well
- // as the nullable field in the structure
- [Test]
- public void BugXamarin163 ()
- {
- string json = @"{""should_have_value"":""\/Date(1277355600000)\/""}";
- byte[] bytes = global::System.Text.Encoding.UTF8.GetBytes(json);
- Stream inputStream = new MemoryStream(bytes);
-
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DateTest));
- DateTest t = serializer.ReadObject(inputStream) as DateTest;
- Assert.AreEqual (634129524000000000, t.ShouldHaveValue.Value.Ticks, "#1");
- }
- [Test]
- public void NullableFieldsShouldSupportNullValue ()
- {
- string json = @"{""should_have_value"":null}";
- var inputStream = new MemoryStream (Encoding.UTF8.GetBytes (json));
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DateTest));
- Console.WriteLine ("# serializer assembly: {0}", serializer.GetType ().Assembly.Location);
- DateTest t = serializer.ReadObject (inputStream) as DateTest;
- Assert.AreEqual (false, t.ShouldHaveValue.HasValue, "#2");
- }
-
- [Test]
- public void DeserializeNullMember ()
- {
- var ds = new DataContractJsonSerializer (typeof (ClassA));
- var stream = new MemoryStream ();
- var a = new ClassA ();
- ds.WriteObject (stream, a);
- stream.Position = 0;
- a = (ClassA) ds.ReadObject (stream);
- Assert.IsNull (a.B, "#1");
- }
- [Test]
- public void OnDeserializationMethods ()
- {
- var ds = new DataContractJsonSerializer (typeof (GSPlayerListErg));
- var obj = new GSPlayerListErg ();
- var ms = new MemoryStream ();
- ds.WriteObject (ms, obj);
- ms.Position = 0;
- ds.ReadObject (ms);
- Assert.IsTrue (GSPlayerListErg.A, "A");
- Assert.IsTrue (GSPlayerListErg.B, "B");
- Assert.IsTrue (GSPlayerListErg.C, "C");
- }
-
- [Test]
- public void WriteChar ()
- {
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof (CharTest));
- using (MemoryStream ms = new MemoryStream()) {
- serializer.WriteObject(ms, new CharTest ());
- ms.Position = 0L;
- using (StreamReader reader = new StreamReader(ms)) {
- reader.ReadToEnd();
- }
- }
- }
- [Test]
- public void DictionarySerialization ()
- {
- var dict = new MyDictionary<string,string> ();
- dict.Add ("key", "value");
- var serializer = new DataContractJsonSerializer (dict.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, dict);
- stream.Position = 0;
- Assert.AreEqual ("[{\"Key\":\"key\",\"Value\":\"value\"}]", new StreamReader (stream).ReadToEnd (), "#1");
- stream.Position = 0;
- dict = (MyDictionary<string,string>) serializer.ReadObject (stream);
- Assert.AreEqual (1, dict.Count, "#2");
- Assert.AreEqual ("value", dict ["key"], "#3");
- }
- [Test]
- public void ExplicitCustomDictionarySerialization ()
- {
- var dict = new MyExplicitDictionary<string,string> ();
- dict.Add ("key", "value");
- var serializer = new DataContractJsonSerializer (dict.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, dict);
- stream.Position = 0;
- Assert.AreEqual ("[{\"Key\":\"key\",\"Value\":\"value\"}]", new StreamReader (stream).ReadToEnd (), "#1");
- stream.Position = 0;
- dict = (MyExplicitDictionary<string,string>) serializer.ReadObject (stream);
- Assert.AreEqual (1, dict.Count, "#2");
- Assert.AreEqual ("value", dict ["key"], "#3");
- }
- [Test]
- public void Bug13485 ()
- {
- const string json = "{ \"Name\" : \"Test\", \"Value\" : \"ValueA\" }";
- string result = string.Empty;
- var serializer = new DataContractJsonSerializer (typeof (Bug13485Type));
- Bug13485Type entity;
- using (var stream = new MemoryStream (Encoding.UTF8.GetBytes (json)))
- entity = (Bug13485Type) serializer.ReadObject (stream);
- result = entity.GetValue;
- Assert.AreEqual ("ValueA", result, "#1");
- }
- [DataContract(Name = "UriTest")]
- public class UriTest
- {
- [DataMember(Name = "members")]
- public Uri MembersRelativeLink { get; set; }
- }
- [Test]
- public void Bug15169 ()
- {
- const string json = "{\"members\":\"foo/bar/members\"}";
- var serializer = new DataContractJsonSerializer (typeof (UriTest));
- UriTest entity;
- using (var stream = new MemoryStream (Encoding.UTF8.GetBytes (json)))
- entity = (UriTest) serializer.ReadObject (stream);
- Assert.AreEqual ("foo/bar/members", entity.MembersRelativeLink.ToString ());
- }
-
- #region Test methods for collection serialization
-
- [Test]
- public void TestArrayListSerialization ()
- {
- var collection = new ArrayListContainer ();
- var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
- var expectedItemsCount = 4;
-
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
- stream.Position = 0;
- Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
- stream.Position = 0;
- collection = (ArrayListContainer) serializer.ReadObject (stream);
-
- Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
- }
-
- [Test]
- [ExpectedException (typeof (InvalidDataContractException))]
- public void TestBitArraySerialization ()
- {
- var collection = new BitArrayContainer ();
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
- }
-
- [Test]
- public void TestHashtableSerialization ()
- {
- var collection = new HashtableContainer ();
- var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
-
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
- stream.Position = 0;
- Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
- }
-
- [Test]
- [ExpectedException (typeof (ArgumentException))]
- public void TestHashtableDeserialization ()
- {
- var collection = new HashtableContainer ();
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
-
- stream.Position = 0;
- serializer.ReadObject (stream);
- }
-
- [Test]
- [ExpectedException (typeof (InvalidDataContractException))]
- public void TestQueueSerialization ()
- {
- var collection = new QueueContainer ();
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
- }
-
- [Test]
- public void TestSortedListSerialization ()
- {
- var collection = new SortedListContainer ();
- var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
-
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
- stream.Position = 0;
- Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
- }
-
- [Test]
- [ExpectedException (typeof (ArgumentException))]
- public void TestSortedListDeserialization ()
- {
- var collection = new SortedListContainer ();
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
-
- stream.Position = 0;
- serializer.ReadObject (stream);
- }
-
- [Test]
- [ExpectedException (typeof (InvalidDataContractException))]
- public void TestStackSerialization ()
- {
- var collection = new StackContainer ();
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
- }
-
- [Test]
- public void TestEnumerableWithAddSerialization ()
- {
- var collection = new EnumerableWithAddContainer ();
- var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
- var expectedItemsCount = 4;
-
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
- stream.Position = 0;
- Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
- stream.Position = 0;
- collection = (EnumerableWithAddContainer) serializer.ReadObject (stream);
-
- Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
- }
-
- [Test]
- [ExpectedException (typeof (InvalidDataContractException))]
- public void TestEnumerableWithSpecialAddSerialization ()
- {
- var collection = new EnumerableWithSpecialAddContainer ();
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
- }
-
- [Test]
- public void TestHashSetSerialization ()
- {
- var collection = new GenericHashSetContainer ();
- var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
- var expectedItemsCount = 2;
-
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
- stream.Position = 0;
- Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
- stream.Position = 0;
- collection = (GenericHashSetContainer) serializer.ReadObject (stream);
-
- Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
- }
-
- [Test]
- public void TestLinkedListSerialization ()
- {
- var collection = new GenericLinkedListContainer ();
- var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
- var expectedItemsCount = 4;
-
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
- stream.Position = 0;
- Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
- stream.Position = 0;
- collection = (GenericLinkedListContainer) serializer.ReadObject (stream);
-
- Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
- }
-
- [Test]
- [ExpectedException (typeof (InvalidDataContractException))]
- public void TestGenericQueueSerialization ()
- {
- var collection = new GenericQueueContainer ();
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
- }
-
- [Test]
- [ExpectedException (typeof (InvalidDataContractException))]
- public void TestGenericStackSerialization ()
- {
- var collection = new GenericStackContainer ();
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
- }
-
- [Test]
- public void TestGenericDictionarySerialization ()
- {
- var collection = new GenericDictionaryContainer ();
- var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
-
- stream.Position = 0;
- Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
- }
-
- [Test]
- [ExpectedException (typeof (ArgumentException))]
- public void TestGenericDictionaryDeserialization ()
- {
- var collection = new GenericDictionaryContainer ();
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
-
- stream.Position = 0;
- serializer.ReadObject (stream);
- }
-
- [Test]
- public void TestGenericSortedListSerialization ()
- {
- var collection = new GenericSortedListContainer ();
- var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
-
- stream.Position = 0;
- Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
- }
-
- [Test]
- [ExpectedException (typeof (ArgumentException))]
- public void TestGenericSortedListDeserialization ()
- {
- var collection = new GenericSortedListContainer ();
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
-
- stream.Position = 0;
- serializer.ReadObject (stream);
- }
-
- [Test]
- public void TestGenericSortedDictionarySerialization ()
- {
- var collection = new GenericSortedDictionaryContainer ();
- var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
-
- stream.Position = 0;
- Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
- }
-
- [Test]
- [ExpectedException (typeof (ArgumentException))]
- public void TestGenericSortedDictionaryDeserialization ()
- {
- var collection = new GenericSortedDictionaryContainer ();
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
-
- stream.Position = 0;
- serializer.ReadObject (stream);
- }
-
- [Test]
- public void TestGenericEnumerableWithAddSerialization ()
- {
- var collection = new GenericEnumerableWithAddContainer ();
- var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
- var expectedItemsCount = 4;
-
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
- stream.Position = 0;
- Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
- stream.Position = 0;
- collection = (GenericEnumerableWithAddContainer) serializer.ReadObject (stream);
-
- Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
- }
-
- [Test]
- [ExpectedException (typeof (InvalidDataContractException))]
- public void TestGenericEnumerableWithSpecialAddSerialization ()
- {
- var collection = new GenericEnumerableWithSpecialAddContainer ();
- var serializer = new DataContractJsonSerializer (collection.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, collection);
- }
-
- [Test]
- [ExpectedException (typeof (InvalidDataContractException))]
- public void TestNonCollectionGetOnlyProperty ()
- {
- var o = new NonCollectionGetOnlyContainer ();
- var serializer = new DataContractJsonSerializer (o.GetType ());
- var stream = new MemoryStream ();
- serializer.WriteObject (stream, o);
- }
-
- // properly deserialize object with a polymorphic property (known derived type)
- [Test]
- public void Bug23058()
- {
- string serializedObj = @"{""PolymorphicProperty"":{""__type"":""KnownDerivedType:#MonoTests.System.Runtime.Serialization.Json"",""BaseTypeProperty"":""Base"",""DerivedProperty"":""Derived 1""},""Name"":""Parent2""}";
- ParentType deserializedObj = Deserialize<ParentType> (serializedObj);
- Assert.AreEqual (deserializedObj.PolymorphicProperty.GetType ().FullName, "MonoTests.System.Runtime.Serialization.Json.KnownDerivedType");
- Assert.AreEqual (deserializedObj.PolymorphicProperty.BaseTypeProperty, "Base");
- Assert.AreEqual ((deserializedObj.PolymorphicProperty as KnownDerivedType).DerivedProperty, "Derived 1");
- Assert.AreEqual (deserializedObj.Name, "Parent2");
- }
- // properly deserialize object with a polymorphic property (base type with __type hint)
- [Test]
- public void DeserializeBaseTypePropHint()
- {
- string serializedObj = @"{""PolymorphicProperty"":{""__type"":""BaseType:#MonoTests.System.Runtime.Serialization.Json"",""BaseTypeProperty"":""Base""},""Name"":""Parent2""}";
- ParentType deserializedObj = Deserialize<ParentType> (serializedObj);
- Assert.AreEqual (deserializedObj.PolymorphicProperty.GetType ().FullName, "MonoTests.System.Runtime.Serialization.Json.BaseType");
- Assert.AreEqual (deserializedObj.PolymorphicProperty.BaseTypeProperty, "Base");
- }
- // properly deserialize object with a polymorphic property (base type with __type hint)
- [Test]
- public void DeserializeBaseTypePropNoHint()
- {
- string serializedObj = @"{""PolymorphicProperty"":{""BaseTypeProperty"":""Base""},""Name"":""Parent2""}";
- ParentType deserializedObj = Deserialize<ParentType> (serializedObj);
- Assert.AreEqual (deserializedObj.PolymorphicProperty.GetType ().FullName, "MonoTests.System.Runtime.Serialization.Json.BaseType");
- Assert.AreEqual (deserializedObj.PolymorphicProperty.BaseTypeProperty, "Base");
- }
- // properly fail deserializing object with a polymorphic property (unknown derived type)
- [ExpectedException (typeof (SerializationException))]
- [Test]
- public void FailDeserializingUnknownTypeProp()
- {
- string serializedObj = @"{""PolymorphicProperty"":{""__type"":""UnknownDerivedType:#MonoTests.System.Runtime.Serialization.Json"",""BaseTypeProperty"":""Base"",""DerivedProperty"":""Derived 1""},""Name"":""Parent2""}";
- ParentType deserializedObj = Deserialize<ParentType> (serializedObj);
- }
-
- #endregion
- }
-
- public class CharTest
- {
- public char Foo;
- }
- public class TestData
- {
- public string Foo { get; set; }
- public string Bar { get; set; }
- internal string Baz { get; set; }
- }
- public enum Colors {
- Red, Green, Blue
- }
- [DataContract (Name = "_ColorsWithDC")]
- public enum ColorsWithDC {
- [EnumMember (Value = "_Red")]
- Red,
- [EnumMember]
- Green,
- Blue
- }
- public enum ColorsEnumMemberNoDC {
- [EnumMember (Value = "_Red")]
- Red,
- [EnumMember]
- Green,
- Blue
- }
- [DataContract]
- public class DCWithEnum {
- [DataMember (Name = "_colors")]
- public Colors colors;
- }
- [DataContract]
- public class DCEmpty
- {
- // serializer doesn't touch it.
- public string Foo = "TEST";
- }
- [DataContract]
- public class DCSimple1
- {
- [DataMember]
- public string Foo = "TEST";
- }
- [DataContract]
- public class DCHasNonDC
- {
- [DataMember]
- public NonDC Hoge= new NonDC ();
- }
- public class NonDC
- {
- public string Whee = "whee!";
- }
- [DataContract]
- public class DCHasSerializable
- {
- [DataMember]
- public SimpleSer1 Ser = new SimpleSer1 ();
- }
- [DataContract (Name = "Foo")]
- public class DCWithName
- {
- [DataMember (Name = "FooMember")]
- public string DMWithName = "value";
- }
- [DataContract (Name = "")]
- public class DCWithEmptyName
- {
- [DataMember]
- public string Foo;
- }
- [DataContract (Name = null)]
- public class DCWithNullName
- {
- [DataMember]
- public string Foo;
- }
- [DataContract (Namespace = "")]
- public class DCWithEmptyNamespace
- {
- [DataMember]
- public string Foo;
- }
- [Serializable]
- public class SimpleSer1
- {
- public string Doh = "doh!";
- }
- public class Wrapper
- {
- [DataContract]
- public class DCWrapped
- {
- }
- }
- [DataContract]
- public class CollectionContainer
- {
- Collection<string> items = new Collection<string> ();
- [DataMember]
- public Collection<string> Items {
- get { return items; }
- }
- }
- [CollectionDataContract]
- public class DataCollection<T> : Collection<T>
- {
- }
- [DataContract]
- public class DataCollectionContainer
- {
- DataCollection<string> items = new DataCollection<string> ();
- [DataMember]
- public DataCollection<string> Items {
- get { return items; }
- }
- }
- [DataContract]
- class SerializeNonDCArrayType
- {
- [DataMember]
- public NonDCItem [] IPAddresses = new NonDCItem [0];
- }
- public class NonDCItem
- {
- public byte [] Data { get; set; }
- }
- [DataContract]
- public class VerifyObjectNameTestData
- {
- [DataMember]
- string Member1 = "foo";
- }
- [Serializable]
- public class KeyValueTestData {
- public List<KeyValuePair<string,string>> TestData = new List<KeyValuePair<string,string>>();
- }
- [DataContract] // bug #586169
- public class Query
- {
- [DataMember (Order=1)]
- public DateTime StartDate { get; set; }
- [DataMember (Order=2)]
- public DateTime EndDate { get; set; }
- }
- public class ClassA {
- public ClassB B { get; set; }
- }
- public class ClassB
- {
- }
- public class GSPlayerListErg
- {
- public GSPlayerListErg ()
- {
- Init ();
- }
- void Init ()
- {
- C = true;
- ServerTimeUTC = DateTime.SpecifyKind (DateTime.MinValue, DateTimeKind.Utc);
- }
- [OnDeserializing]
- public void OnDeserializing (StreamingContext c)
- {
- A = true;
- Init ();
- }
- [OnDeserialized]
- void OnDeserialized (StreamingContext c)
- {
- B = true;
- }
- public static bool A, B, C;
- [DataMember (Name = "T")]
- public long CodedServerTimeUTC { get; set; }
- public DateTime ServerTimeUTC { get; set; }
- }
- #region polymorphism test helper classes
- [DataContract]
- [KnownType (typeof (KnownDerivedType))]
- public class ParentType
- {
- [DataMember]
- public string Name { get; set; }
- [DataMember]
- public BaseType PolymorphicProperty { get; set; }
- }
- [DataContract]
- public class BaseType
- {
- [DataMember]
- public string BaseTypeProperty { get; set; }
- }
- [DataContract]
- public class KnownDerivedType : BaseType
- {
- [DataMemberAttribute]
- public string DerivedProperty { get; set; }
- }
- [DataContract]
- public class UnknownDerivedType : BaseType
- {
- [DataMember]
- public string DerivedProperty { get; set; }
- }
- #endregion
- }
- [DataContract]
- class GlobalSample1
- {
- }
- public class MyDictionary<K, V> : System.Collections.Generic.IDictionary<K, V>
- {
- Dictionary<K,V> dic = new Dictionary<K,V> ();
- public void Add (K key, V value)
- {
- dic.Add (key, value);
- }
- public bool ContainsKey (K key)
- {
- return dic.ContainsKey (key);
- }
- public ICollection<K> Keys {
- get { return dic.Keys; }
- }
- public bool Remove (K key)
- {
- return dic.Remove (key);
- }
- public bool TryGetValue (K key, out V value)
- {
- return dic.TryGetValue (key, out value);
- }
- public ICollection<V> Values {
- get { return dic.Values; }
- }
- public V this [K key] {
- get { return dic [key]; }
- set { dic [key] = value; }
- }
- IEnumerator IEnumerable.GetEnumerator ()
- {
- return dic.GetEnumerator ();
- }
- ICollection<KeyValuePair<K,V>> Coll {
- get { return (ICollection<KeyValuePair<K,V>>) dic; }
- }
- public void Add (KeyValuePair<K, V> item)
- {
- Coll.Add (item);
- }
- public void Clear ()
- {
- dic.Clear ();
- }
- public bool Contains (KeyValuePair<K, V> item)
- {
- return Coll.Contains (item);
- }
- public void CopyTo (KeyValuePair<K, V> [] array, int arrayIndex)
- {
- Coll.CopyTo (array, arrayIndex);
- }
- public int Count {
- get { return dic.Count; }
- }
- public bool IsReadOnly {
- get { return Coll.IsReadOnly; }
- }
- public bool Remove (KeyValuePair<K, V> item)
- {
- return Coll.Remove (item);
- }
- public IEnumerator<KeyValuePair<K, V>> GetEnumerator ()
- {
- return Coll.GetEnumerator ();
- }
- }
- public class MyExplicitDictionary<K, V> : IDictionary<K, V> {
- Dictionary<K,V> dic = new Dictionary<K,V> ();
- public void Add (K key, V value)
- {
- dic.Add (key, value);
- }
- public bool ContainsKey (K key)
- {
- return dic.ContainsKey (key);
- }
- ICollection<K> IDictionary<K, V>.Keys {
- get { return dic.Keys; }
- }
- public bool Remove (K key)
- {
- return dic.Remove (key);
- }
- public bool TryGetValue (K key, out V value)
- {
- return dic.TryGetValue (key, out value);
- }
- ICollection<V> IDictionary<K, V>.Values {
- get { return dic.Values; }
- }
- public V this [K key] {
- get { return dic [key]; }
- set { dic [key] = value; }
- }
- IEnumerator IEnumerable.GetEnumerator ()
- {
- return dic.GetEnumerator ();
- }
- ICollection<KeyValuePair<K,V>> Coll {
- get { return (ICollection<KeyValuePair<K,V>>) dic; }
- }
- public void Add (KeyValuePair<K, V> item)
- {
- Coll.Add (item);
- }
- public void Clear ()
- {
- dic.Clear ();
- }
- public bool Contains (KeyValuePair<K, V> item)
- {
- return Coll.Contains (item);
- }
- public void CopyTo (KeyValuePair<K, V> [] array, int arrayIndex)
- {
- Coll.CopyTo (array, arrayIndex);
- }
- public int Count {
- get { return dic.Count; }
- }
- public bool IsReadOnly {
- get { return Coll.IsReadOnly; }
- }
- public bool Remove (KeyValuePair<K, V> item)
- {
- return Coll.Remove (item);
- }
- public IEnumerator<KeyValuePair<K, V>> GetEnumerator ()
- {
- return Coll.GetEnumerator ();
- }
- }
- [DataContract]
- public class Bug13485Type
- {
- [DataMember]
- public string Name { get; set; }
- [DataMember (Name = "Value")]
- private string Value { get; set; }
- public string GetValue { get { return this.Value; } }
- }
- #region Test classes for Collection serialization
- [DataContract]
- public abstract class CollectionContainer <V>
- {
- V items;
- [DataMember]
- public V Items
- {
- get {
- if (items == null) items = Init ();
- return items;
- }
- }
-
- public CollectionContainer ()
- {
- Init ();
- }
-
- protected abstract V Init ();
- }
-
- [DataContract]
- public class ArrayListContainer : CollectionContainer<ArrayList> {
- protected override ArrayList Init ()
- {
- return new ArrayList { "banana", "apple" };
- }
- }
-
- [DataContract]
- public class BitArrayContainer : CollectionContainer<BitArray> {
- protected override BitArray Init ()
- {
- return new BitArray (new [] { false, true });
- }
- }
-
- [DataContract]
- public class HashtableContainer : CollectionContainer<Hashtable> {
- protected override Hashtable Init ()
- {
- var ht = new Hashtable ();
- ht.Add ("key1", "banana");
- ht.Add ("key2", "apple");
- return ht;
- }
- }
-
- [DataContract]
- public class QueueContainer : CollectionContainer<Queue> {
- protected override Queue Init ()
- {
- var q = new Queue ();
- q.Enqueue ("banana");
- q.Enqueue ("apple");
- return q;
- }
- }
-
- [DataContract]
- public class SortedListContainer : CollectionContainer<SortedList> {
- protected override SortedList Init ()
- {
- var l = new SortedList ();
- l.Add ("key1", "banana");
- l.Add ("key2", "apple");
- return l;
- }
- }
-
- [DataContract]
- public class StackContainer : CollectionContainer<Stack> {
- protected override Stack Init ()
- {
- var s = new Stack ();
- s.Push ("banana");
- s.Push ("apple");
- return s;
- }
- }
- public class EnumerableWithAdd : IEnumerable
- {
- private ArrayList items;
- public EnumerableWithAdd()
- {
- items = new ArrayList();
- }
- public IEnumerator GetEnumerator()
- {
- return items.GetEnumerator();
- }
- public void Add(object value)
- {
- items.Add(value);
- }
- public int Count
- {
- get {
- return items.Count;
- }
- }
- }
- public class EnumerableWithSpecialAdd : IEnumerable
- {
- private ArrayList items;
- public EnumerableWithSpecialAdd()
- {
- items = new ArrayList();
- }
- public IEnumerator GetEnumerator()
- {
- return items.GetEnumerator();
- }
- public void Add(object value, int index)
- {
- items.Add(value);
- }
- public int Count
- {
- get
- {
- return items.Count;
- }
- }
- }
- [DataContract]
- public class EnumerableWithAddContainer : CollectionContainer<EnumerableWithAdd>
- {
- protected override EnumerableWithAdd Init()
- {
- var s = new EnumerableWithAdd();
- s.Add ("banana");
- s.Add ("apple");
- return s;
- }
- }
- [DataContract]
- public class EnumerableWithSpecialAddContainer : CollectionContainer<EnumerableWithSpecialAdd>
- {
- protected override EnumerableWithSpecialAdd Init()
- {
- var s = new EnumerableWithSpecialAdd();
- s.Add("banana", 0);
- s.Add("apple", 0);
- return s;
- }
- }
- [DataContract]
- public class GenericDictionaryContainer : CollectionContainer<Dictionary<string, string>> {
- protected override Dictionary<string, string> Init ()
- {
- var d = new Dictionary<string, string> ();
- d.Add ("key1", "banana");
- d.Add ("key2", "apple");
- return d;
- }
- }
- [DataContract]
- public class GenericHashSetContainer : CollectionContainer<HashSet<string>> {
- protected override HashSet<string> Init ()
- {
- return new HashSet<string> { "banana", "apple" };
- }
- }
- [DataContract]
- public class GenericLinkedListContainer : CollectionContainer<LinkedList<string>> {
- protected override LinkedList<string> Init ()
- {
- var l = new LinkedList<string> ();
- l.AddFirst ("apple");
- l.AddFirst ("banana");
- return l;
- }
- }
- [DataContract]
- public class GenericListContainer : CollectionContainer<List<string>> {
- protected override List<string> Init ()
- {
- return new List<string> { "banana", "apple" };
- }
- }
- [DataContract]
- public class GenericQueueContainer : CollectionContainer<Queue<string>> {
- protected override Queue<string> Init ()
- {
- var q = new Queue<string> ();
- q.Enqueue ("banana");
- q.Enqueue ("apple" );
- return q;
- }
- }
- [DataContract]
- public class GenericSortedDictionaryContainer : CollectionContainer<SortedDictionary<string, string>> {
- protected override SortedDictionary<string, string> Init ()
- {
- var d = new SortedDictionary<string, string> ();
- d.Add ("key1", "banana");
- d.Add ("key2", "apple");
- return d;
- }
- }
- [DataContract]
- public class GenericSortedListContainer : CollectionContainer<SortedList<string, string>> {
- protected override SortedList<string, string> Init ()
- {
- var d = new SortedList<string, string> ();
- d.Add ("key1", "banana");
- d.Add ("key2", "apple");
- return d;
- }
- }
- [DataContract]
- public class GenericStackContainer : CollectionContainer<Stack<string>> {
- protected override Stack<string> Init ()
- {
- var s = new Stack<string> ();
- s.Push ("banana");
- s.Push ("apple" );
- return s;
- }
- }
- public class GenericEnumerableWithAdd : IEnumerable<string>
- {
- private List<string> items;
- public GenericEnumerableWithAdd()
- {
- items = new List<string>();
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return items.GetEnumerator ();
- }
- public IEnumerator<string> GetEnumerator()
- {
- return items.GetEnumerator ();
- }
- public void Add(string value)
- {
- items.Add(value);
- }
- public int Count
- {
- get {
- return items.Count;
- }
- }
- }
- public class GenericEnumerableWithSpecialAdd : IEnumerable<string>
- {
- private List<string> items;
- public GenericEnumerableWithSpecialAdd()
- {
- items = new List<string>();
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return items.GetEnumerator ();
- }
- public IEnumerator<string> GetEnumerator()
- {
- return items.GetEnumerator ();
- }
- public void Add(string value, int index)
- {
- items.Add(value);
- }
- public int Count
- {
- get
- {
- return items.Count;
- }
- }
- }
- [DataContract]
- public class GenericEnumerableWithAddContainer : CollectionContainer<GenericEnumerableWithAdd>
- {
- protected override GenericEnumerableWithAdd Init()
- {
- var s = new GenericEnumerableWithAdd();
- s.Add ("banana");
- s.Add ("apple");
- return s;
- }
- }
- [DataContract]
- public class GenericEnumerableWithSpecialAddContainer : CollectionContainer<GenericEnumerableWithSpecialAdd>
- {
- protected override GenericEnumerableWithSpecialAdd Init()
- {
- var s = new GenericEnumerableWithSpecialAdd();
- s.Add("banana", 0);
- s.Add("apple", 0);
- return s;
- }
- }
- [DataContract]
- public class NonCollectionGetOnlyContainer
- {
- string _test = "my string";
-
- [DataMember]
- public string MyString {
- get {
- return _test;
- }
- }
- }
- #endregion
|