0

I’m using DataContractSerializer for xml serialization. While It tries to serialize SubClass, throws the below error

'SubClass:http://schemas.datacontract.org/2004/07/SubClass ' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or 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 the serializer

So I have added “SubClass” in KnownTypeAttribute to resolve this. But it does not work.

I have visited the below article for this issue, "Type not expected", using DataContractSerializer - but it's just a simple class, no funny stuff?

Please anyone let me know how to resolve this?

[DataContract(Name = "BaseClass"]
[KnownType("Types")]
public class BaseClass
{
    [DataMember]
    public bool IsSerialized{get;set;}

     public static Type[] Types()
     {
         return MainClass.Types();
     }
}
[DataContract(Name = "SubClass"]
public class SubClass:BaseClass //Getting error for this class
{
    [DataMember]
    public string Format {get;set;}
}

public class MainClass
{
    public MainClass()
    {
        var ser = new DataContractSerializer(typeof(BaseClass));
        MemoryStream stream = new MemoryStream();
        ser.WriteObject(stream,new BaseClass());
    }
    public static Type[] Types()
    {
         return new Type[]{typeof(BaseClass),typeof(SubClass)};
    }
}
Prithiv
  • 504
  • 5
  • 20
  • `So I have added “SubClass” in KnownTypeAttribute to resolve this` You have added `Types` not `SubClass` – Gusman Feb 01 '18 at 12:19
  • Sorry i can't understand. please explain it clearly. – Prithiv Feb 01 '18 at 12:22
  • `[KnownType("Types")]` -> `[KnownType("SubClass")]` – Gusman Feb 01 '18 at 12:22
  • public static Type[] Types() { return new Type[]{typeof(BaseClass),typeof(SubClass)}; } here i have added "SubClass" for KnownTypeAttribute – Prithiv Feb 01 '18 at 12:23
  • That's not on your post – Gusman Feb 01 '18 at 12:23
  • [DataContract(Name = "SubClass"] [KnownType(typeof(SubClass))] public class SubClass:BaseClass { [DataMember] public string Format {get;set;} } i also tried this. – Prithiv Feb 01 '18 at 12:24
  • but its not working – Prithiv Feb 01 '18 at 12:26
  • 1
    As far as I can tell, using the code in your question there is no issue (other than some syntax errors on your `DataContract` attributes, which are both missing a `)` before the `]`) - it runs fine without throwing any exceptions. Even changing it to serialize an instance of `SubClass` instead of `BaseClass` as it's currently doing in your code snippet doesn't result in an exception. Please provide the code that *doesn't* work, ideally that you have confirmed exhibits the issue when run *exactly as provided*. – Iridium Feb 01 '18 at 12:44

0 Answers0