views:

483

answers:

1

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?

+2  A: 

If you add the KnownType attribute (from System.Runtime.Serialization) to the base class for the child class then it will work:

[KnownType(typeof(Child))]
class Base
{}

class Child : Base
{}

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).

Bryant
You're correct. Works the same with XML serialization.
Rob Prouse
Unfortunately the base class is in a separate namespace to the child class. And the base class namespace has no knowledge of the child class namespace.
Mark Ingram
Then there is really no way to do this.
Bryant