I have the following structure:
class Base { } class Child : Base { }
When I try to do the following:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Base)); serializer.WriteObject(stream, data);
It fails with the error message:
Type ‘MyNamespace.Child’ with data contract name ‘Child:http://schemas.datacontract.org/2004/07/MyNamespace‘ is not expected. Add any types not known statically to the list of known types – for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
Does anyone know how to correctly serialize just the child class?
If you add the KnownType attribute (from System.Runtime.Serialization) to the base class for the child class then it will work:
This is needed because the serializer doesn’t load your child type when you set it up to serialize the base class (at least this is my understanding).