You can add KnownTypeAttribute to ObjectToSerialize so that the serializer knows what types to expect:
[DataContract] [KnownType(typeof(Aspirate))] [KnownType(typeof(Dispense))] public class ObjectToSerialize { .... }
I understand that the Aspirate and Dispense classes Aspirate derived from CompositeNode ? This is not clear from your sample code.
You have an error in the code:
get {return this.CompositeNode;}
it should be:
get {return this.compNode;}
Update: in response to your question in the comments: you should initialize the collection inside the ObjectToSerialize constructor:
public ObjectToSerialize() { this.compNode = new List<CompositeNode>(); }
Update 2: Wrong line:
ser.WriteObject(stream1, cn.CompositeNode);
It should be:
ser.WriteObject(stream1, cn);
By the way, you can simply write this:
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ObjectToSerialize));
You have already defined known types using attributes. Adding known types to the constructor is redundant.
source share