0

I Have a email class as

public class EmailInfo
{
    public MailAddress SenderEmailAddress { get; set; }
    public MailAddressCollection ReceiverEmailAddress { get; set; }
    public MailAddressCollection CCEmailAddress { get; set; }
    public MailAddressCollection BCCEmailAddress { get; set; }
    public AttachmentCollection Attachment { get; set; }
    public string Subject { get; set; }
    public DateTime EmailDate { get; set; }
}

and When I Try to serialize list of Type EmailInfo. I get the the Following error

Type 'System.Collections.Generic.List`1[[Darena.EmailParser.EmailInfo, Darena.EmailParser, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name 'ArrayOfEmailInfo:http://schemas.datacontract.org/2004/07/Darena.EmailParser' 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.

I am Serializing using

 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(EmailInfo));
        MemoryStream ms = new MemoryStream();
        ser.WriteObject(ms, emailInfos);
        string jsonString = Encoding.UTF8.GetString(ms.ToArray());
        ms.Close();
        return jsonString;

Any help

dbc
  • 104,963
  • 20
  • 228
  • 340
Pankaj
  • 1,446
  • 4
  • 19
  • 31

2 Answers2

0

The types you want to serialize have to be serializable.

For DataContractJsonSerializer it means you have to decorate your class (EmailInfo) with DataContract attribute and its members (just those you want to include into serialized string) with DataMember attribute.

However, in your case you are referencing 3rd party types, like MailAddress and other types that are not serializable so you would have to provide some type of custom serialization and its quite limited for DataContractJsonSerializer.

Have a look at Json.NET library, which provides much more flexibility for JSON serialization, eg. JsonConverter. You'll find good examples at this web site.

eXavier
  • 4,821
  • 4
  • 35
  • 57
0

The List cannot support the serializetion. You can use the object[] instead of List.

Hank
  • 27
  • 2