Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataContractSerializer and Known Types

I am serializing an object in code (not via a WCF call), and I am getting a little hung up with known types (I have used them with WCF, but not with the DataContract serializer as a "stand-alone" serializer)

I get an exception when I run the code below. I expected it to run without error because I supplied Known Types. What am I getting wrong here?


public class Parent {}
public class Child: Parent {}

// the code -- serialized is a serialized Child
// type is typeof(Parent) (I know it works if I pass typeof(Child), but isn't that what Known Types is all about??

// passing the known types seems to make no difference -- this only works if I pass typeof(Child) as the first param
var serializer = new DataContractSerializer(parentType, new Type[] {typeof(Child)});
object test = serializer.ReadObject(serialized);

like image 530
JMarsch Avatar asked Dec 17 '22 03:12

JMarsch


1 Answers

Ok, so I'm having one of those days where I keep answering myself. The problme was not with the deserialization, it was in the serialization -- you must create the serializer with the same base type as the deserializer (I had created the serializer based upon the child type). For what it's worth, working code is below:


{
            var child = new Child();
            // here is where I went wrong before -- I used typeof(Child), with no known types to serialize
            var serializer = new DataContractSerializer(typeof(Parent), new Type[] { typeof(Child) });
            var stream = new MemoryStream();
            serializer.WriteObject(stream, child);
            stream.Position = 0;
            serializer = new DataContractSerializer(typeof(Parent), new Type[] { typeof(Child) });
            object test = serializer.ReadObject(stream);
            stream.Dispose();
            Console.WriteLine(test.ToString());
            Console.ReadLine();
}

like image 126
JMarsch Avatar answered Dec 18 '22 16:12

JMarsch