Exception during the serialization - Type with data contract name is not expected

I have this classes:

[DataContract]
class ClassA
{ [DataMember] public Object Value; // and this can be of ClassB or some primitive type. ...
}
[DataContract]
class ClassB : IEnumerable<KeyValuePair<String, ClassA>>
{ [DataMember] private Dictionary<String, ClassA> dictionary; ...
}

but getting this exception when serialization take place:

Type 'MyNamespace.ClassA' with data contract name 'ClassA:' 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.

I feel that I should use KnownType attribute, but I can't figure out how, because I am not owning IEnumerable<T>.

Can anyone help? Thanks.

2 Answers

I've finally get it right. The solution is quite simple, Value from first class is of type Object, and the serializer have to know which types will be boxed into that Object.

So ClassA should be declared as:

[DataContract]
[KnownType(typeof(ClassA)]
[KnownType(typeof(ClassB)]
class ClassA
{ [DataMember] public Object Value; // ClassA or ClassB or some primitive type. ...
}

This document here really helped clarifying what is KnownType.

1

Try the following:

[DataContract]
[KnownType(typeof(int))]
// Same way add here all the types that you are using in your class A.
class ClassA
{ [DataMember] public int Value; ...
}
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like