문제

I have a class which inherits from a collection, specifically List<> and I've listed the class below. The problem I'm encountering when I serialize the object to XML using DataContractSerializer is the additional fields I've added within the object are not getting serialized by the serializer.
Here is the class:


[CollectionDataContract(Name = "ServiceEvents", Namespace = "")]
public class ServiceEventList : List<ServiceEvent> 
{
  [DataMember]
  public long StaleDate { get; set; }

  [DataMember]
  public long ExpirationDate { get; set; }
}

When I serialize the object and write to disk, here is the output (notice both StaleDate and ExpirationDate are missing).


<ServiceEvents xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><ServiceEvent><Date>2012-06-26T22:23:24.120817Z</Date><Description>A Service Event</Description><Id>634763462041210040</Id><Notes></Notes><Odometer>42</Odometer></ServiceEvent></ServiceEvents>

Here is the code that serializes the object:

using (FileStream fs = new FileStream(path, FileMode.Create))
{
  //TODO: StaleDate is not serializing to disk
  //TODO: ExpirationDate is not serializing to disk
  DataContractSerializer ser = new DataContractSerializer(typeof(ServiceEventList));
  ser.WriteObject(fs, list);
}

My next thought is to remove the inheritance structure and just embed a List object into the class. I'd prefer to just extend List but won't waste more time on it if the community confirms my approach won't work. Thanks in advance for the advice.

도움이 되었습니까?

해결책

According to this post:

http://social.msdn.microsoft.com/Forums/eu/wcf/thread/57eb195a-43a9-47fe-8b1a-a9d23feb2df2

the problem is indeed that you inherit from a collection type - in this case the DataContractSerializer serializes only its items, but not any extra properties.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top