2

我有两个班级:ServiceTriggerServiceCalendar

当我序列化model.Triggers时,我收到一个异常消息:

无法序列化类型为
'System.Collections.Generic.IEnumerable`1[[yyyy.ServiceCalendar, yyy.ChangeAD, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' 的成员 'yyy.ServiceTrigger.ServiceDaysOfWeek',
请参阅内部异常了解更多详情。"}

我创建了一个IEnumerable<ServiceTrigger>

IEnumerable<ServiceTrigger> serviceTriggers = model.Triggers;
XDocument xDoc = SerializationUtil.Serialize(model.Triggers);

头等舱是这样的:

[DataContract]
public class ServiceTrigger
{   
    [DataMember(Name = "triggerID")]
    public long TriggerID { get; set; }

    [DataMember(Name = "name")]
    public string Name { get; set; }

    [DataMember(Name = "dateStart")]
    public string DateStart { get; set; }

    [DataMember(Name = "code")]
    public string Code { get; set; }

    [DataMember(Name = "isActive")]
    public bool IsActive { get; set; }

    [DataMember(Name = "dateFrom")]
    public string DateFrom { get; set; }

    [DataMember(Name = "dateTo")]
    public string DateTo { get; set; }  

    [DataMember(Name = "currentState")]
    public string CurrentState { get; set; }

    [DataMember(Name = "daysOfWeek")]
    public IEnumerable<ServiceCalendar> ServiceDaysOfWeek { get; set; } 

    [DataMember(Name = "monthsOfYear")]
    public IEnumerable<ServiceCalendar> MonthsOfYear { get; set; }

    [DataMember(Name = "daysOfMonth")]
    public IEnumerable<ServiceCalendar> DaysOfMonth { get; set; } 
}

二等舱是这样的:

[DataContract]
public class Calendar
{
    [DataMember(Name = "id")]
    public int Id { get; set; }

    [DataMember(Name = "name")]
    public string Name { get; set; }

    [DataMember(Name = "code")]
    public string Code { get; set; }

    [DataMember(Name = "isActive")]
    public bool IsActive { get; set; }
)

我的序列化类是这样的:

public static class SerializationUtil
{
    public static T Deserialize<T>(XDocument doc)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

        using (var reader = doc.Root.CreateReader())
        {
            return (T)xmlSerializer.Deserialize(reader);
        }
    }

    public static XDocument Serialize(this object obj)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());

        XDocument doc = new XDocument();
        using (var writer = doc.CreateWriter())
        {
            xmlSerializer.Serialize(writer, obj);
        }

        return doc;
    }
}
4

1 回答 1

4

您不能序列化接口。您需要使用实际对象,例如List<ServiceCalendar>.

另请注意,ServiceCalendar需要一个不带参数的默认构造函数,以便XmlSerializer在反序列化时创建它。这仅在您添加带有参数的自定义构造函数时才重要。如果您根本没有构造函数,则默认构造函数已经存在。

例子:

public class ServiceCalendar {
    // this is required for deserialization if a .ctor with parameters is present.
    public ServiceCalendar() { }

    public ServiceCalendar(int id) {
        this.id = id;
    }
}

否则你会得到一个类似的异常

没有为ServiceCalendar类型定义无参数构造函数

于 2013-04-12T14:23:23.600 回答