Marwan Tushyeh
Marwan Tushyeh

Reputation: 1525

Serialization Exception : data contract is not expected

I receive the following exception message while serializing an object to XML:

{"Type 'Alerter.EmailSender' with data contract name  'EmailSender:http://schemas.datacontract.org/2004/07/Alerter' is not expected. Consider using a DataContractResolver 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 DataContractSerializer."}

This is the class that i am trying to serialize an object of it to an XML File:

namespace Alerter
{
  [DataContract]
  public class EmailSender : IAction
  {
    private EmailSetting _emailSetting;
    private SmtpClient _smtpClient;
    [DataMember]
    public bool IncludeFullDetails
    {
        get;
        set;
    }
    [DataMember]
    public string[] Receivers
    {
        get;
        set;
    }

    public EmailSender()
    {
        _emailSetting = new EmailSetting();
        SetupClient();
    }

    private void SetupClient()
    {
        // Some Logic
    }


    public void Report(LogDictionary logDictionary)
    {
       // Some Logic
    }
   }
 }

That's the code i use for serialization:

 using (FileStream writer = new FileStream(fileName, FileMode.Create))
        {
            DataContractSerializer ser =
                new DataContractSerializer(typeof(List<Rule>));
            ser.WriteObject(writer, list);
        }

I appreciate your help.

Upvotes: 1

Views: 4224

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

Make sure you have specified this EmailSender class as a known type to your serializer using the proper constructor:

DataContractSerializer ser = new DataContractSerializer(
    typeof(List<Rule>), 
    new[] { typeof(EmailSender) }
);
ser.WriteObject(writer, list);

The reason you need this is because probably in the object graph of the Rule class you only have used the IAction interface for all members and the serializer doesn't even know about the existence of the EmailSender implementation.

You should do the same for all other types which are not statically known in the Rule object graph.

Upvotes: 2

Related Questions