我有两个课程:ServiceTrigger
和ServiceCalendar
。
当我序列化model.Triggers
时,我得到一个例外说:
无法序列化类型为
的成员'yyy.ServiceTrigger.ServiceDaysOfWeek' 'System.Collections.Generic.IEnumerable`1 [[yyyy.ServiceCalendar,yyy.ChangeAD,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]]',
有关详细信息,请参阅内部异常。“}
我创建了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;
}
}
答案 0 :(得分: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
的类型定义无参数构造函数