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

2

5

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

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.

Mage answered 13/5, 2015 at 9:12 Comment(0)
D
2

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;
    ...
}
Dinnerware answered 13/5, 2015 at 9:18 Comment(2)
Why would [KnownType(typeof(int))] help when? System.Int32 is always a known type.Breastsummer
I'm afraid that you both are right,partially. Indeed, KnownType is missing there. I'll put details in an answer.Mage
M
7

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.

UPDATE: Because the upper link seems not working anymore, here is a link to an archived webpage: https://web.archive.org/web/20160304050721/http://blogs.msdn.com/b/youssefm/archive/2009/04/21/understanding-known-types.aspx

Mage answered 13/5, 2015 at 12:20 Comment(2)
Sorry to everyone who was trying to help, because at first I wrote int Value, but in fact that was an Object, and that was the most important part in my question.Mage
The link is dead. It can be simpipied as [DataContract, KnowType(typeof(...))].Copartner
D
2

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;
    ...
}
Dinnerware answered 13/5, 2015 at 9:18 Comment(2)
Why would [KnownType(typeof(int))] help when? System.Int32 is always a known type.Breastsummer
I'm afraid that you both are right,partially. Indeed, KnownType is missing there. I'll put details in an answer.Mage

© 2022 - 2024 — McMap. All rights reserved.